gpt4 book ai didi

sql-server - SQL Server 中单行 MERGE/upsert 的语法

转载 作者:行者123 更新时间:2023-12-01 17:33:05 25 4
gpt4 key购买 nike

我正在尝试在表上执行单行插入/更新,但所有示例都是针对集合的。

任何人都可以修复我的语法吗:

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 的解决方案是将单行转换为子查询 - 这让我认为 MERGE 命令并不是真正用于单行更新插入。

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');

最佳答案

我终于在 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 (;).

关于sql-server - SQL Server 中单行 MERGE/upsert 的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2479488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com