SQL Server:使用output子句插入批处理

时间:2016-10-18 04:46:29

标签: sql sql-server

我正在尝试以下

  1. 使用表值参数(tvp)将记录数插入表A。此tvp具有不在A
  2. 中的额外列
  3. A获取插入的ID以及tvp中相应的额外列,并将其添加到另一个表B
  4. 这是我试过的

    类型:

    CREATE TYPE tvp AS TABLE
    (
        id int,
        otherid int,
        name nvarchar(50),
        age int
    );
    

    表:

    CREATE TABLE A (
        [id_A] [int] IDENTITY(1,1) NOT NULL,
        [name] [varchar](50),
        [age] [int]
    );
    
    CREATE TABLE B (
        [id_B] [int] IDENTITY(1,1) NOT NULL,
        [id_A] [int],
        [otherid] [int]
    );
    

    插入:

    DECLARE @a1 AS tvp;
    DECLARE @a2 AS tvp
    
    -- create a tvp (dummy data here - will be passed to as a param to an SP)
    INSERT INTO @a1 (name, age, otherid) VALUES ('yy', 10, 99999), ('bb', 20, 88888);
    
    INSERT INTO A (name, age) 
    OUTPUT 
        inserted.id_A, 
        inserted.name, 
        inserted.age, 
        a.otherid -- <== isn't accepted here
    INTO @a2 (id, name, age, otherid)
    SELECT name, age FROM @a1 a;
    
    INSERT INTO B (id_A, otherid) SELECT id, otherid FROM @a2
    

    但是,The multi-part identifier "a.otherid" could not be bound.失败了,我猜这是预期的,因为INSERT语句(https://msdn.microsoft.com/en-au/library/ms177564.aspx)不接受来自其他表的列。

      

    from_table_name   是一个列前缀,用于指定DELETE,UPDATE或MERGE语句的FROM子句中包含的表,该语句用于指定要更新或删除的行。

    有没有其他方法可以实现这个目标?

1 个答案:

答案 0 :(得分:1)

您无法使用 INTO 运算符从源表中选择值。 对于此类情况,请在 MERGE 命令中使用OUTPUT子句。

DECLARE @a1 AS tvp;
DECLARE @a2 AS tvp

INSERT INTO @a1 (name, age, otherid) VALUES ('yy', 10, 99999), ('bb', 20, 88888);


MERGE A a
USING @a1 a1
ON a1.id =a.[id_A]
WHEN NOT MATCHED THEN
INSERT (name, age) 
     VALUES (a1.name, a1.age)
OUTPUT inserted.id_A, 
      a1.otherId,
      inserted.name, 
      inserted.age 
     INTO @a2;


INSERT INTO B (id_A, otherid) SELECT id, otherid FROM @a2