--传入参数ID declare@idbigint set@id=5 --以下为实现代码 declare@prebigint,@p0int //Step1:找到比它小的且最大的Position的那条记录 select@pre=sysid,@p0=position from (selectmax(b.position) as m from t_test a,t_test b where a.sysid=@idand b.position<a.position) t,t_test c where c.position=t.m --Step2:更新前一条记录,让Position+1 update t_test set position=position+1where sysid=@pre --Step3:更新当前记录,让Position=前一条记录 update t_test set position=casewhen@p0isNULLthen0else@p0endwhere sysid=@id
--传入参数,一个以‘,'分隔的字串 declare@idsnvarchar(20) set@ids='2,4' --以下为实现代码 declare@tmpnvarchar(128),@idxint,@startint,@numnvarchar(8) declare@idbigint,@prebigint,@poldint --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 (selectmax(b.position) as m from t_test a,t_test b where a.sysid=@idand b.position<a.position) t,t_test c where c.position=t.m update t_test set position=position+1where sysid=@pre update t_test set position=casewhen@poldisNULLthen0else@poldendwhere 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 (selectmax(b.position) as m from t_test a,t_test b where a.sysid=@idand b.position<a.position) t,t_test c where c.position=t.m update t_test set position=position+1where sysid=@pre update t_test set position=casewhen@poldisNULLthen0else@poldendwhere sysid=@id