zoukankan      html  css  js  c++  java
  • SQL 使用Cursor(游标)遍历结果集

    使用Cursor(游标)可以在存储过程中遍历select 结果集,对其进行相关的操作。

    Cursor(游标)语法格式

    DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
    OPEN 游标名称
    FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
    WHILE @@FETCH_STATUS=0
            BEGIN
                      SQL语句执行过程... ...
                      FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
            END
    CLOSE 游标名称
    DEALLOCATE 游标名称 (删除游标)

    Cursor(游标)使用示例代码

    --创建一个table1结构如下:
    id int 
    name varchar(50)
    age int 
    --要求:使用Cursor进行循环使每条数据age+1
    declare @id int
    declare @name varchar(50)
    declare @age int
    declare cursor1 cursor for         --定义游标cursor1
    select * from table1               --使用游标的对象(跟据需要填入select文)
    open cursor1                       --打开游标
    
    fetch next from cursor1 into @id,@name,@age  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中
    
    while @@fetch_status=0           --判断是否成功获取数据
    begin
    update table1 set age=age+1
    where id=@id                           --进行相应处理(跟据需要填入SQL文)
    
    fetch next from cursor1 into @id,@name,@age  --将游标向下移1行
    end
    
    close cursor1                   --关闭游标
    deallocate cursor1
  • 相关阅读:
    NKOJ P3051浇花
    Linux-Shell脚本编程-学习-2-Linux基本命令
    Linux-Shell脚本编程-学习-1-Linux基本命令
    Ubuntu下使用Git_6
    Ubuntu下使用Git_5
    电脑优化,提速
    Ubuntu下使用Git_4
    Ubuntu下使用Git_3
    Ubuntu下使用Git_2
    Ubuntu下使用Git_1
  • 原文地址:https://www.cnblogs.com/huhangfei/p/5000707.html
Copyright © 2011-2022 走看看