SQL 服务器中插入的 ID 列表
List of inserted ID in SQL Server
我有一个 table 变量
@temp (tmpId, c1, c2, c3, d1, d2, d3)
我想将@temp 中的行插入到具有名为ID 的标识列的table (MyTable),并将插入的ID 分配给@temp 中的行。我知道可以使用 OUTPUT 子句检索插入的 ID 列表。
INSERT INTO MyTABLE (c1, c2, c3)
OUTPUT INSERTED.id, INSERTED.c1, ... INTO @IDs (id, c1, ...)
SELECT (c1, c2, c3)
尽管有 @IDs table 我不能将插入的 IDs 分配给 tmpIds,因为 c1、c2、c3 列不是唯一的。我需要 ID 将 d1、d2、d3 列插入另一个 table。
我脑子里只有一个解决方案。逐行插入行并使用 SCOPE_IDENTITY() 检索 id。但我想避免使用循环。
知道如何一步插入这些行吗?
尝试使用合并技巧将源行与插入的标识值链接起来:
merge MyTABLE t
using @temp s
on 1=0
when not mathed then
insert ...
output inserted.ID, s.tempID
into @linked_ids(id1, id2);
我有一个 table 变量
@temp (tmpId, c1, c2, c3, d1, d2, d3)
我想将@temp 中的行插入到具有名为ID 的标识列的table (MyTable),并将插入的ID 分配给@temp 中的行。我知道可以使用 OUTPUT 子句检索插入的 ID 列表。
INSERT INTO MyTABLE (c1, c2, c3)
OUTPUT INSERTED.id, INSERTED.c1, ... INTO @IDs (id, c1, ...)
SELECT (c1, c2, c3)
尽管有 @IDs table 我不能将插入的 IDs 分配给 tmpIds,因为 c1、c2、c3 列不是唯一的。我需要 ID 将 d1、d2、d3 列插入另一个 table。 我脑子里只有一个解决方案。逐行插入行并使用 SCOPE_IDENTITY() 检索 id。但我想避免使用循环。 知道如何一步插入这些行吗?
尝试使用合并技巧将源行与插入的标识值链接起来:
merge MyTABLE t
using @temp s
on 1=0
when not mathed then
insert ...
output inserted.ID, s.tempID
into @linked_ids(id1, id2);