Friday, July 24, 2015

Swap the values of two columns in SQL Server

 Do you have fun with SQL Server?. Let's start 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 Customer 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?
  1. SELECT * FROM CUSTOMER

Don't worry, to do this task, you need to just write a simple update query for Customer table like as :
  1. UPDATE Customer SET Name=Address , Address=Name
Now After query execution you will find the the values of columns Name and Address have been interchanged, that's so cool.
  1. SELECT * FROM CUSTOMER

Note

  1. Data type of both the columns should be same and also length should be enough to hold the swapped column data other wise data will be truncated.
Resources:-
http://www.dotnet-tricks.com/Tutorial/sqlserver/PW8W071112-Swap-the-values-of-two-columns-in-SQL-Server.html

No comments:

Post a Comment