Deep Sharma
Deep Sharma

Reputation: 3473

Swap columns value in output based on certain condition using SQL Server

I have a table say "Temp" with columns "From", "To" and "Symbol" i want to swap the value of column "To" into column "From" based on value in column "Symbol".. For Example

Temp      From        To        Symbol
        -1000        -24858       <
         2000         50000       ><
         4000         8000        >

All i want is to swap value of "To" into "From" and value of "From" into "To" where value of "Symbol" is "<", rest will remain same. And this output should be result of select query.

so output will be like:

Temp      From        To        Symbol
        -24858       -1000        <
         2000         50000       ><
         4000         8000        >    

Upvotes: 1

Views: 1615

Answers (2)

Amit Singh
Amit Singh

Reputation: 8109

Select (Case when symbol='<'
then [to] 
else [from] end)as [from],(Case when symbol='<'
then [from] 
else [to] end)as [to] from temp

here is SQL FIDDLE Demo

Upvotes: 3

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36591

Try this.

update tablename
SET [to]= case WHEN symbol='<' THEN [from] ELSE [to] END,
[from]=case WHEN symbol='<' THEN [to] ELSE [from] END

Upvotes: 0

Related Questions