利用游标循环遍历修改列

如下图,有一张用户表tb_User,现在的需求是将表中所有小于25岁的用户全部加到25岁:

具体代码:

begin
  declare @error int --记录每次执行sql后是否有错误,0表示没有错误
  declare @temp varchar(50) --每次循环的对象(可以理解成for循环里面的i值)
  set @error=0

  begin tran --开启事物,保证多次执行sql的原子性

  declare order_cursor cursor --申明一个游标量,所属值为Id
  for(select Id from tb_User where Age<=25)

  open order_cursor --打开这个游标

  fetch next from order_cursor into @temp --循环这个游标量
  while @@FETCH_STATUS=0 --返回被Fetch语句执行的最后游标的状态
    begin
      update tb_User set Age=Age+(25-Age) where Id=@temp

      set @error=@error+@@ERROR --记录每次执行sql后是否有错误,0表示没有错误

      fetch next from order_cursor into @temp --转到下一个游标,没有会死循环
    end

  if(@error=0)
    begin
      commit tran --没有出现错误,提交事物
    end
  else
    begin
      rollback tran --出现错误,回滚事物
    end

  close order_cursor --关闭游标
  deallocate order_cursor --释放游标
end
go

执行结果截图:

 

 

 

执行成功。本文由https://www.cnblogs.com/xielong/p/5941595.html得出,这里是为了作个笔记,方便查阅,如有侵权,请联系我删除。

 

posted @ 2020-06-12 13:56  平安777  阅读(26)  评论(0)    收藏  举报