1、背景:
按主表分组,修复从表数据的顺序号
2、思路:
使用游标来实现,逻辑类似于一个双层循环,循环赋值
3、具体实现:
declare @a int,@error INT,@operationID NUMERIC(10,0),@workStepInfoID BIGINT,@workOrderID INT declare @temp NUMERIC(10,0) set @a=1 --用于更新序号 set @error=0 -- 错误号 set @temp=0 -- 主表分组标识 begin tran --申明事务 --申明游标 declare order_cursor cursor for SELECT operationID,workStepInfoID,workOrderID FROM WorkStepInfo WHERE workOrderID <> 0 AND workStepInfoID>634759 ORDER BY operationID,workStepInfoID --打开游标-- open order_cursor --开始循环游标变量-- fetch next from order_cursor into @operationID,@workStepInfoID,@workOrderID while @@FETCH_STATUS = 0 --返回被 FETCH语句执行的最后游标的状态-- BEGIN if @temp <> @operationID BEGIN SET @temp=@operationID set @a=1 end update WorkStepInfo set workOrderID=@a where workStepInfoID=@workStepInfoID set @a=@a+1 set @error= @error + @@ERROR --记录每次运行sql后是否正确,0正确 fetch next from order_cursor into @operationID,@workStepInfoID,@workOrderID --转到下一个游标 end if @error=0 begin commit tran --提交事务 PRINT '执行成功' end else begin rollback tran --回滚事务 PRINT '执行失败' end close order_cursor --关闭游标 deallocate order_cursor --释放游标