我有一个有效的 MySQL 查询,它为给定用户(与默认用户“admin”相同)更新或插入数据(多行)。它可以在 MySQL 中运行,但我很难将其转换为 Microsoft SQL Server 2012 等效项。
MySQL 查询是:
REPLACE INTO table_name (user, name, sub_name, display, html_div, display_order, good_low, good_high, critical_low, warning_low, warning_high, critical_high, last_updated)
SELECT 'user1', name, sub_name, display, html_div, display_order, good_low, good_high, critical_low, warning_low, warning_high, critical_high, last_updated
FROM table_name WHERE user = 'admin'
我尝试将其转换为 SQL Server 的是:
MERGE table_name AS TARGET
USING (SELECT 'user1', name, sub_name, display, html_div, display_order, good_low, good_high, critical_low, warning_low, warning_high, critical_high, last_updated FROM table_name WHERE [user] = 'admin')
AS SOURCE ([user], name, sub_name, display, html_div, display_order, good_low, good_high, critical_low, warning_low, warning_high, critical_high, last_updated)
ON TARGET.[user] = 'admin'
WHEN MATCHED THEN
UPDATE
SET [user] = 'user1', name = SOURCE.name, sub_name = SOURCE.sub_name, display = SOURCE.display, html_div = SOURCE.html_div, display_order = SOURCE.display_order, good_low = SOURCE.good_low, good_high = SOURCE.good_high, critical_low = SOURCE.critical_low, warning_low = SOURCE.warning_low, warning_high = SOURCE.warning_high, critical_high = SOURCE.critical_high, last_updated = SOURCE.last_updated
WHEN NOT MATCHED THEN
INSERT ([user], name, sub_name, display, html_div, display_order, good_low, good_high, critical_low, warning_low, warning_high, critical_high, last_updated)
VALUES ('user1', SOURCE.name, SOURCE.sub_name, SOURCE.display, SOURCE.html_div, SOURCE.display_order, SOURCE.good_low, SOURCE.good_high, SOURCE.critical_low, SOURCE.warning_low, SOURCE.warning_high, SOURCE.critical_high, SOURCE.last_updated);
我得到的错误是:
Msg 8672, Level 16, State 1, Line 1
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.
但是查询预计会更新多行,所以我想我在这里需要一些不同的东西。
您能帮我将此 MySQL 查询转换为等效的 SQL Server 吗?
最佳答案
MERGE 要求源行上有一个与目标中的行匹配的唯一值。否则它不知道要使用哪一个源行 - 它们可能不同!在这种情况下,您根本没有指定从 TARGET 到 SOURCE 的任何匹配。 ON TARGET.[user] = 'admin'
应类似于 ON TARGET.[user] = SOURCE.[user]
。每个源行应匹配一个(或多个目标行)。但每个目标行只能与一个源行匹配。
因此,您在 SOURCE 中创建“相似”行,然后将用户 ID 与目标表进行比较。如果用户已经存在,则将数据重写为相似的。否则插入一个新行。
关于mysql - SQL : How to convert REPLACE INTO . ... SELECT .... FROM 从 MySQL 到 SQL Server 的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207338/