Skip to content
Advertisement

Getting new IDs after insert

I’m inserting a bunch of new rows into a table which is defined as follows:

using the following insert:

when I’ve finished, I’d like to know the IDs of all the newly inserted rows. SCOPE_IDENTITY() only returns the ID last row inserted.

How can I get all the new IDs?

One method that springs to mind would be to grab the current largest identity from sometable and the scope_identity() post-insert, and use these two values to select from sometable. For example:

Is there a better pattern?

Advertisement

Answer

Use the OUTPUT functionality to grab all the INSERTED Id back into a table.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement