排序

--编写排序的问题。比如 1、2、3、4、5、6这种排列号
--思路:(1)假设1变成5,那么就是1直接变5,2、3、4、5 分别减1,6不变
--(2)假设5变成3,那么5直接变成3,1、2不变,3、4减1,6不变
--(3)比如:3变成6。那么6是目标值,3是欲成为目标的值
--(4)用事务或者存储过程实现
--(5)要传的參数各自是:表名,目标值。欲成为目标的值。标识列(比如ID)

Create proc [dbo].[pro_woqu]
@ID int ,--ID值
@targetValue int ,--目标值
@wishtargetValue int,--欲成为目标的值
@tableName varchar(100)

as
begin tran
update [User] set DisplayOrder=@targetValue where ID=@ID;
if(@targetValue<@wishtargetValue)--假设5变成3,那么5直接变成3,1、2不变,3、4减1,6不变
begin 
update [User]set DisplayOrder=DisplayOrder+1 where DisplayOrder>=@targetValue and DisplayOrder<@wishtargetValue and ID!=@ID and ParentID=0
end
if(@targetValue>@wishtargetValue)--3变成6。那么6是目标值。3是欲成为目标的值
begin
update [User]set DisplayOrder=DisplayOrder-1 where DisplayOrder<=@targetValue and DisplayOrder>@wishtargetValue and ID!=@ID and ParentID=0
end
if @@error<>0
 begin  rollback tran
return 0
end
else 
begin commit tran
return 1
end

原文地址:https://www.cnblogs.com/gccbuaa/p/6699114.html