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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With