[英]Get Id after an INSERT in SQL Server in a multithread enviromment?
如何在SQL Server中插入INSERT后獲取id?
對於我的插入,我使用context.ExecuteStoreCommand()
警告:我有一個多線程應用程序,它在同一個表中“同時”插入一些數據。
SELECT SCOPE_IDENTITY()
在insert語句之后使用它,它將返回您在作用域中插入的標識。 您可以將此值分配給變量或將其返回到輸出參數中。
您應該將Scope_Identity()
用於此方案。 這將返回當前范圍的標識。 @@Identity
返回最后插入的標識。
查看MSDN上的Scope Identity - 有一些示例表明,與使用Scope_Identity
相比, @@Identity
將返回不正確的值
嘗試這個
@@identity
在示例代碼下面
strSQL = "INSERT INTO tablename (name) VALUES (@name);SELECT @@Identity"
SQLCommand.CommandText = strSQL
Id = SQLCommand.ExecuteScalar()
另一種實現方法是使用T-SQL語言的OUTPUT子句。
例如:
create table #tmpTable
(
ID int identity(1,1) not null primary key,
SomeValue varchar(20) not null
);
insert #tmpTable
output INSERTED.ID
values('SomeTextData')
drop table #tmpTable;
從整體解決方案設計的角度來看,我建議您將插入邏輯包裝到您從應用程序源代碼調用的存儲過程(返回插入的記錄ID)中。
INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');
我想你可以編寫一個存儲過程,它有一個輸入/輸出參數,然后從參數中獲取值。
我很確定如果需要身份值而不是ObjectContext.ExecuteStoreCommand ,你會想要使用ObjectContext.ExecuteStoreQuery方法。
您需要使用,因為其他人已經提到SCOPE_IDENTITY()
,而不是@@IDENTITY
因為SCOPE_IDENTITY()
返回當前執行范圍的標識值@@IDENTITY
“是一個返回最后插入的標識值的系統函數“。
像這樣的東西應該做的伎倆:
using(var context = GetAContextThatsReadyToUse())
{
var valueForColumn1 = 5;
var result = ExecuteStoreQuery<int>("INSERT INTO table1 (Column1) VALUES ({0});SELECT SCOPE_IDENTITY()", valueForColumn1);
foreach(var item in result)
{
// Should only return one result, which is the identity value inserted by ExecuteStoreQuery
Console.WriteLine(item);
}
}
我有很多情況,一次就有100個進程在一張桌子上寫。 我沒有使用SCOPE_IDENTITY()
而是將整個insert / ID fetch包裝到一個事務中,並且該方法沒有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.