Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 428
Ben McCormack Avatar asked Nov 30 '22 09:11

Ben McCormack


2 Answers

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+).

like image 169
OMG Ponies Avatar answered Dec 04 '22 09:12

OMG Ponies


SELECT @ID = SCOPE_IDENTITY();
like image 23
Neil Knight Avatar answered Dec 04 '22 07:12

Neil Knight