Write an SQL Query to swap two integer numbers without using the third variable in SQL Server.
Write an SQL Query to swap two integer numbers without using the third variable in SQL Server.
Web Developer
I am a professional .NET developer with over 4 years of hands-on industry experience in designing, developing, and maintaining scalable web applications. I specialize in .NET Core, C#, RESTful APIs, and database-driven systems using SQL Server.
There are simple techniques to swap two integer numbers in SQL Server in which, third variable is not required including Addition and subtraction or in another way that is XOR. Here's how you can do it in SQL:
Using Addition and Subtraction:
Explanation:
@a.@bfrom the new@aand assign the result to@b. Now,@bholds the original value of@a.@b(which holds the old value of@a) from the new@a. Now,@aholds the original value of@b.Using XOR (Bitwise Operator):
Explanation:
Output:
After either method:
@a becomes 20.
@b becomes 10.
In both methods, the two variables are exchanged directly without the need to use a third variable.