Skip to content
Advertisement

Get back the id of each insert in SQL Server

Let’s say we want to insert two users and I want to know the userId of each record I inserted.

Example:

Db:

Setup, insert two users:

Insert statement:

This will return two usersIds, example 1 & 2. But how do I know which of the two users got which userId?

I can differentiate them in code with their ‘uniqueid’ I pass but I don’t know how to return it.

Advertisement

Answer

You can’t correlate the inserted rows with the database-assigned IDs, at least not without inserting an alternate key as well. INSERT … OUTPUT will not let you output a row that wasn’t actually inserted, so the column that correlates the un-keyed rows with the new key values has to be actually inserted.

So the options are:

  1. To use a SEQUENCE instead of IDENTITY and and either assign IDs to the table variable before insert, or assign IDs to the entities on the client, eg by calling sp_sequence_get_range.

  2. Use MERGE instead of INSERT. This is what Entity Framework Core does. See eg The Case of Entity Framework Core’s Odd SQL

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