Click here to Skip to main content
15,891,920 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can i interchange the value of alternate rows of a column of a table in sql? (i.e row1value becomes row2value and row2value becomes row1value similarly row3value becomes row4value and row4value becomes row3value)
Posted
Comments
PhilLenoir 3-Nov-14 14:20pm    
How is row1 defined in relation to row2, row3 to row4 etc.? If you can define that relationship, as SQL Server passes the ACID test, you just need an update query with the appropriate FROM clause.
syed shanu 3-Nov-14 19:25pm    
can you provide your table details

1 solution

Hi,
i have made a sample query for you check this,Hope this will help you.

SQL
-- Create sample table.

create table Interchanges
(rowNum  int,
 rowvalue  varchar(40))

-- insert sample data
 insert into Interchanges(rownum,rowvalue) values (1,'row1')
 insert into Interchanges(rownum,rowvalue) values (2,'row2')
 insert into Interchanges(rownum,rowvalue) values (3,'row3')
 insert into Interchanges(rownum,rowvalue) values (4,'row4')
 insert into Interchanges(rownum,rowvalue) values (5,'row5')
 insert into Interchanges(rownum,rowvalue) values (6,'row6')

-- Select query 
SELECT  * FROM Interchanges 

-- The out but will be like this : 
--rowNum         rowvalue
--1		row2
--2		row1
--3		row4
--4		row3
--5		row6
--6		row5

-- Used CTE to update swap row data
-- run both cte and update query at same time

;with cte as
   (
     SELECT distinct rownum ,case when rownum+1=2 then 2 else rownum+1 end as rownewval, rowvalue FROM Interchanges  WHERE rownum % 2 = 1  
   UNION  ALL
   SELECT distinct rownum ,case when rownum-1=0 then 1 else rownum-1 end as rownewval, rowvalue FROM Interchanges  WHERE rownum % 2 = 0 
    )
update Interchanges set
Interchanges.rowvalue= upval.rowvalue
from Interchanges  ,cte upval
where Interchanges.rownum=upval.rownewval

-- Select query 
SELECT  * FROM Interchanges 

-- The Final result as you expected

----rowNum             rowvalue
--1			row2
--2			row1
--3			row4
--4			row3
--5			row6
--6			row5
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900