Saturday, 7 September 2013

Swap the values of two columns in SQL Server

 
Do you have fun with SQL Server?.
Suppose you want to swap the values of two columns of a table in SQL Server, how could you achieve this tricky task?. Actually, it is simple and so funny.
 
Suppose you have a Persons table in the database with the following data and you want to interchange the values of columns Name and Address then how do you do?

Query :

 Before swapping :
select * from [testdb1].[dbo].[persons]


P_Id       LastName            FirstName           Addr         City
1              Kulkarni                Nihar                     Pune        India
2              Gates                    Bill                          San Jose   US


After swapping :

update [testdb1].[dbo].[persons]
set [Addr]=[City],[City]=[Addr]
 
P_Id       LastName            FirstName           Addr      City
1              Kulkarni                Nihar                     India      Pune
2              Gates                    Bill                          US          San Jose
 
 
Time pass Solution. ..bt needful !!!!!
I know to tooooo simple solutions , but sometimes we forget ...
Enjoy..!!
 
 
 

No comments:

Post a Comment