我试图在插入语句后得到一个键值。 例子: 我有一个表的属性名称和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

其他回答

在插入一个带有identity列的表之后,你可以引用@@IDENTITY来获取值: http://msdn.microsoft.com/en-us/library/aa933167%28v=sql.80%29.aspx

有多种方法可以获取插入命令后最后插入的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值,而不是使用“OUTPUT Inserted”。ID”

如果插入语句抛出异常,我将直接抛出它。而是“输出插入”。ID”将返回0,这可能与预期不同。

您可以将选择语句附加到插入语句。 整数myInt = 插入到表1 (FName)值('Fred');选择Scope_Identity (); 这将在执行标量时返回一个标识的值。

有很多方法可以在插入后退出

在向表中插入数据时,可以使用OUTPUT子句 返回已插入到表中的数据的副本。的 OUTPUT子句有两种基本形式:OUTPUT和OUTPUT INTO。使用 如果希望将数据返回给调用应用程序,则使用OUTPUT表单。 如果希望将数据返回到表或表中,则使用OUTPUT INTO表单 表变量。

DECLARE @MyTableVar TABLE (id INT,NAME NVARCHAR(50));

INSERT INTO tableName
(
  NAME,....
)OUTPUT INSERTED.id,INSERTED.Name INTO @MyTableVar
VALUES
(
   'test',...
)

IDENT_CURRENT:它返回在任何会话中为特定表或视图创建的最后一个标识。

SELECT IDENT_CURRENT('tableName') AS [IDENT_CURRENT]

SCOPE_IDENTITY:它返回同一个会话和同一个作用域的最后一个标识。作用域是存储过程/触发器等。

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];  

@@IDENTITY:返回同一会话的最后一个标识。

SELECT @@IDENTITY AS [@@IDENTITY];