Pages

Sunday, 15 July 2012

HOW TO SWAP TABLE COLUMN VALUES IN SQL:

Initially we are creating an temporary table with two columns c1 and c2 with tinyint data type.
create table #swap_data
(c1 tinyint,
c2  tinyint);

The command(s) completed successfully.

Now we are going to insert some sample data into the temporary table.

insert into #swap_data values (1,10)
insert into #swap_data values (2,20)
insert into #swap_data values (3,30)
insert into #swap_data values (4,40)
insert into #swap_data values (5,50)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

We are going to query the data from the temporary table.

select * from #swap_data
c1   c2  
---- ----
1    10
2    20
3    30
4    40
5    50
(5 row(s) affected)

This involves the concept of all at once operation
Logically, you should assume that the whole operation takes place at once.
It is as if the table is not modified until the whole operation finishes and then the result replaces the source.

This is the simple sql command to swap table column values

update #swap_data set c1=c2,c2=c1

(5 row(s) affected)

After update the table now once again we are going to query the same table.
select * from #swap_data
c1   c2  
---- ----
10   1
20   2
30   3
40   4
50   5
(5 row(s) affected)

Yes the table column values are swaped.

No comments:

Post a Comment