Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Id after an INSERT in SQL Server in a multithread enviromment?

How can I get id after an INSERT in SQL Server ?

For my insert, I use context.ExecuteStoreCommand()

Warning: I have a multi-threaded application which inserts "at the same time" some data in the same table.

like image 370
Patrice Pezillier Avatar asked Oct 12 '10 07:10

Patrice Pezillier


People also ask

How can I return ID after insert 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.

How do you insert multiple records to get the identity value?

Your options are using a cursor and taking the identity for each row you insert, or using Darren's approach of storing the identity before and after. So long as you know the increment of the identity this should work, so long as you make sure the table is locked for all three events.


1 Answers

SELECT SCOPE_IDENTITY()

Use this after your insert statement and it will return you the identity of inserted in your scope. You can assign this to variable or return it in an output parameter.

like image 74
Numenor Avatar answered Nov 15 '22 07:11

Numenor