How to Swap Values of Two Columns in SQL Server

Well let’s see how easy it is to do such a thing.

There are a few things that need to be kept in mind while doing this; the two columns should have the same datatype and the length should be good enough to hold the swapped value otherwise the data would be truncated. Let us see one practical demonstration for the same.

Let us create a table with the following structure and insert few records in the same.

  1. create table Student  
  2. (  
  3. StudentID Int identity primary key,  
  4. FirstName varchar(30),  
  5. LastName varchar(30),  
  6. Marks Int  
  7. )  
  8.   
  9. Insert into Student(FirstName,LastName,Marks) Values('Nitin','Tyagi',400)  
  10. Insert into Student(FirstName,LastName,Marks) Values('Ajay','Sharma',300)  
  11. Insert into Student(FirstName,LastName,Marks) Values('Vikrant','Sharma',100)  
code


Let us check the table contents.
  1. Select * from Student 

 

 table
 
Let us now swap the values of FirstName and LastName. Write the following query to achieve the same.
  1. Update Student Set FirstName=LastName,LastName=FirstName  
code

Let us check the output. Execute the below query.
  1. Select * from Student  
table
As we can see the values have been swapped between the two columns. Swapping in SQL is pretty easy.