2016-05-31 142 views
0

对于我找不到答案的MERGE语法有个问题。MERGE语法SQL Server 2012错误

我有以下情况:

第一步:

create temp table #TempTbl 

第二步: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 

我需要知道的是我上面的步骤不会我只找到空数据在我的临时表中#TempTbl,因为我只说WHEN NOT MATCHED ... THEN INSERT,而不是DELETE

第二个问题,什么类型的列应该$action是,因为我有错误消息:

列名或提供的值不匹配表定义

虽然我试图从我的表中定义第一列varchar(100),nvarchar(100),但没有运气。但是,如果我省略了$action字段,那么我的声明就有效。

+0

'@ action'必须是相同的数据类型作为你的第一列'#TempTbl'。要存储'deleted'的东西,你必须删除一些东西 - 比如'当源不匹配时候THEN DELETE' – gofr1

+0

@BogdanM你想存储更改和/或插入的值吗? – jpw

+0

好的,应该是什么类型?正如我写的,我已经尝试过,但没有运气 – BogdanM

回答

5

所以,这将举行$行动列应该是nvarchar(10)

下面的语句将行添加到临时表中两个insertupdate(作为更新的确是一个删除后插入),但不同的操作:

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

如果你不想在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' 
+2

很多,非常感谢。祝你有美好的一天:)。问候, – BogdanM