我使用这种stackoverflow技巧已经很长一段时间了很长时间才能正常工作。 Generate an Update SQL for Changing the Order of an Item?
但如果行之间缺少记录,则无效。见这个样本,
declare @MyTable table
(
[ID] INT,
[Order] INT,
Name VARCHAR(20)
)
insert into @MyTable values(11111,1,'A'), (22222,2,'B'), (3333,3,'C'),(44444,4,'D');
select * from @MyTable;
--which will gives you
----------------------
-- ID Order Name
-- 11111 1 A
-- 22222 2 B
-- 3333 3 C
-- 44444 4 D
----------------------
-- Now just delete a row
delete from @MyTable where [ID] = 3333;
select * from @MyTable;
--which will gives you
--------------------
-- ID Order Name
-- 11111 1 A
-- 22222 2 B
-- 44444 4 D
--------------------
-- Now just decrement the order of 4
declare @OldOrder INT = 4;
declare @NewOrder INT = @OldOrder - 1;
UPDATE @MyTable
SET [Order] = (CASE
WHEN
[Order] = @OldOrder
THEN
@NewOrder
WHEN
@NewOrder > @OldOrder
THEN
[Order] - 1
ELSE
[Order] + 1
END)
WHERE ([Order] BETWEEN @OldOrder AND @NewOrder OR [Order] BETWEEN @NewOrder AND @OldOrder)
select * from @MyTable;
--which will gives you
--------------------
--ID Order Name
--11111 1 A
--22222 2 B
--44444 3 D
--------------------
--The result should be
--------------------
--ID Order Name
--11111 1 A
--22222 3 B
--44444 2 D
--------------------
答案 0 :(得分:1)
您的更新有几个问题......
UPDATE @MyTable
SET [Order] = (CASE
WHEN [Order] = @OldOrder THEN @NewOrder
WHEN @NewOrder > @OldOrder THEN [Order] - 1
ELSE
[Order] + 1
END)
WHERE ([Order] BETWEEN @OldOrder AND @NewOrder OR [Order] BETWEEN @NewOrder AND @OldOrder)
WHEN 3 > 4 THEN [Order] - 1
WHERE ([Order] BETWEEN 4 AND 3 OR [Order] BETWEEN 3 AND 4)
您只更新此查询中的一条记录,因此输出正确。
答案 1 :(得分:0)
你的第二个WHEN条件从未评估为真。
您指定@NewOrder = @OldOrder - 1
,因此@NewOrder
永远不会大于@OldOrder
。