SQL Server 中插入的 ID 列表 [英] List of inserted ID in SQL Server

查看:87
本文介绍了SQL Server 中插入的 ID 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表变量

@temp (tmpId, c1, c2, c3, d1, d2, d3)

我想将行从@temp 插入到具有称为 ID 的标识列的表 (MyTable) 中,并将已插入的 ID 分配给 @temp 中的行.我知道可以使用 OUTPUT 子句检索插入的 id 列表.

I want to insert rows from @temp to a table (MyTable) having identity column called ID and assign the isnerted IDs to the rows in @temp. I know that the list of inserted ids can be retrieve using OUTPUT clause.

INSERT INTO MyTABLE (c1, c2, c3)
OUTPUT INSERTED.id, INSERTED.c1, ... INTO @IDs (id, c1, ...)
SELECT (c1, c2, c3)

尽管有@IDs 表,我无法将插入的 id 分配给 tmpIds,因为 c1、c2、c3 列不是唯一的.我需要 Id 将 d1、d2、d3 列插入另一个表.我脑子里只有一个解决办法.一一插入行并使用 SCOPE_IDENTITY() 检索 id.但我想避免使用循环.知道如何一步插入这些行吗?

Dispite having @IDs table I can not assigne the inserted ids to the tmpIds because the c1, c2, c3 columns are not unique. I need the Ids to insert d1, d2, d3 columns to another table. I have only one solution in my mind. Inserting rows one by one and retrieving id with SCOPE_IDENTITY(). But I'd like to aviod using loop. Any idea how to insert these rows in one step?

推荐答案

尝试将源行与插入的标识值链接起来的合并技巧:

Try merge trick with linking source rows with inserted identity values:

merge MyTABLE t
using @temp s
on 1=0
when not mathed then
insert ...
output inserted.ID, s.tempID 
into @linked_ids(id1, id2);

这篇关于SQL Server 中插入的 ID 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆