How do I get the Identity field that results from an insert?

别等时光非礼了梦想. 提交于 2020-02-03 08:43:29

问题


I'm going to insert data into a table like so:

Insert Into MyTable (Field1, Field2)
           Values   ('test', 5)

When that insert occurs, the new row is going to have an identify value in the ID column. If have a variable called @ID in my T-SQL code, how do I populate @ID with the result of the T-SQL Insert?

Declare @ID int

Insert into MyTable (Field1, Field2)
             Values ('test', 5)

--//How do I populate @ID with the value of ID of the record that was just inserted?

回答1:


There are two ways - the first is to use SCOPE_IDENTITY:

DECLARE @ID INT

INSERT INTO MyTable (Field1, Field2)
VALUES ('test', 5)

SELECT @ID = SCOPE_IDENTITY() 

Don't use @@IDENTITY -- the value it contains is for the last updated IDENTITY column without regard for scope. Meaning, it's not reliable that it holds the value for your INSERT, but SCOPE_IDENTITY does.

The other alternative is to use the OUTPUT clause (SQL Server 2005+).




回答2:


SELECT @ID = SCOPE_IDENTITY();



回答3:


You should use scope_identity in your case.

There are different ways to get last inserted identity and they differ in how they work just for your information listing them -

  1. @@IDENTITY

  2. SCOPE_IDENTITY()

  3. IDENT_CURRENT

  4. OUTPUT CLAUSE (came to know about it from @OMG Ponies answer)

Consider the differences and comparisons between them before deciding which one to use.



来源:https://stackoverflow.com/questions/4157142/how-do-i-get-the-identity-field-that-results-from-an-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!