1. 游标概述
由于SQLServer是使用结果集来处理数据,因此当需要逐条处理表中的记录时就必须使用游标来处理。游标一般被定义和使用在服务器端,当游标
开启后,服务器为每一个游标保持一个指针,用来前后检索数据。当游标大量的使用时,服务器端的负担很重。
2. 游标的特性
A.种类:动态游标、静态游标和、键集游标和仅向前游标;


    动态游标(Dynamic):可以监测对结果集的所有操作(增、删、改),前后滚动。当滚动时,动态游标反映结果集中所做的修改。


    静态游标(Static):不能监测其他用户的所有操作,前后滚动。以快照形式把当前表存到Tempdb临时表中,执行指令后将结果集带给游标,
                        新的数据值不会显示在静态游标中。


    键集游标(Keyset):可以监测用户对数据的修改,前后滚动。在Tempdb中利用主键实现对数据检索。


    对于仅向前游标(Fast_only):该游标只能向前滚动。


B.功能:可设置游标结果为只读的,或可更新的;游标的移动类型等;
3 游标的状态--声明
Declare  cursor_ name Cursor for Select 语句
--打开
Open cursor_name
--提取数据
Fetch next from cursor_name into 变量1,变量2
--关闭游标
 Close cursor_name
--释放游标
Deallocate cursor
4.例题
事例1、查询某个书店的订单的数量--存储过程名称 StoreOrderSum
--输入参数:@StoreName varchar(30) 书店名称
--返回参数:@SumQty int 订单数量
--定义静态游标名称:SalesQty
Create procedure StoreOrderSum
@StoreName varchar(30)
As
Declare SalesQty cursor static
For  select qty from sales
where stor_id= (select stor_id from stores where stor_name like @storename+'%')
Open SalesQty
De4clare @Qty smallint
Declare @sumqty int
select @qty=0
select @sumqty=0
Fetch next from SalesQty into @Qty --游标首次打开时指针指为 Bof 必须移动到第一条记录上
While @@fetch_status=0 --游标状态函数 ,当值不为0时,游标移动指针
--可能到记录末或出现错误
Begin
   Set @Sumqty=@Sumqty+@Qty    --累计订单数量
   Fetch next from SalesQty into @Qty --按查询结果集字段顺序依次将
--当前记录中的数据给变量赋值
End
Close Salesqty
Deallocate Salesqty
Return @SumQty
测试:
Begin
Declare @ff int
Exec @ff=OrderNum 'Bookbeat'
Print cast(@ff as varchar)
End
例题2、打印每名学生的成绩,并对其评定。--声明游标
declare cursor_stu cursor
static
for select name,cj from student
declare
  @name varchar(8),
@cj int
    --打开游标
open cursor_stu
--提取游标
fetch next from cursor_stu into @name ,@cj
while (@@fetch_status=0)
begin
      if @cj<60
        print @name+cast(@cj as char(8))+’不及格’
      else
        if @cj>=60 and @cj<70
         print @name+cast(@cj as char(8))+’ 及格’
        fetch next from cursor_stu into @name,@cj
end
--关闭游标
  close cursor_stu
--释放游标
  deallocate cursor_stu



事例3:将多行数据按每二行合并一行

sql server代替游标 ms sql server支持的游标类型_数据

--声明游标

declare cursor_AA cursor static

for select ID,name from AA

declare  @ID_A varchar(10),  @NAME_A VARCHAR(10),

         @ID_B varchar(10),  @NAME_B VARCHAR(10),

         @ROWS INT,  @ROW INT

SET @ROW=0

    --打开游标

open cursor_AA

--提取游标

SET @ROWS=@@CURSOR_ROWS

SELECT @ROWS

while (@ROW<@ROWS)

begin

       fetch next from cursor_AA into @ID_A,@name_A

       SET @ROW=@ROW+1

       fetch next from cursor_AA into @ID_B,@name_B

       SET @ROW=@ROW+1

       INSERT INTO BB(ID_A,NAME_A,ID_B,NAME_B)

              VALUES(@ID_A,@NAME_A,@ID_B,@NAME_B)

       SET @ID_A=''

       SET @NAME_A=''

       SET @ID_B=''

       SET @NAME_B=''

end

close cursor_AA --关闭游标

deallocate cursor_AA--释放游标

sql server代替游标 ms sql server支持的游标类型_数据库_02