如何在sql中的两个并发表行值之间切换

时间:2016-07-29 10:06:56

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2012

我有一个表名[NavBar],其中包含以下列:

Id [int]
Name [nvarchar]
DisplayOrder [int]

示例数据:

Id   Name   DisplayOrder
---------------------------
 100   Home        1
 101   Products    2
 102   Contact     3
 103   Career      4

如何执行更新操作以在DisplayOrder的两行two concurrent rows之间切换(按Displayorder排序)?

例如Contact = 4, Career = 3

预期产出:

100  Home      1
101  Products  2
102  Contact   4
103  Career    3

输入参数:仅限一行的Id

2 个答案:

答案 0 :(得分:1)

如果您要更新id = 102(然后是103)

if (alertDialog.isShowing())
        alertDialog.dismiss();

<强>输出

 drop table navBar;
 create table navBar
 (Id [int],
Name [nvarchar] (200),
DisplayOrder [int]);

insert into navBar
values
 (100,   'Home'      ,  1),
 (101,   'Products',    2),
 (102 ,  'Contact',     3),
 (103  , 'Career',      4);

 declare @id int;

 set @id = 102

 ; with t as(
 select id,  name, DisplayOrder, 
        lag(id) over(order by DisplayOrder) lgid, 
        lag(DisplayOrder) over(order by DisplayOrder) lgDisplayOrder,
        lead(DisplayOrder) over(order by DisplayOrder) ldDisplayOrder
 from navBar)
 update t
   set DisplayOrder = case @id when id then ldDisplayOrder else lgDisplayOrder end
 where (@id = id and ldDisplayOrder is not null)
   or  (@id = lgid);


 select * from navBar;

答案 1 :(得分:0)

我认为应该有效

declare @Id int = 101

update t1 
set Id = new_ID + @Id
from NavBar t1
inner join  (select DisplayOrder, row_number()  over (order by DisplayOrder) as new_ID
            from NavBar where Id > @Id) as t2  on t2.DisplayOrder = t1.DisplayOrder