create proc p_process
@id int
as
if @id=(select min(id) from 表)
begin
raiserror('不能调整最小id的NO',1,16)
return
endupdate 表 set [NO]=b.[NO]
from 表 a,表 b
where a.id between @id-1 and id
and b.id between @id-1 and id
and a.id=case when b.id=@id then @id-1 else @id end

解决方案 »

  1.   

    --错了,id是不连续的,改一下:create proc p_process
    @id int
    as
    declare @nid int
    select @nid=max(ID) from 表 where ID<@ID
    if @@rowcount=0
    begin
    raiserror('不能调整最小id的NO',1,16)
    return
    endupdate a set [NO]=b.[NO]
    from 表 a,表 b
    where a.id between @nid and @id
    and b.id between @nid and @id
    and a.id=case when b.id=@id then @nid else @id end
      

  2.   

    --测试--测试数据
    create table 表(ID int,Name varchar(10),[NO] int)
    insert 表 select 1,'TOM' ,1
    union all select 2,'Jack',2
    union all select 5,'Kate',5
    union all select 6,'Mary',6
    go--存储过程
    create proc p_process
    @id int
    as
    declare @nid int
    select @nid=max(ID) from 表 where ID<@ID
    if @@rowcount=0
    begin
    raiserror('不能调整最小id的NO',1,16)
    return
    endupdate a set [NO]=b.[NO]
    from 表 a,表 b
    where a.id between @nid and @id
    and b.id between @nid and @id
    and a.id=case when b.id=@id then @nid else @id end
    go--调用
    exec p_process 5--显示结果
    select * from 表
    go--删除测试
    drop proc p_process
    drop table 表/*--测试结果ID          Name       NO          
    ----------- ---------- ----------- 
    1           TOM        1
    2           Jack       5
    5           Kate       2
    6           Mary       6(所影响的行数为 4 行)
    --*/