我试图在插入语句后得到一个键值。 例子: 我有一个表的属性名称和id。Id是一个生成的值。
INSERT INTO table (name) VALUES('bob');
现在我想在同一步骤中取回id。这是怎么做到的?
我们使用的是Microsoft SQL Server 2008。
我试图在插入语句后得到一个键值。 例子: 我有一个表的属性名称和id。Id是一个生成的值。
INSERT INTO table (name) VALUES('bob');
现在我想在同一步骤中取回id。这是怎么做到的?
我们使用的是Microsoft SQL Server 2008。
当前回答
有多种方法可以获取插入命令后最后插入的ID。
@@IDENTITY : It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the value SCOPE_IDENTITY(): It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table. IDENT_CURRENT(‘TABLENAME’) : It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.
现在似乎更难决定哪一个能完全符合我的要求。
我更喜欢SCOPE_IDENTITY()。
如果在insert语句中使用select SCOPE_IDENTITY()和TableName,您将得到您所期望的确切结果。
来源:CodoBee
其他回答
您可以将选择语句附加到插入语句。 整数myInt = 插入到表1 (FName)值('Fred');选择Scope_Identity (); 这将在执行标量时返回一个标识的值。
最好和最可靠的解决方案是使用SCOPE_IDENTITY()。
你只需要在每次插入后获取作用域标识并将其保存在一个变量中,因为你可以在同一个作用域中调用两个插入。
Ident_current和@@identity可能是他们工作,但他们不是安全范围。在大型应用程序中可能会出现问题
declare @duplicataId int
select @duplicataId = (SELECT SCOPE_IDENTITY())
更多细节在这里微软文档
有多种方法可以获取插入命令后最后插入的ID。
@@IDENTITY : It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the value SCOPE_IDENTITY(): It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table. IDENT_CURRENT(‘TABLENAME’) : It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.
现在似乎更难决定哪一个能完全符合我的要求。
我更喜欢SCOPE_IDENTITY()。
如果在insert语句中使用select SCOPE_IDENTITY()和TableName,您将得到您所期望的确切结果。
来源:CodoBee
使用SCOPE_IDENTITY()获取新的ID值
INSERT INTO table (name) VALUES('bob');
SELECT SCOPE_IDENTITY()
http://msdn.microsoft.com/en-us/library/ms190315.aspx
实体框架执行类似于gbn的答案:
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO Customers(FirstName)
OUTPUT inserted.CustomerID INTO @generated_keys
VALUES('bob');
SELECT t.[CustomerID]
FROM @generated_keys AS g
JOIN dbo.Customers AS t
ON g.Id = t.CustomerID
WHERE @@ROWCOUNT > 0
输出结果存储在临时表变量中,然后选择返回给客户端。你必须意识到这一点:
insert可以生成多行,因此变量可以保存多行,因此可以返回多个ID
我不知道为什么EF会将临时表内部连接回实际表(在什么情况下两者会不匹配)。
但英孚就是这么做的。
仅支持SQL Server 2008或更新版本。如果是2005年,那你就不走运了。