2016-05-31 139 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