例如,假设我有,
create table product
(
ID INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(10)
)
insert into product(Name) values('a')
insert into product(Name) values('b')
insert into product(Name) values('c')
insert into product(Name) values('d')
insert into product(Name) values('e')
create table #tempproduct
(
ID INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(10)
)
declare @OutputAttributesValues table
(
[NewID] INT,
[OldID] INT
)
insert into #tempproduct(Name)
OUTPUT INSERTED.[ID],[ID] INTO @OutputAttributesValues
select [Name] FROM product
请参阅我需要从输出中获取旧ID和新ID。但是这个sql给了我错误“无效的列名'ID'。” http://sqlfiddle.com/#!3/a27b2/1
答案 0 :(得分:10)
您无法使用传统的INSERT
输出未插入的字段。
请改用merge(警告:仅适用于数据库兼容性> = 100):
MERGE
#tempproduct AS t
USING(
SELECT
Name
, ID
FROM
product) AS s
ON (1=0)
WHEN NOT MATCHED
THEN INSERT (Name) VALUES (Name)
OUTPUT inserted.ID, s.ID INTO @OutputAttributesValues;
SELECT * FROM @OutputAttributesValues
答案 1 :(得分:1)
如果要输出ID
表中的Products
以及临时表中新创建的ID INT IDENTITY
,则需要扩展该临时表以包含Products.ID
列也是:
create table #tempproduct
(
ID INT IDENTITY(1,1) NOT NULL,
OldID INT,
Name VARCHAR(10)
)
declare @OutputAttributesValues table
(
[NewID] INT,
[OldID] INT
)
insert into #tempproduct(OldID, Name)
OUTPUT INSERTED.[ID], Inserted.OldID INTO @OutputAttributesValues
select ID, [Name] FROM product