Friday, 5 July 2019

Swap values between two columns in sql server


When we are going for SQL interview, most frequent this question asked by the interviewer. Who can we swap the values between the two columns?
Let’s see how we will do it.
I have a table named “EMP”.
                         

I want the swap the fname with the lname those deptno=10
For the swapping I am taking a variable and performing the swap.
DECLARE @temp as varchar(20)
update emp
set    @temp = fname,
       fname = lname,
       lname = @temp
WHERE  deptno = 10;
GO
   
4 rows updated
See the result below.
                                      
Values have been swapped those empID 10.

Popular Posts