使用Merge NOT MATCHED插入多行

时间:2016-09-15 21:18:42

标签: sql-server tsql merge

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

我尝试在目标表上插入两行,如果某个项目在目标上不存在但在源上存在。每次我尝试SQL服务器都会在'上发生错误,' VALUES之间。

MERGE语句必须以分号(;)

结束

是否可以在MERGE语句中执行多行插入?

2 个答案:

答案 0 :(得分:3)

可以通过调整USING子句来返回每tbl_source.itemnum个值的多行:

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

答案 1 :(得分:1)

我对msdn的理解是,您只能为每个不匹配的记录插入一行。你需要使用Merge吗?如果不是,以下方法将起作用

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