数据库上移和下移

DECLARE @operType INT = 0;--0下移 1上移
DECLARE @id INT = 1;

declare @preSort int;--上一条记录的排序值
declare @preid int; --上一条记录的id值
declare @curSort int;--当前记录的排序值
declare @nextSort int;--下一条记录的排序值
declare @nextid int; --下一条记录的id值
IF @operType = 0
BEGIN
with TB As (select top 1000 *,row_number() over(order by Sort desc) as rowid from cn9c080.tb_QQ_CommodityTemplete WHERE status <> 2 order by Sort desc)

select @nextSort=sort,@nextid=id from TB where rowid=(select rowid-1 from TB where id=@id);
select @curSort=Sort From cn9c080.tb_QQ_CommodityTemplete Where id=@id;
IF @nextSort IS NULL
BEGIN
SELECT -1;--已经在最低部
RETURN;
END;

update cn9c080.tb_QQ_CommodityTemplete set Sort=@nextSort where id=@id;
update cn9c080.tb_QQ_CommodityTemplete set Sort=@curSort where id=@nextid;

SELECT @@ROWCOUNT;
END;
ELSE
BEGIN
with TB As (select top 1000 *,row_number() over(order by Sort desc) as rowid from cn9c080.tb_QQ_CommodityTemplete WHERE status <> 2 order by Sort desc)
select @preSort=sort,@preid=id from TB where rowid=(select rowid+1 from TB where id=@id);
select @curSort=Sort From cn9c080.tb_QQ_CommodityTemplete Where id=@id;
IF @preSort IS NULL
BEGIN
SELECT -2;--已经在最顶部
RETURN;
END;

update cn9c080.tb_QQ_CommodityTemplete set Sort=@preSort where id=@id;
update cn9c080.tb_QQ_CommodityTemplete set SOrt=@curSort where id=@preid;

SELECT @@ROWCOUNT;
END;

posted @ 2019-02-16 16:18  木子zzgxl  阅读(856)  评论(0编辑  收藏  举报