Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Return value after INSERT

I'm trying to get a the key-value back after an INSERT-statement. Example: I've got a table with the attributes name and id. id is a generated value.

    INSERT INTO table (name) VALUES('bob'); 

Now I want to get the id back in the same step. How is this done?

We're using Microsoft SQL Server 2008.

like image 207
melbic Avatar asked Oct 27 '11 14:10

melbic


People also ask

How can I get data after insert in SQL?

SQL Server provides four ways to retrieve the newly generated identity value after rows have been inserted into a table: @@Identity. Scope_Identity() Ident_Current()

What does SQL return after insert?

An SQL INSERT statement writes new rows of data into a table. If the INSERT activity is successful, it returns the number of rows inserted into the table. If the row already exists, it returns an error. Multiple rows can be inserted into a table.

How can I get auto increment value after insert in SQL Server?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

How do I get the last inserted identity column value in SQL Server?

We use SCOPE_IDENTITY() function to return the last IDENTITY value in a table under the current scope. A scope can be a module, trigger, function or a stored procedure. We can consider SQL SCOPE_IDENTITY() function similar to the @@IDENTITY function, but it is limited to a specific scope.


2 Answers

No need for a separate SELECT...

INSERT INTO table (name) OUTPUT Inserted.ID VALUES('bob'); 

This works for non-IDENTITY columns (such as GUIDs) too

like image 119
gbn Avatar answered Oct 11 '22 02:10

gbn


Use SCOPE_IDENTITY() to get the new ID value

INSERT INTO table (name) VALUES('bob');  SELECT SCOPE_IDENTITY() 

http://msdn.microsoft.com/en-us/library/ms190315.aspx

like image 30
Curtis Avatar answered Oct 11 '22 04:10

Curtis