用SQL实现记录上下移动的思路

在做管理系统时,不可避免会要求对记录进行上下移动.
假如我们有一张表 t_test ,它的字段如下:

CREATE TABLE [ dbo ] . [ t_test ] (
[ sysid ] [ bigint ] NOT NULL ,
[ cname ] [ nvarchar ] ( 50 )COLLATEChinese_PRC_CI_AS NULL ,
[ position ] [ int ] NULL
)

其中的position用来表示记录排列次序。

首先,讨论一下移动一条记录的的SQL语句写法(为简化问题,只写了上移的语句):

-- 传入参数ID
declare @id bigint
set @id = 5

--
以下为实现代码
declare @pre bigint , @p0 int
// Step1:找到比它小的且最大的Position的那条记录
select @pre = sysid, @p0 = position from
(
select max (b.position) as m from t_testa,t_testb where a.sysid = @id and b.position < a.position)t,t_testc
where c.position = t.m
--
Step2:更新前一条记录,让Position + 1
update t_test set position = position + 1 where sysid = @pre
--
Step3:更新当前记录,让Position = 前一条记录
update t_test set position = case when @p0 is NULL then 0 else @p0 end where sysid = @id

逻辑写在注释里了,应该不难看明白。也就是找到前一条记录,跟当前记录交换一下即可。

然后,我们来看多条记录同时移动的方法,其实可以把上面的过程写进存储过程,然后在前台代码中用循环调用一下即可,如果我们要在SP中实现循环,也可以这样来做:

-- 传入参数,一个以‘,'分隔的字串
declare @ids nvarchar ( 20 )

set @ids = ' 2,4 '

-- 以下为实现代码
declare @tmp nvarchar ( 128 ), @idx int , @start int , @num nvarchar ( 8 )
declare @id bigint , @pre bigint , @pold int

-- Step1:找到第一个分隔符
set @tmp = @ids
set @idx = charindex ( ' , ' , @tmp )

-- Step2:循环每个切开的字串
while @idx <> 0
begin
-- Step2.1:切开一段
set @num = substring ( @tmp , 1 , @idx - 1 )
set @tmp = substring ( @tmp , @idx + 1 , len ( @tmp ) - @idx )
-- print'num='+@num
set @idx = charindex ( ' , ' , @tmp )

-- 按单条记录移动的方法处理(其实可以用调用另一个SP的方法实现)
set @id = convert ( bigint , @num )

select @pre = sysid, @pold = position from
(
select max (b.position) as m from t_testa,t_testb where a.sysid = @id and b.position < a.position)t,t_testc
where c.position = t.m

update t_test set position = position + 1 where sysid = @pre
update t_test set position = case when @pold is NULL then 0 else @pold end where sysid = @id

end

-- Step3:注意最后一段也要处理一下
-- 剩下的字串完整处理即可
set @num = substring ( @tmp , 1 , len ( @tmp ))
-- print'num='+@num

set @id = convert ( bigint , @num )

select @pre = sysid, @pold = position from
(
select max (b.position) as m from t_testa,t_testb where a.sysid = @id and b.position < a.position)t,t_testc
where c.position = t.m

update t_test set position = position + 1 where sysid = @pre
update t_test set position = case when @pold is NULL then 0 else @pold end where sysid = @id

因为从页面上的checkbox传过来的参数,形式就是以逗号分隔的字串,所以如果直接再传给SP来处理,应该是比较方便的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值