5

例如,假设我有,

    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

4

2 回答 2

13

您不能使用传统INSERT输出未插入的字段。改用合并(警告:仅适用于数据库兼容性> = 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
于 2012-11-29T06:35:34.720 回答
1

如果要同时输出表中的以及从临时表中新创建ID的,则需要扩展该临时表以包含该列:ProductsID INT IDENTITYProducts.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 
于 2012-11-29T06:37:56.687 回答