I'm using SQL Server to swap two values in two rows. Let me show:
[ord] [name]
1 John
4 Jack
7 Pete
9 Steve
11 Mary
Say, I need to swap [ord] numbers for "Pete" and "Steve" to make this table to be like so:
[ord] [name]
1 John
4 Jack
9 Pete
7 Steve
11 Mary
This seems like a trivial task but I can't seem to write an SQL UPDATE statement for it.
Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.
Can we UPDATE multiple tables with a single SQL query? No, only 1 table can be updated with an UPDATE statement.
If 'Peter'
and 'Steve'
are unique in your table, this will do:
UPDATE TableX
SET ord = ( SELECT MIN(ord) + MAX(ord)
FROM TableX
WHERE name IN ('Peter', 'Steve')
) - ord
WHERE name IN ('Peter', 'Steve')
or (improved by @Erwin):
UPDATE TableX
SET ord = ( SELECT SUM(ord)
FROM TableX
WHERE name IN ('Peter', 'Steve')
) - ord
WHERE name IN ('Peter', 'Steve')
Use a CASE expression:
UPDATE yourtable
SET [ord] = CASE [ord] WHEN 9 THEN 7
WHEN 7 THEN 9 END
WHERE [ord] IN (7, 9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With