MERGE对我无法找到答案的语法有疑问.
我有以下情况:
步骤1:
create temp table #TempTbl
Run Code Online (Sandbox Code Playgroud)
第二步MERGE:
MERGE INTO T1 target
USING T2 AS source ON (bunch of columns)
WHEN MATCHED
UPDATE
SET some columns from target equal some columns from source
WHEN NOT MATCHED BY TARGET
THEN INSERT (bunch of columns)
VALUES (bunch of columns from SOURCE)
OUTPUT $action, deleted.* into #TempTbl
Run Code Online (Sandbox Code Playgroud)
我需要知道的是,对于我的上述步骤,我不会在临时表中找到空数据#TempTbl,正如我所说WHEN NOT MATCHED ... THEN INSERT,不是DELETE吗?
第二个问题,应该$action是什么类型的列,因为我有错误消息:
列名或提供的值与表定义不匹配
虽然我试图从我的表都定义了第一列varchar(100),nvarchar(100)但没有运气.但是,如果我省略该$action字段,那么我的陈述可行.
因此,将保存$ action的列应该是nvarchar(10).
以下语句将为临时表添加行insert和update(因为更新实际上是删除后跟插入)但具有不同的操作:
-- sample test data
create table t1 (col1 int, col2 int)
create table t2 (col1 int, col2 int)
insert t1 values (1,1),(2,1)
insert t2 values (2,2),(3,3)
create table #temptbl (dml_action nvarchar(10), col1 int, col2 int)
-- merge statement
merge into t1 target
using t2 as source
on target.col1 = source.col1
when matched
then update set target.col2 = source.col2
when not matched by target
then insert (col1, col2) values (source.col2, source.col2)
output $action, inserted.col1, inserted.col2 into #temptbl ;
-- sample result
select * from #temptbl
dml_action col1 col2
---------- ----------- -----------
INSERT 3 3
UPDATE 2 2
Run Code Online (Sandbox Code Playgroud)
如果您不想要update行,则可以将整个批处理包装到另一个语句中,如下所示:
insert #temptbl (dml_action, col1, col2)
select dml_action, col1, col2
from
(
merge into t1 target
using t2 as source
on target.col1 = source.col1
when matched
then update set target.col2 = source.col2
when not matched by target
then insert (col1, col2) values (source.col2, source.col2)
output $action as dml_action, inserted.col1, inserted.col2
) a
where a.dml_action = 'INSERT'
Run Code Online (Sandbox Code Playgroud)