SQL Server中单行MERGE / upsert的语法
我试图做一个表单插入/更新,但所有的例子是有集。
任何人都可以修复我的语法:
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')
每个marc_s的解决scheme是将单行转换为子查询 – 这让我觉得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');
基本上,你是在正确的轨道上 – 但你错过了你想要合并数据的来源 – 尝试像这样:
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
子句中使用适当的条件,可以将源限制为单行 – 没有问题。
不要忘记后面的分号! 没有开玩笑 – 这很重要!
看到这个博客文章是一个很好的介绍MERGE
。
我终于在SQL Server 2008中使用MERGE
获得了Upsert语法。使用Jacob 想做的事(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 (;).