Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to get the id of values I just INSERTed?

Tags:

sql-server

I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.

Can you tell me how to do it the right way?

like image 852
Niyaz Avatar asked Sep 05 '08 12:09

Niyaz


People also ask

How do I get my ID after insert?

There are multiple ways to get the last inserted ID after insert command. SCOPE_IDENTITY() : It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table.

How can I get just inserted record ID in SQL?

@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database. IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.


1 Answers

@@IDENTITY is not scope safe and will get you back the id from another table if you have an insert trigger on the original table, always use SCOPE_IDENTITY()

like image 69
SQLMenace Avatar answered Oct 07 '22 19:10

SQLMenace