排序

2014-11-24 03:07:36 · 作者: · 浏览: 4
--编写排序的问题,例如 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