sql server adjacent table record exchange (single and pair exchange)

I saw such a question in the blog question of the blog garden: There are two fields, id and name, in a table. The id is continuous, non-empty and non-repeating. I want to exchange the name values ​​of adjacent table records (single and double exchange). ).

In addition, if the last single row does not have a corresponding next row matching record, the last single row record is not updated.

Feel a bit interesting, try to implement it (SQL Server), and record it.

Create a diosos table.

--If the table exists, delete the table 
if  object_id (N ' diosos ' , N ' U ' ) is  not  null  drop  table diosos; --create
 table create 
table  diosos (id int , name varchar ( 64 ));

Insert data into the table.

-- 插入数据
insert into diosos(id, name) values(1, 'one');
insert into diosos(id, name) values(2, 'two');
insert into diosos(id, name) values(3, 'three');
insert into diosos(id, name) values(4, 'four');
insert into diosos(id, name) values(5, 'five');
insert into diosos(id, name) values(6, 'six');
insert into diosos(id, name) values(7, 'seven');
insert into diosos(id, name) values(8, 'eight');
insert into diosos(id, name) values(9, 'nine');

Check it out to see if the data is correct.

--Query data 
select  *  from diosos;

To realize the exchange of adjacent table records (single and double exchange), the principle is to judge the parity and adjacent id addition and subtraction according to the remainder of the id to make a left outer join association, and update the name of the row record.

--Update , exchange each pair, not pairwise 
update d1 set d1.name = d2.name
 from diosos d1
 left  join diosos d2
 on (d1.id % 2  =  0  and d1.id = (d2.id +  1 ) ) or (d1.id % 2  =  1  and d1.id = (d2.id -  1 ))
 where d2.name is  not  null ;

Query again, successful implementation.

-- Query 
select  *  from diosos again;

It's still pretty fun, although I don't think there will be any actual scenes, hahaha.


"You have to believe that there will be people in this world who understand the suffering behind you, and there will be people who are willing to give you a whole season of splendor."

Reprinted in: https://www.cnblogs.com/yanggb/p/11327788.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782316&siteId=291194637