Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


T-SQL Query | [ Swap Value of Column with another Without Case Statement ]

The puzzle is very simple. Here you have to swap values of column. In sample input case you have only column called Val. In this column only 2 values are present ‘A’ & ‘B’. We have to update value of A with B and B with A. Please check out the sample input and expected output for details.

Sample Input

Val
A
B
B
A
B
B

Expected output

Val
B
A
A
B
A
A

Rules/Restrictions

  • The solution should be should use “SELECT” statement or “CTE”.
  • Please do not use CASE, REPLACE, IIF and CHOOSE.
  • Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com

Script

Use the below script to generate the source table and fill them up with the sample data.


--

CREATE TABLE Swap
(
Val VARCHAR(1)
)
GO

INSERT INTO Swap(Val) VALUES ('A'),('B'),('B'),('A'),('B'),('B')

--

UPDATE – 10-Apr-2015 – Solution 1


-- Solution 1 --

UPDATE s
SET s.Val = s1.Val
FROM Swap S
INNER JOIN Swap S1
ON S.Val <> S1.Val

--

Add a comment if you have any other solution in mind. We all need to learn.

Keep Learning

http://MSBISkills.com