SQL中游标(cursor)的基本使用实例

目录
  •  类型:
  • 1.普通游标
  • 2.滚动游标
  • 具体FETCH用法:
    • Arguments
  • 总结

 类型:

  1.普通游标   只有NEXT操作

  2.滚动游标 有多种操作

1.普通游标

DECLARE @username varchar(20),@UserId varchar(100)
DECLARE cursor_name CURSOR FOR --定义游标
    SELECT TOP 10 UserId,UserName FROM UserInfo
    ORDER BY UserId DESC
OPEN cursor_name --打开游标
FETCH NEXT FROM cursor_name INTO  @UserId,@username  --抓取下一行游标数据
WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT '用户ID:'+@UserId+'            '+'用户名:'+@username
        FETCH NEXT FROM cursor_name INTO @UserId,@username
    END
CLOSE cursor_name --关闭游标
DEALLOCATE cursor_name --释放游标

结果:

用户ID:zhizhi            用户名:邓鸿芝

用户ID:yuyu            用户名:魏雨

用户ID:yujie            用户名:李玉杰

用户ID:yuanyuan            用户名:王梦缘

用户ID:YOUYOU            用户名:lisi

用户ID:yiyiren            用户名:任毅

用户ID:yanbo            用户名:王艳波

用户ID:xuxu            用户名:陈佳绪

用户ID:xiangxiang            用户名:李庆祥

用户ID:wenwen            用户名:魏文文

2.滚动游标

--带SCROLL选项的游标
SET NOCOUNT ON
DECLARE C SCROLL CURSOR FOR  --SCORLL 后,有了更多的游标操作(滚动游标)
    SELECT TOP 10 UserId,UserName FROM UserInfo
    ORDER BY UserId DESC
OPEN C
FETCH LAST FROM C   --最后一行的数据,并将当前行为指定行
FETCH ABSOLUTE 4 FROM C  --从第一行开始的第4行数据,并将当前行为指定行  这里的n可正可负,n>0 往下翻,n<0 往上翻
FETCH RELATIVE 3 FROM C  --相对于当前行的后3行数据,并将当前行为指定行  这里的n可正可负
FETCH RELATIVE -2 FROM C --相对于当前行的前2行数据,并将当前行为指定行
FETCH PRIOR FROM C   ----相对于当前行的前1行数据
FETCH FIRST FROM C   --刚开始第一行的数据,并将当前行为指定行
FETCH NEXT FROM C   --相对于当前行的后1行数据

CLOSE C
DEALLOCATE C

结果(可以参考第一个结果分析):

具体FETCH用法:

FETCH
          [ [ NEXT | PRIOR | FIRST | LAST
                    | ABSOLUTE { n | @nvar }
                    | RELATIVE { n | @nvar }
               ]
               FROM
          ]
{ { [ GLOBAL ] cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ]

Arguments

NEXT

Returns the result row immediately following the current row and increments the current row to the row returned. If FETCH NEXT is the first fetch against a cursor, it returns the first row in the result set. NEXT is the default cursor fetch option.

PRIOR

Returns the result row immediately preceding the current row, and decrements the current row to the row returned. If FETCH PRIOR is the first fetch against a cursor, no row is returned and the cursor is left positioned before the first row.

FIRST

Returns the first row in the cursor and makes it the current row.

LAST

Returns the last row in the cursor and makes it the current row.

ABSOLUTE { n| @nvar}

If n or @nvar is positive, returns the row n rows from the front of the cursor and makes the returned row the new current row. If n or @nvar is negative, returns the row n rows before the end of the cursor and makes the returned row the new current row. If n or @nvar is 0, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.

RELATIVE { n| @nvar}

If n or @nvar is positive, returns the row n rows beyond the current row and makes the returned row the new current row. If n or @nvar is negative, returns the row n rows prior to the current row and makes the returned row the new current row. If n or @nvar is 0, returns the current row. If FETCH RELATIVE is specified with n or @nvar set to negative numbers or 0 on the first fetch done against a cursor, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.

GLOBAL

Specifies that cursor_name refers to a global cursor.

cursor_name

Is the name of the open cursor from which the fetch should be made. If both a global and a local cursor exist with cursor_name as their name, cursor_name to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified.

@cursor_variable_name

Is the name of a cursor variable referencing the open cursor from which the fetch should be made.

INTO @variable_name[ ,...n]

Allows data from the columns of a fetch to be placed into local variables. Each variable in the list, from left to right, is associated with the corresponding column in the cursor result set. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column. The number of variables must match the number of columns in the cursor select list.

总结

到此这篇关于SQL中游标(cursor)基本使用的文章就介绍到这了,更多相关SQL游标的使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • sqlserver 游标的简单示例

    Declare @Id varchar(20) Declare @Name varchar(20) Declare Cur Cursor For select substring(id,0,7) as id,name from temp1 Open Cur Fetch next From Cur Into @Id,@Name While @@fetch_status=0 Begin Update temp Set [c3]=@Name where [id] like @Id+'%' Fetch

  • MySQL游标概念与用法详解

    本文实例讲述了MySQL游标概念与用法.分享给大家供大家参考,具体如下: 1.游标的概念(Cursor) 一条sql,对应N条资源,取出资源的接口,就是游标,沿着游标,可以一次取出1行.如果开发过安卓的同学应该知道有一个Api是Cursor,也是读取SQLite数据库用的,和这个有点类似. 2.使用游标的步骤 (1)声明 使用declare进行声明 declare 游标名 cursor for select_statement (2)打开游标 使用open进行打开 open 游标名 (3)从游标

  • 教你怎么使用sql游标实例分享

    [sql] --1.将每个老师的工资更新为原来的工资+奖金 --定义两个变量,用来存储ttid与reward declare @tid int declare @reward money --1.建立一个基于奖金表的游标 declare cur_reward cursor fast_forward for select ttid,reward from TblTeacherSalary --2.打开游标 open cur_reward --通过游标读取数据 fetch next from cur

  • mysql存储过程 游标 循环使用介绍

    Mysql的存储过程是从版本5才开始支持的,所以目前一般使用的都可以用到存储过程.今天分享下自己对于Mysql存储过程的认识与了解. 一些简单的调用以及语法规则这里就不在赘述,网上有许多例子.这里主要说说大家常用的游标加循环的嵌套使用. 首先先介绍循环的分类: (1)WHILE ... END WHILE (2)LOOP ... END LOOP (3)REPEAT ... END REPEAT (4)GOTO 这里有三种标准的循环方式:WHILE循环,LOOP循环以及REPEAT循环.还有一种

  • 基于MySQL游标的具体使用详解

    测试表 level ; 复制代码 代码如下: create table test.level (name varchar(20)); 再 insert 些数据 ; 代码 初始化 复制代码 代码如下: drop procedure if exists useCursor // 建立 存储过程 create 复制代码 代码如下: CREATE PROCEDURE useCursor() BEGIN 局部变量的定义 declare 复制代码 代码如下: declare tmpName varchar(

  • mysql存储过程中使用游标的实例

    复制代码 代码如下: DELIMITER $$ DROP PROCEDURE IF EXISTS getUserInfo $$ CREATE PROCEDURE getUserInfo(in date_day datetime)-- -- 实例-- MYSQL存储过程名为:getUserInfo-- 参数为:date_day日期格式:2008-03-08--    BEGINdeclare _userName varchar(12); -- 用户名declare _chinese int ; -

  • sqlserver游标使用步骤示例(创建游标 关闭游标)

    游标(cursor)是一个存储在DBMS服务器上的数据库查询,它不是一条SELECT语句,而是被该语句检索出来的结果集.在存储了游标之后,应用程序可以根据需要滚动或浏览其中的数据. 使用游标 使用游标的步骤: 在使用游标前,必须声明(定义)它.这个过程实际上没有检索数据,它只是定义要使用的SELECT语句和游标选项.一旦声明,就必须打开游标以供使用.这个过程用前面定义的SELECT语句把数据实际检索出来.对于填有数据的游标,根据需要取出(检索)各行.在结束游标使用时,必须关闭游标,可能的话,释放

  • MSSQL 游标使用 心得

    游标为您提供了在逐行的基础上而不是一次处理整个结果集为基础的操作表中数据的方法. 1.如何使用游标 1)定义游标语句 Declare <游标名> Cursor For 2)创建游标语句 Open <游标名> 3)提取游标列值.移动记录指针 Fetch <列名列表> From <游标名> [Into <变量列表>] 4)使用@@Fetch_Status利用While循环处理游标中的行 5)删除游标并释放语句 Close <游标名>/De

  • SQL中游标(cursor)的基本使用实例

    目录  类型: 1.普通游标 2.滚动游标 具体FETCH用法: Arguments 总结  类型: 1.普通游标   只有NEXT操作 2.滚动游标 有多种操作 1.普通游标 DECLARE @username varchar(20),@UserId varchar(100) DECLARE cursor_name CURSOR FOR --定义游标 SELECT TOP 10 UserId,UserName FROM UserInfo ORDER BY UserId DESC OPEN cu

  • Oracle中游标Cursor基本用法详解

    查询 SELECT语句用于从数据库中查询数据,当在PL/SQL中使用SELECT语句时,要与INTO子句一起使用,查询的 返回值被赋予INTO子句中的变量,变量的声明是在DELCARE中.SELECT INTO语法如下: SELECT [DISTICT|ALL]{*|column[,column,...]} INTO (variable[,variable,...] |record) FROM {table|(sub-query)}[alias] WHERE............ PL/SQL

  • Oracle中游标Cursor的用法详解

    目录 一.使用游标 1.定义游标 2.打开游标 3.提取数据 4.关闭游标 5.游标属性 6.参数游标 二.for循环遍历,实现遍历游标最高效方式. 三.使用游标更新或删除数据 四.通过bulk collect减少loop处理的开销 五.使用游标变量 1.游标变量使用步骤 1.1定义ref cursor类型和游标变量 1.2打开游标 1.3提取游标数据 1.4关闭游标变量 2.游标变量使用示例 一.使用游标 对于DML语句和单行select into ,oracle自动分配隐形游标.处理sele

  • SQL中where语句的用法及实例代码(条件查询)

    目录 1.where语法和用法 (1)语法:where <criteria> 即where <查询条件> (2)用法:获取满足一定条件的目标数据. 2.实例 (1)单一条件查询 (2)多条件查询 补充:引号的使用 总结 1.where语法和用法 (1)语法:where <criteria> 即where <查询条件> 具体查询语句:select <字段> from <表名> where <查询条件> 说明:①多个条件则用“

  • SQL Server 游标语句 声明/打开/循环实例

    SQL Server游标语句使用方法: 复制代码 代码如下: --声明一个游标 DECLARE MyCursor CURSOR FOR SELECT TOP 5 FBookName,FBookCoding FROM TBookInfo//定义一个叫MyCursor的游标,存放for select 后的数据 --打开一个游标 OPEN MyCursor//即打开这个数据集 --循环一个游标 DECLARE @BookName nvarchar(2000),@BookCoding nvarchar(

  • SQL中from_unixtime函数的使用方法实例

    目录 1.from_unixtime的语法及用法 (1)语法:from_unixtime(timestamp ,date_format) (2)用法:将时间戳转为指定日期格式. (3)常见的日期格式 2.实例 总结 1.from_unixtime的语法及用法 (1)语法:from_unixtime(timestamp ,date_format) 即from_unixtime(时间戳 ,日期格式 参数说明 timestamp :时间戳,可为一串数字,也可为字段. date_format:时间格式,

  • MS SQL Server游标(CURSOR)的学习使用

    说实的,使用MS SQL Server这样久,游标一直没有使用过.以前实现相似的功能,都是使用WHILE循环加临时表来实现.刚才有参考网上示例练习写了一下.了解到游标概念与语法. 下面代码示例中, 先是宣告你在游标中需使用变量,也就是临时存储处理字段的数据. 2. 宣告一个游标,并SELECT需要处理的数据集. 3. 打开游标(#8行代码). 4. 从游标中拿来FETCH NEXT 数据给变量赋值. 5. 循环@@FETCH_STATUS = 0条件. 6. 在循环块,可以处理第一笔的记录逻辑了

  • 在Oracle PL/SQL中游标声明中表名动态变化的方法

    /*     小弟刚刚接触ORACLE存储过程,有一个问题向各位同行求教,小弟写了一个存储过程,其目的是接收一个参数作为表名,然后查询该表中的全部记录的某一个字段的内容导入到另一个表中.     (     tabname in varchar     )     is     v_servicesname tabname.服务类型%type; --这个变量就是用来存放所要取得的字段内容,但不知该如何定义     cursor curSort1 is select 服务类型 from tabna

  • Sql存储过程游标循环的用法及sql如何使用cursor写一个简单的循环

    用游标,和WHILE可以遍历您的查询中的每一条记录并将要求的字段传给变量进行相应的处理 ================== DECLARE @A1 VARCHAR(10), @A2 VARCHAR(10), @A3 INT DECLARE CURSOR YOUCURNAME FOR SELECT A1,A2,A3 FROM YOUTABLENAME OPEN YOUCURNAME fetch next from youcurname into @a1,@a2,@a3 while @@fetch

  • 实例理解SQL中truncate和delete的区别

    本文以一个简单实例为大家介绍了SQL中truncate和delete的区别,帮助大家理解,具体内容如下 ---创建表Table1 IF OBJECT_ID('Table1','U') IS NOT NULL DROP TABLE Table1 GO CREATE TABLE Table1 (ID INT NOT NULL, FOID INT NOT NULL) GO --插入测试数据 INSERT INTO Table1 VALUES(1,101),(2,102),(3,103),(4,104)

随机推荐