Inserting multiple rows with Merge NOT MATCHED

2019-09-05 16:11发布

问题:

MERGE tbl_target t
USING tbl_source s
ON t.itemnum = s.itemnum
WHEN NOT MATCHED 
    INSERT (itemnum, minqty, maxqty, parent)
    VALUES (s.itemnum,0,99,10),(s.itemnum,0,99,80);

I'm trying to Insert two rows on the target table if an item does not exist on target but does exist on the source. Everytime I try SQL server gives an error on the ',' between the VALUES.

A MERGE statement must be terminated by a semi-colon (;)

Is it possible to do multi-row inserts in a MERGE statement?

回答1:

It is possible by tweaking the USING clause to return multiple rows per tbl_source.itemnum value:

MERGE tbl_target t
USING (
  select s.itemnum, 
         0 as minqty, 
         99 as maxqty,
         p.parent 
    from tbl_source s
    cross join (
      select 10 as parent
      union all
      select 80 as parent) p
) s
ON t.itemnum = s.itemnum
WHEN NOT MATCHED THEN
    INSERT (itemnum, minqty, maxqty, parent)
    VALUES (s.itemnum,s.minqty,s.maxqty,s.parent);


回答2:

What I understand from msdn is that you can only insert a row for each non matching record. Do you need to use Merge? If not the following will work

WITH CTE (Sitemnum) 
AS 
(
    SELECT s.itemnum
    FROM tbl_source s
    LEFT JOIN tbl_target t ON (s.itemnum = t.itemnum)
    WHERE t.itemnum IS NULL
)
INSERT tbl_target
SELECT Sitemnum,0,99,10 
FROM CTE
UNION 
SELECT Sitemnum,0,99,80
FROM CTE