比如有这样一个表格t_info:
id | code |
---|---|
1 | 1001 |
2 | 1002 |
3 | 1003 |
其中,id是主键且是自增列,code是编号(从1001开始,也是依次递增),现在面临一个问题,code列的数据
出现了混乱,成了下面的样子:
id | code |
---|---|
1 | 1001 |
2 | 1005 |
3 | 3 |
现在要在数据库中批量更新每一行,怎搞呢
下面是一个方案:
declare @code int --存放编号
declare @min_id int --存放最小id
set @code=1001 --设定初始编号
set @min_id=(select min(id) from oa_employee) --设定初始最小id
while @min_id >0
begin
update t_info set code=@code where id=@min_id --总是将编号赋值给最小id所在行
set @min_id=(select min(id) from oa_employee where id>@min_id) --更新最小id为次行id
set @code=@code+1 --更新code值
end