首页 > 解决方案 > 获取 SQL Server 中每个插入的 id

问题描述

假设我们要插入两个用户,并且我想知道我插入的每条记录的 userId。

例子:

D b:

User.lookup database with these columns:
UserId(PK, identity) | Username

设置,插入两个用户:

declare @users table (uniqueId INT, name nvarchar(100));
insert into @users (0, 'TestUser')--Two users with the same name, they'll get a different userid in the db
insert into @users (1, 'TestUser')--Uniqueid is just an autonumber I use to tell the difference between them.

插入语句:

insert into user.lookup (userName)
output inserted.userid
select name from @users;

这将返回两个用户 ID,例如 1 和 2。但是我如何知道两个用户中的哪个用户获得了哪个用户 ID?

我可以通过我通过的“唯一标识”在代码中区分它们,但我不知道如何返回它。

标签: sqlsql-serverinsertoutput

解决方案


不要只看outputid。您可以包括其他列:

insert into user.lookup (userName)
    output inserted.*
    select name from @users;

是一个 db<>fiddle。


推荐阅读