This question already has an answer here:
-
How to get last inserted id?
8 answers
I want to get the new created ID when you insert a new record in table.
I read this: http://msdn.microsoft.com/en-us/library/ms177564.aspx but it needs to create temporary table.
I want to return the ID after executing INSERT statement (assuming executing just one INSERT).
Example:
1 Joe Joe
2 Michael Mike
3 Zoe Zoe
When executing an INSERT statement, I want to return the created ID, means 4.
Can tell me how to do that using SQL statement or it is not possible ?
Solution
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven’t inserted another row – it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options – @@IDENTITY
and IDENT_CURRENT
– read more about how they works and in what way they’re different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
Related
The post Best Way to Get Identity of Inserted Row appeared first on Solved.