小编典典

如何使用OUTPUT捕获新旧ID?

sql

例如,假设我有,

    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


阅读 216

收藏
2021-03-10

共1个答案

小编典典

您不能使用传统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
2021-03-10