我试图在插入语句后得到一个键值。 例子: 我有一个表的属性名称和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
其他回答
*参数在连接字符串中的顺序有时很重要。* Provider参数的位置可以在添加一行后中断记录集游标。我们在SQLOLEDB提供程序中看到了这种行为。
添加行之后,行字段不可用,除非Provider被指定为连接字符串中的第一个参数。当提供程序位于连接字符串中的任何位置(除了第一个参数之外)时,新插入的行字段将不可用。当我们将提供者移动到第一个参数时,行字段神奇地出现了。
INSERT INTO files (title) VALUES ('whatever');
SELECT * FROM files WHERE id = SCOPE_IDENTITY();
这是最安全的选择,因为在带有触发器的表上存在OUTPUT子句冲突的已知问题。这使得它非常不可靠,即使你的表目前没有任何触发器-有人添加一个下线将破坏你的应用程序。像定时炸弹一样的行为。
详见msdn文章:
http://blogs.msdn.com/b/sqlprogrammability/archive/2008/07/11/update-with-output-clause-triggers-and-sqlmoreresults.aspx
不需要单独的SELECT…
INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');
这也适用于非identity列(比如guid)
您可以将选择语句附加到插入语句。 整数myInt = 插入到表1 (FName)值('Fred');选择Scope_Identity (); 这将在执行标量时返回一个标识的值。
这是我如何使用输出插入,当插入到一个表,使用ID作为标识列在SQL Server:
'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)