zoukankan      html  css  js  c++  java
  • Sql Server 之游标

      一般来说,我们通过SQL一般是面向集合进行数据操作,但是游标提供给我们更加强大的功能可以对数据集合进行逐行遍历有选择性的操作处理。当然游标也有其不可避免的缺陷就是:低效和复杂。所以一般正常的操作处理不会选择使用游标进行数据操作。

      游标的使用:

    declare testCur cursor                   

      for select ID,gradefrom student where grade <60 or grade is null   ---声明游标

    open testCur                                                                      ---打开游标

    declare @ID       decimal(10,0)
    declare @grade  varchar(100)                            ---定义游标中的参数

      fetch next from testCur into @ID,@grade                ---当游标被打开时,行指针将指向该游标集第1行之前,如果要读取游标集中的第1行数据,必须移动行指针使其指向第1行

    while @@fetch_status=0                                                    --- @@fetch_status=0 说明游标活动(fetch next from testCur)成功,-1 表示FETCH 语句失败或此行不在结果集中,-2 被提取的行不存在

      if @grade is not null                         ---加入逻辑判断

      begin

        update student set grade=60 where grade<60 and id=@ID     --根据游标

        fetch next from testCur into @ID,@grade

      end

      else

      begin

        update student set grade='缺考' where id=@ID

        fetch next from testCur into @ID,@grade

      end

    close testCur                              ---关闭游标

    deallocate testCur                            ---删除游标

    Best Wish !
  • 相关阅读:
    jq绑定on事件无效
    数字以0补全
    redis常用操作
    mysql数据操作日常
    centos端口映射
    centos7防火墙操作
    mysql5.7order by问题
    centos无法上网解决方法
    面试题
    ztree 获取子节点所有父节点的name的拼接
  • 原文地址:https://www.cnblogs.com/ultimateWorld/p/4761293.html
Copyright © 2011-2022 走看看