简体   繁体   中英

SQL Server: Insert batch with output clause

I'm trying the following

  1. Insert number of records to table A with a table-valued parameter (tvp). This tvp has extra column(s) that are not in A
  2. Get the inserted ids from A and the corresponding extra columns in the the tvp and add them to another table B

Here's what I tried

Type:

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

Tables:

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]
);

Insert:

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

However, this fails with The multi-part identifier "a.otherid" could not be bound. , which I guess is expected because columns from other tables are not accepted for INSERT statement ( https://msdn.microsoft.com/en-au/library/ms177564.aspx ).

from_table_name Is a column prefix that specifies a table included in the FROM clause of a DELETE, UPDATE, or MERGE statement that is used to specify the rows to update or delete.

So is there any other way to achieve this?

You cannot select value from a source table by using INTO operator. Use OUTPUT clause in the MERGE command for such cases.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM