Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an INSERT statement's OUTPUT clause to get the identity value?

People also ask

How do I get my identity back after insert?

The @@Identity function will return the last identity value inserted in the current session, in any table and in any scope.

How do I do an output statement in SQL?

To insert output clause result into a table , First declare a table variable to store the result of output clause ,and use the output caluse syntax to store the result into table variable . To accessing Inserted records, Output clause uses inserted virtual table that contains the new rows.

How can I get the last ID inserted in SQL?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.


You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.