1. 程式人生 > >SQL Server 遊標使用

SQL Server 遊標使用

pri 再次 sta order ext ast lar etime archive

1.聲明遊標
DECLARE 遊標名 CURSOR SELECT語句(註:此處一定是SELECT語句)
2.打開遊標
OPEN 遊標名
3.讀取遊標數據
Fetch [Next | Prior | First | Last | Absolute n | Relative n ] From 遊標名 INTO @name1,@name2...
WHILE(@@FETCH_STATUS = 0)
BEGIN
--要執行的SQL語句

FETCH NEXT FROM 遊標名
END

4.關閉遊標
CLOSE 遊標名。關閉後不能對遊標進行讀取等操作,但可以使用OPEN語句再次打開
5.釋放遊標
DEALLOCATE 遊標名。即刪除遊標,不可再使用

例子:

declare @index int;
declare @userId uniqueidentifier;
set @index=1;
declare user_cur cursor
for select UserId from T_User order by CreateTime desc open user_cur fetch next from user_cur into @userId while (@@FETCH_STATUS=0) begin update T_User set Sort=@index where UserId=@userId; set @index=@index+1; fetch next from user_cur into @userId end close user_cur; deallocate user_cur;

參考鏈接:http://www.cnblogs.com/youngberry/archive/2009/07/17/1525647.html

SQL Server 遊標使用