sql - 获取 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?
我可以通过我通过的“唯一标识”在代码中区分它们,但我不知道如何返回它。
解决方案
不要只看output
id。您可以包括其他列:
insert into user.lookup (userName)
output inserted.*
select name from @users;
这是一个 db<>fiddle。
推荐阅读
- drupal - 无论如何检查Drupal中过去的日志?
- oracle - Tomcat to oracle channel 加密使用透明数据加密
- vue.js - 无法将 eva-icons 安装到 Vue-cli 项目
- if-statement - 以公式为条件的 if 子句
- ios - 无法使用本地化设置语言
- java - service.jar 中没有主要清单属性
- javascript - 使用 MS Graph 将 excel 转换为 pdf 返回错误文件
- java - java - 如何在具有3个表的记录的java中创建数据结构?
- python - 不理解这段代码的真假部分。我在此代码中的输入(所有整数)如何“为真”或“为假”?
- awk - 在新行中打印文件每列之前的第 1 列