SQL游标怎么用

例子
table1结构如下
id    int
name  varchar(50)

declare @id int
declare @name varchar(50)
declare cursor1 cursor for         --定义游标cursor1
select * from table1               --使用游标的对象(跟据需要填入select文)
open cursor1                       --打开游标

fetch next from cursor1 into @id,@name  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中

while @@fetch_status=0           --判断是否成功获取数据
begin
update table1 set name=name+'1'
where id=@id                           --进行相应处理(跟据需要填入SQL文)

fetch next from cursor1 into @id,@name  --将游标向下移1行
end

close cursor1                   --关闭游标
deallocate cursor1

 

----------------------------------------------------------
  @@fetch_status是MSSQL的一个全局变量
  其值有以下三种,分别表示三种不同含义:【返回类型integer】
  0 FETCH 语句成功
  -1 FETCH 语句失败或此行不在结果集中
  -2 被提取的行不存在
  @@fetch_status值的改变是通过fetch next from实现的
  “FETCH NEXT FROM Cursor”
  实例:
  下面的示例用 @@FETCH_STATUS 控制在一个 WHILE 循环中的游标活动。
  DECLARE Employee_Cursor CURSOR FOR
  SELECT LastName, FirstName FROM Northwind.dbo.Employees
  OPEN Employee_Cursor
  FETCH NEXT FROM Employee_Cursor
  WHILE @@FETCH_STATUS = 0
  BEGIN
  FETCH NEXT FROM Employee_Cursor
  END
  CLOSE Employee_Cursor
  DEALLOCATE Employee_Cursor

 

实战示范:
--Intro: 统计大于N积分的用户
--Date:  2009-08-13
--Author: Silver Lee
------------------------------------
ALTER PROCEDURE dbo.TSP_InsertTjMorethanScore
@TjScore int
AS  
 declare @AuthPeoples int
 
 declare @uguid uniqueidentifier
 declare @uemail varchar(50)
 declare @MailAuthentication int
 declare @recommend int
 declare @ulogintime datetime
 
 declare cursor1 cursor for         --定义游标cursor1
 select uguid,uemail,MailAuthentication,recommend,@ulogintime from tt_userinfo where available>=@TjScore              --使用游标的对象(跟据需要填入select文)
 open cursor1                       --打开游标

 fetch next from cursor1 into @uguid,@uemail,@MailAuthentication,@recommend,@ulogintime  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中

 while @@fetch_status=0           --判断是否成功获取数据
 begin
 select @AuthPeoples=count(A.uguid) from tt_usercommend A INNER JOIN tt_userinfo B ON A.uguidcommend=B.uguid where B.MailAuthentication=1 and A.uguid=@uguid
 
 insert into tt_tjcommend(uguid,TjScore,registEmail,MailAuthentication,recommend,AuthPeoples,LastLoginTime,TjDate)
 values(@uguid,@TjScore,@uemail,@MailAuthentication,@recommend,@AuthPeoples,@ulogintime,getdate())
 
 fetch next from cursor1 into @uguid,@uemail,@MailAuthentication,@recommend,@ulogintime  --将游标向下移1行
 end

 close cursor1                   --关闭游标
 deallocate cursor1

posted @ 2009-11-05 15:56  Silver.Lee  阅读(1456)  评论(0编辑  收藏  举报