Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap values for two rows in the same table in SQL Server

Tags:

sql

sql-server

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
like image 547
Amr Elnashar Avatar asked May 03 '10 13:05

Amr Elnashar


People also ask

How do you interchange in SQL?

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.

What is GROUP BY 2 in SQL?

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.

How do you update multiple values in one column in SQL?

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.


2 Answers

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)
like image 141
KM. Avatar answered Sep 21 '22 17:09

KM.


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.

like image 32
Israel Margulies Avatar answered Sep 21 '22 17:09

Israel Margulies