How to Swap Two column values of a table whose data types are same?
It is possible by writing a simple UPDATE statement
——————————————————————-
USE [ADVENTUREWORKS2012]
GO
——————————————————————-
— Before Swapping
——————————————————————-
SELECT TOP 5 [VacationHours], [SickLeaveHours]
FROM [HumanResources].[Employee]
——————————————————————-
UPDATE [HumanResources].[Employee]
SET
[VacationHours] = [SickLeaveHours],
[SickLeaveHours] = [VacationHours]
——————————————————————-
— After Swapping
——————————————————————-
SELECT TOP 5 [VacationHours], [SickLeaveHours]
FROM [HumanResources].[Employee]
——————————————————————-
We can check the data before and after swap from the above SELECT statements.
Result Set:
Note:
This question seems to be easy. But few interviewers might confuse you with this kind of easy questions.
we can use the below mentioned query also:
UPDATE a
SET a.[VacationHours] = b.[SickLeaveHours]
from [HumanResources].[Employee] a inner join [HumanResources].[Employee] b
on a.[VacationHours] != b.[SickLeaveHours]
Thanks Sekhar.
Thanks a lot.