我对SQL数据库游标的理解

  1. 什么是游标?
    游标是SQL 的一种数据访问机制。可以将游标简单的看成是查询的结果集的一个指针,可以根据需要在结果集上面来回滚动,浏览需要的数据。
  2. 游标的作用是什么?
    可以保存查询结果,方便查询,可以创建一个游标可以多次使用。提高查询效率。
  3. 实例
    –声明游标
    declare cur_cust_level Cursorfor select ID,ConsumerAmount from Customers
    –打开游标
    open cur_cust_level
    –浏览数据,取数据ID,CustomerAccount
    –取数据–拿之前先定义两个变量
    declare @id int
    declare @Cacount int
    fetch next from cur_cust_level into @id,@Cacount
    –循环往下
    while(@@FETCH_STATUS=0)
    begin
    print @id+@Cacount
    fetch next from cur_cust_level into
    @id,@Cacount End 游标
    –关闭游标close cur_cust_level
    –释放游标deallocate cur_cust_level
    declare cur_statis Cursor
    for
    select year(ConsumerTime) yy,month(ConsumerTime) mm,day(ConsumerTime)dd,sum(ConsumerAmount) yye from Customers
    group by year(ConsumerTime),month(ConsumerTime),day(ConsumerTime)
    –打开游标
    open cur_statis
    –浏览数据并获取
    declare @yy varchar(50)
    declare @mm varchar(50)
    declare @dd varchar(50)
    declare @yye int
    fetch next from cur_statis into @yy,@mm,@dd,@yye
    while(@@FETCH_STATUS=0)
    begin
    insert into Statis values(@yy,@mm,@dd,@yye)
    fetch next from cur_statis into @yy,@mm,@dd,@yyeend
    –关闭游标
    close cur_statis
    deallocate cur_statis
    select * from Statis
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值