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.
- 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)
Let us check the table contents.
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
Let us check the output. Execute the below query.
As we can see the values have been swapped between the two columns. Swapping in SQL is pretty easy.