如何使用OUTPUT捕获新旧ID?

时间:2012-11-29 06:26:42

标签: sql sql-server sql-server-2008

例如,假设我有,

    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

2 个答案:

答案 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