簡體   English   中英

SQL Server:使用輸出子句插入批處理

[英]SQL Server: Insert batch with output clause

我正在嘗試以下

  1. 使用表值參數(tvp)將記錄數插入表A 此電視有不在A額外列
  2. A獲取插入的ID,並在TVP中獲取相應的額外列,然后將其添加到另一個表B

這是我嘗試過的

類型:

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/zh-cn/library/ms177564.aspx )不接受其他表中的列。

from_table_name是列前綴,用於指定DELETE,UPDATE或MERGE語句的FROM子句中包含的表,該表用於指定要更新或刪除的行。

那么還有其他方法可以實現這一目標嗎?

您不能使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM