日期:2014-05-18  浏览次数:20465 次

在数据库版发了个帖子,没人理,再出100分
数据库表T(A,   B,   .....),其中A、B为主键,同时B还作为排序字段。当修改B时,如将@oldB改为@newB,我的做法是

--(1)将oldB改为-1:
Update   T   Set   B=-1   Where   A=@A   and   B=@oldB

--   (2)如果是将较大的数改为较小的,则将[@newB,@oldB)之间的数加1
if   (@newB   <   @oldB)
        Update   T   Set   B=B+1   Where   A=@A   and   B> =@newB   and   B <@oldB
else     --   否则将(@oldB,   @newB]之间的数减1
        Update   T   Set   B=B-1   Where   A=@A   and   B> @oldB   and   B <=@newB

--   (3)将-1再改回来
update   T   Set   B=@newB   Where   A=@A   and   B=-1

问题:这样处理时,将一个较小的数改为较大的没有问题,但将一个较大的数改为较小的数时,出现主键值不能重复的错误。
    不启用事务,发现是在第二步出的错,难道批量处理时,每处理一条记录就进行完整性检查,而不是这个语句执行完再检查?不知道大家有什么好的办法。


------解决方案--------------------
没看懂
------解决方案--------------------
if (@newB < @oldB)
Update T Set B=B+1 Where B> =@newB and B <@oldB
else -- 否则将(@oldB, @newB]之间的数减1
Update T Set B=B-1 Where B> @oldB and B <=@newB

把A=@A去掉
------解决方案--------------------
什么数据库?我在Sql Server 2005 上测试了下,没有这样的问题。