Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I have a table with data like something as -

id1 id2
1 5
2 8
3 6

Output like -

id1 id2
5 1
8 2
6 3

I want to swap value all values of 1st column in 2nd column and 2 columns value into 1st column.
Posted
Updated 1-Aug-13 2:43am
v3
Comments
What have you tried?

 
Share this answer
 
Comments
Maciej Los 1-Aug-13 8:57am    
I prefer second link ;)
+5 for links...
Adarsh chauhan 1-Aug-13 8:59am    
Good Links.. +5
[no name] 1-Aug-13 9:08am    
Thanks Maciej Los and Adarsh chauhan
Hi,

try this

create table test
(
col1 int,
col2 int
)

insert into test values(1,4),(10,5),(2,10),(5,9)


simple one

select * from test

UPDATE test SET col1=col2, col2=col1

select * from test



Now the complex one ;)
select * from test

update t1
set t1.col1=t2.c1,t1.col2=t2.c2
from test t1
join
(
select col2 as c1,col1 as c2 from test
)t2
on t1.col1=t2.c2

select * from test
 
Share this answer
 
if you just want to display the value at column2 in place of column1 and visa versa then can simply fetch data as

select id2 as 'id1',id1 as 'id2' from table
 
Share this answer
 
It's simple:
SQL
DECLARE @tmp TABLE (id1 INT, id2 INT)
INSERT INTO @tmp (id1, id2)
SELECT 1, 5
UNION ALL SELECT 2, 8
UNION ALL SELECT 3, 6

UPDATE t1
    SET t1.id1 = t2.id2,
        t1.id2 = t2.id1
FROM @tmp AS t1 INNER JOIN @tmp AS t2 ON t1.id1 = t2.id1

SELECT *
FROM @tmp
 
Share this answer
 
SQL
IF(SELECT OBJECT_ID('TEMPDB..#TEM')) IS NOT NULL
DROP TABLE #TEM
SELECT TOP 0 * INTO #TEM  FROM TABLENAME


INSERT INTO #TEM SELECT id2,ID1 FROM TABLENAME
SELECT * FROM #TEM
 
Share this answer
 
try this...:)

SQL
UPDATE tableName SET Column1=Column2, Column2=Column1
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900