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

你可能感兴趣的:(数据库,server,sql语句,记录,next)