How to Swap Values of Two Columns in SQL Server

Introduction

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

A few things need to be kept in mind while doing this; the two columns should have the same data type, and the length should be good enough to hold the swapped value; otherwise, the data would be truncated. Let us see one practical demonstration of the same.

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

create table Student  
(  
StudentID Int identity primary key,  
FirstName varchar(30),  
LastName varchar(30),  
Marks Int  
)  
  
Insert into Student(FirstName,LastName,Marks) Values('Nitin','Tyagi',400)  
Insert into Student(FirstName,LastName,Marks) Values('Ajay','Sharma',300)  
Insert into Student(FirstName,LastName,Marks) Values('Vikrant','Sharma',100)  

code

Let us check the table contents.

Select * from Student 

table

Let us now swap the values of FirstName and LastName. Write the following query to achieve the same.

Update Student Set FirstName=LastName,LastName=FirstName  

code

Let us check the output. Execute the below query.

Select * from Student  

table

Summary

As we can see, the values have been swapped between the two columns. Swapping in SQL is pretty easy. 

Reference