I have a working MySQL query which updates or inserts the data (multiple rows) for a given user same as default user 'admin'. It works in MySQL but I am having hard time converting it into Microsoft SQL Server 2012 equivalent.
The MySQL query is:
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'
What I tried to convert this into SQL Server is:
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);
I get error as:
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.
But the query is expected to update multiple rows, so I think I need something different here.
Can you please help me to convert this MySQL query into it's equivalent SQL Server?