当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL用法三(游标和Fetch)

SQL用法三(游标和Fetch)

2019年05月23日  | 移动技术网IT编程  | 我要评论

在网上兼职,13400,爆丸小子第二部

/一般情况下,我们用select这些查询语句时,都是针对的一行记录而言,
如果要在查询分析器中对多行记录(即记录集)进行读取操作时,则需要使用到游标或while等循环
/
以下内容摘自

/
游标的类型:
  1、静态游标(不检测数据行的变化)
  2、动态游标(反映所有数据行的改变)
  3、仅向前游标(不支持滚动)
  4、键集游标(能反映修改,但不能准确反映插入、删除)

游标使用顺序:
   1、定义游标
   2、打开游标
   3、使用游标
   4、关闭游标
   5、释放游标

transact-sql:
declare 游标名 cursor [local | global][forward_only | scroll][static | keyset | dynamic ] [read_only | scroll_locks]  
  for selet语句   [for  update[of 列名[,列名]]
 注:local 局部游标     global 全局游标
     forward_only 仅向前  scroll 滚动
     static 静态  keyset 键集 dynamic 动态
     read_only 只读 scroll_locks 锁定游标当前行

获取游标的数据
  fetch [[next | prior | first | last | 
  absolute{ n | @nvar | relative { n | @nvar}]
  from ] 游标名 [into 变量]
  注:
    next  下一行  prior  上一行  first 第一行
    last  最后一行  absolute n 第n行
    relative n 当前位置开始的第n行
    into 变量  把当前行的各字段值赋值给变量

游标状态变量:
    @@fetch_status  游标状态
         0 成功  -1 失败  -2 丢失
    @@cursor_rows 游标中结果集中的行数
        n 行数 -1 游标是动态的  0 空集游标
操作游标的当前行:
   current of 游标名

以下例子,在sql server 2000 测试成功

use pubs
go

declare @auid char(12),@aulname varchar(20),@aufname varchar(20), @st char(2),@auinfo varchar(50)
declare auth_cur cursor for
select au_id, au_lname, au_fname, state
from authors

open auth_cur


fetch next from auth_cur into @auid,@aulname,@aufname, @st
while (@@fetch_status=0)
  begin
    print '作者编号: '+@auid
    print '作者姓名: '+@aulname+','+@aufname
    print '所在州: '+@st
    print '--------------------------'
    fetch next from auth_cur into @auid,@aulname,@aufname, @st
  end


close auth_cur
deallocate auth_cur

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网