示例下载:WebSite1(排序).rar
表结构
CREATE TABLE [dbo].[Orders] (
[Id] [int] IDENTITY (1, 1) NOT NULL ,
[Name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[OrderId] [int] NULL
) ON [PRIMARY]
GO
[Id] [int] IDENTITY (1, 1) NOT NULL ,
[Name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[OrderId] [int] NULL
) ON [PRIMARY]
GO
存储过程
--exec Sp_Order_UpOrDown 1,-1
--select * from orders order by orderid
create proc Sp_Order_UpOrDown
@itemIndex int, --行Id
@type int --移动类型,1上移,-1下移
as
if @itemIndex = 1 and @type = 1 return --第一行不能上移
declare @count int
select @count=count(*) from orders
if @itemIndex = @count and @type = -1 return --最后一行不能下移
declare @Id int,@OrderId int,@nId int,@nOrderId int
declare @sql nvarchar(400)
set @sql = N'select top 1 @Id=Id,@OrderId=OrderId from (select top ' + cast(@itemIndex as nvarchar(50)) + ' * from orders order by orderID ) a order by orderID desc'
exec sp_executesql @sql,N'@Id int out,@OrderId int out',@Id out,@OrderId out
if @type = 1 set @itemIndex = @itemIndex - 1
if @type = -1 set @itemIndex = @itemIndex + 1
set @sql = N'select top 1 @nId=Id,@nOrderId=OrderId from (select top ' + cast(@itemIndex as nvarchar(50)) + ' * from orders order by orderID ) a order by orderID desc'
exec sp_executesql @sql,N'@nId int out,@nOrderId int out',@nId out,@nOrderId out
update orders set orderid=@nOrderId where id=@Id
update orders set orderid=@OrderId where id=@nId
--select * from orders order by orderid
create proc Sp_Order_UpOrDown
@itemIndex int, --行Id
@type int --移动类型,1上移,-1下移
as
if @itemIndex = 1 and @type = 1 return --第一行不能上移
declare @count int
select @count=count(*) from orders
if @itemIndex = @count and @type = -1 return --最后一行不能下移
declare @Id int,@OrderId int,@nId int,@nOrderId int
declare @sql nvarchar(400)
set @sql = N'select top 1 @Id=Id,@OrderId=OrderId from (select top ' + cast(@itemIndex as nvarchar(50)) + ' * from orders order by orderID ) a order by orderID desc'
exec sp_executesql @sql,N'@Id int out,@OrderId int out',@Id out,@OrderId out
if @type = 1 set @itemIndex = @itemIndex - 1
if @type = -1 set @itemIndex = @itemIndex + 1
set @sql = N'select top 1 @nId=Id,@nOrderId=OrderId from (select top ' + cast(@itemIndex as nvarchar(50)) + ' * from orders order by orderID ) a order by orderID desc'
exec sp_executesql @sql,N'@nId int out,@nOrderId int out',@nId out,@nOrderId out
update orders set orderid=@nOrderId where id=@Id
update orders set orderid=@OrderId where id=@nId