sql server 游标学习小记

  语言中有好多循环的语句如for,while,foreach,但在sql语句中你怎么去循环一个表一次取出其中的数据呢,这就需要用到下面我们要讲的游标了,游标相当于语言中的循环语句

  声明一个游标:declare CursorNull cursor

  把查到的变量值赋给游标:fetch next from CursorNull into @A0100,@A2530,@A2507
  开始循环:while(@@fetch_status = 0)
  关闭游标:CLOSE CursorNull;
  删除游标与游标名之间的关联: deallocate CursorNull;

  下面附上一个自己写的游标写例子吧!希望对你们有帮助 

 declare @iNullCount  int;--年终考核记录条数个数
declare @A0100 varchar(max);
declare @A2530 varchar(max);
declare @A2507 varchar(max);
select @iNullCount=(select count(*) from dbo.A025A001);--查询年终考核表中记录的条数
--如果记录的条数大于0,进行修改
if(@iNullCount>0)
begin
 declare CursorNull cursor for select A0100,A2530,A2507 from dbo.A025A001
 open CursorNull
  fetch next from CursorNull into @A0100,@A2530,@A2507
  while(@@fetch_status = 0)
    begin
       select @A2530= (
                select n0105 from B001C902 where
                id=(select top 1 (a9001) as a2530 from dbo.A090A001 where
                a0100=(select a0100 from dbo.A025A001 where a0100=@A0100)
                order by a9005 desc))
       select @A2507= (
                select Description  from dbo.sr_codeitem where
                Code=(select top 1 (A0405) from A004A001 where
                A0100 = (select a0100 from dbo.A025A001 where a0100=@A0100)
                order by A0430 desc) and CodeId='AM')
           if(@A2530<>'')
      
           begin
             update dbo.A025A001 set A2530=@A2530 where a0100=@A0100
          end 
           if(@A2507<>'')
      
           begin
             update dbo.A025A001 set A2507=@A2507 where a0100=@A0100
          end          
        fetch next from CursorNull into @A0100,@A2530,@A2507
      end 
 CLOSE CursorNull;
 deallocate CursorNull;
End

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值