I want to swap the values from two rows in a table. I have the rows IDs of the two rows. Is there any query to do that? Here is an example. Before the query I have this:
row1 : 1,2,3 row2 : 5,6,7
After the swap I want this:
row1 : 5,6,7 row2 : 1,2,3
Introduction (Swap Column Values in SQL Server) : If you are a developer and have learned the programming languages, you might think that you will need a third variable or another temporary storage location to swap the values. Here, as you are a SQL Server DBA, you can simply swap them using a single update statement.
The group by multiple columns technique is used to retrieve grouped column values from one or more tables of the database by considering more than one column as grouping criteria. We use SQL queries to group multiple columns of the database.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
If you want to swap values from one row to the other for two known IDs try something like this:
--need to store the original values
SELECT
*,CASE WHEN id=123 then 987 ELSE 123 END AS JoinId
INTO #Temp
FROM YourTable
WHERE ID in (123,987)
--swap values
UPDATE y
SET col1=t.col1
,col2=t.col2
FROM YourTable y
INNER JOIN #Temp t ON y.id =t.JoinId
WHERE ID in (123,987)
Simple update works:
UPDATE myTable
SET
col1 = CASE WHEN col1 = 1 THEN 5 ELSE 1 END,
col2 = CASE WHEN col2 = 2 THEN 6 ELSE 2 END,
col3 = CASE WHEN col3 = 3 THEN 7 ELSE 3 END
Result: row values are swapped.
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