游标

    SQL语句提供了对记录集合的各种操作,但若需要进行一些针对记录集中的单个记录进行
判断,然后再执行的操作,有时就不能实现,而使用游标可以解决这一1问题:


   1:游标的创建和使用
      游标的创建分为5个步骤:
     (1)定义游标:( 查下语法规则)
        ex:
      declare  T_log_cursor  CURSOR
FOR
  SELECT  ID,F_logText,F_logType,datee  from   dbo.T_log
  where F_logType='3' order by  datee
      (2)  打开游标:
          --2打开游标,实际上执行定义游标内的select语句,形成游标记录集填充游标,并把游标的指针定位在第一条记录前
open T_log_cursor 
declare  @cur_rowcount  int
select   @cur_rowcount=@@CURSOR_ROWS
print @cur_rowcount
      (3)读取游标
     --读取游标(fetch  cursor)
declare  @id int
declare  @F_logType nvarchar(50)
declare  @F_logText  nvarchar(50)
declare  @datee  Datetime
fetch  next  from  T_log_cursor
into  @id,@F_logText,@F_logType,@datee  --将记录各字段内容保存到对应的变量中
while  @@FETCH_STATUS=0
begin 
   print  (str(@id)+''+@F_logText+''+@F_logType+''+Convert(nvarchar,@datee))
   fetch  next  from  T_log_cursor
into  @id,@F_logText,@F_logType,@datee
end


(4) 关闭游标
    close T_log_cursor
(5) 释放游标
    deallocate  T_log_cursor
  
          
一个连贯的句子就是:
    select  *  from  dbo.T_log
--1定义游标
declare  T_log_cursor  CURSOR
FOR
  SELECT  ID,F_logText,F_logType,datee  from   dbo.T_log
  where F_logType='3' order by  datee

--2打开游标,实际上执行定义游标内的select语句,形成游标记录集填充游标,并把游标的指针定位在第一条记录前
open T_log_cursor 
--3读取游标(fetch  cursor)
declare  @id int
declare  @F_logType nvarchar(50)
declare  @F_logText  nvarchar(50)
declare  @datee  Datetime
fetch  next  from  T_log_cursor
into  @id,@F_logText,@F_logType,@datee  --将记录各字段内容保存到对应的变量中
while  @@FETCH_STATUS=0
begin 
   print  (str(@id)+''+@F_logText+''+@F_logType+''+Convert(nvarchar,@datee))
   fetch  next  from  T_log_cursor
into  @id,@F_logText,@F_logType,@datee
end


--4关闭游标
    close T_log_cursor
--5释放游标
    deallocate  T_log_cursor
  


3:游标使用中应注意的问题:
   (1)  全局变量:
           全局变量@@fetch_status 用来存储fetch语句执行状态的信息,可使用查询语句
           select  @@fetch_status  来完成上述查询任务。
 
          全局变量@@rowcount记载到最近一次fetch操作为止,从游标记录集中共返回的行数,同样,可
          使用查询语句select @@rowcount 来进行查看:

     游标的使用会在几个方面影响系统的性能:
    导致页锁和表锁的增加;
    导致网络通信量的增加
    服务器处理相应指令的额外开销:
    因此尽管游标控制比较灵活,但会损失速度,这就存在一个游标使用的优化:


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值