2010-03-19 101 views
53

我正在嘗試在表上執行單行插入/更新操作,但所有示例均爲集合。單行MERGE/upsert SQL Server中的語法

任何人都可以解決我的語法請:每marc_s

MERGE member_topic ON mt_member = 0 AND mt_topic = 110 
WHEN MATCHED THEN UPDATE SET mt_notes = 'test' 
WHEN NOT MATCHED THEN INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test') 

分辨率是單列轉換爲子查詢 - 這讓我想起了MERGE命令是不是真的打算單列upserts。

MERGE member_topic 
USING (SELECT 0 mt_member, 110 mt_topic) as source 
ON member_topic.mt_member = source.mt_member AND member_topic.mt_topic = source.mt_topic 
WHEN MATCHED THEN UPDATE SET mt_notes = 'test' 
WHEN NOT MATCHED THEN INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test'); 
+0

嗯,我的瀏覽器中這些行間隔如此接近,以至於某些下劃線未顯示。 – Jacob 2010-03-19 17:58:13

回答

42

基本上,你在正確的軌道上 - 但你缺少從您要合併的數據源 - 嘗試這樣的事:

MERGE 
    member_topic AS target 
USING 
    someOtherTable AS source 
ON 
    target.mt_member = source.mt_member 
    AND source.mt_member = 0 
    AND source.mt_topic = 110 
WHEN MATCHED THEN 
    UPDATE SET mt_notes = 'test' 
WHEN NOT MATCHED THEN 
    INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test') 
; 

沒有特殊的語法對於單行MERGE - 您需要做的就是使用適當的子句。通過ON條款中的適當條件,您可以將源限制爲單行 - 沒有問題。

而且不要忘記尾隨分號!沒有開玩笑 - 這很重要!

看到this blog postMERGE一個很好的介紹。

+6

我沒有someOtherTable。你是說我必須用這樣的東西模擬一個嗎? 使用(SELECT 0 mt_member,110 mt_topic)作爲源 – Jacob 2010-03-19 18:17:18

+0

@Jacob:你必須有一個源,是的 - 像你提到的子查詢應該沒問題 - 試試吧! – 2010-03-19 19:59:04

+5

對於這個答案困惑的人來說,看看[這個其他問題](http://stackoverflow.com/questions/11216067/what-is-using-in-sql-server-2008-merge-syntax)。 – 2012-11-26 19:13:29

88

我終於得到了使用SQL Server 2008中MERGE的語法的Upsert使用什麼雅各布做的(一個的Upsert):

IF EXISTS(SELECT * FROM member_topic WHERE mt_member = 0 AND mt_topic = 110) 
BEGIN 
    --update existing row 
    UPDATE member_topic SET mt_notes = 'test' 
    WHERE mt_member = 0 
    AND mt_topic = 110 
END 
ELSE 
BEGIN 
    --insert new row 
    INSERT INTO member_topic (mt_member, mt_topic, mt_notes) 
    VALUES (0, 110, 'test') 
END 

等效MERGE語法是:

MERGE member_topic 
USING ( 
    VALUES (0, 110, 'test') 
) AS foo (mt_member, mt_topic, mt_notes) 
ON member_topic.mt_member = foo.mt_member 
    AND member_topic.mt_topic = foo.mt_topic 
WHEN MATCHED THEN 
    UPDATE SET mt_notes = foo.mt_notes 
WHEN NOT MATCHED THEN 
    INSERT (mt_member, mt_topic, mt_notes) 
    VALUES (foo.mt_member, foo.mt_topic, foo.mt_notes) 
; --A MERGE statement must be terminated by a semi-colon (;). 
+8

在'WHEN NOT MATCHED THEN'子句中,爲什麼要插入'VALUES(mt_member,mt_topic,mt_notes)'而不是'VALUES(foo.mt_member,foo.mt_topic,foo.mt_notes)'? – 2013-10-18 16:18:48

+0

@SamP因爲爲什麼不呢?它是否像SQL Server將從某個位置*其他*比僞表'foo'獲取值?哦,等待...... – 2016-01-31 17:17:06

+0

不會在表中更新_all_行中的「UPDATE member_topic SET mt_notes ='test'」行嗎?不是什麼意圖。 – 2016-05-13 13:37:58