我正在使用 SqlCommand
,如下所示:
command.CommandText = "INSERT INTO ... VALUES ...; SELECT SCOPE_IDENTITY();";
这够了吗,还是我需要 BEGIN TRAN
等? (提到 here 。)
当然,我首先尝试了它,而且效果很好。但是即使有两个同时插入,它能正常工作吗? (而且我不确定如何测试那个。)
最佳答案
您不需要BEGIN TRAN
。 Scope_Identity()
没有它也能正常工作。即使有“同时插入”。这就是该函数的全部要点——仅返回当前范围的答案。
请注意,在低于 SQL Server 2012 的版本中,并行性可能会破坏 Scope_Identity()
,因此您必须使用查询提示 WITH (MAXDOP 1)
在你的 INSERT
语句上,如果你想让它在 100% 的时间内正常工作。你可以read about this problem on Microsoft Connect . (在 SQL Server 2008 R2 Service Pack 1 的累积更新包 5 中是 theoretically fixed,但有些人似乎认为这可能不是 100% 正确)。
SQL Server 2005 及更高版本中还有 OUTPUT
子句,这是返回有关 INSERT
的数据的另一种方式,可以通过向客户端发送行集或通过输出到表格。请注意,接收行集并不能真正证明 INSERT
已正确提交...因此您可能应该在存储过程中使用 SET XACT_ABORT ON;
。以下是 OUTPUT
的示例:
CREATE TABLE @AInsert(IDColumn);
INSERT dbo.TableA (OtherColumn) -- not the identity column
OUTPUT Inserted.IDColumn -- , Inserted.OtherColumn, Inserted.ColumnWithDefault
INTO @AInsert
SELECT 'abc';
-- Do something with @AInsert, which contains all the `IDColumn` values
-- that were inserted into the table. You can insert all columns, too,
-- as shown in the comments above
关于c# - 是否需要 "BEGIN TRAN"才能获得正确的 SCOPE_IDENTITY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076417/