tags:

views:

258

answers:

3

I have table and I want to swap the values from two rows. 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

I don't want write it in .NET code because I think an SQL query is easier than that.

A: 

Like this recent question?

Copy row to another row in same table and vise versa Sql Server?

gbn
+1  A: 

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)
KM
Thanks KM is this query works with multiple rows means if those IDs are forign keys and i need to swap their rows.
Amr Elnashar
this should work if the columns to swap are foreign keys or just plain data.
KM