1. Declaring cursors
DECLARE cursor name CURSOR SELECT statement (NOTE: This must be a SELECT statement)
2. Open the cursor
OPEN cursor Name
3. Reading cursor data
Fetch [Next | Prior | First | Last | Absolute N | Relative N] from cursor name into @name1, @name2 ...
while (@ @FETCH_STATUS = 0)
BEGIN
--The SQL statement to execute
FETCH NEXT from cursor name
END
4. Close the cursor
The CLOSE cursor name. The cursor cannot be read after closing, but can be opened again using the Open statement
5. Releasing cursors
The DEALLOCATE cursor name. Delete cursor, no longer available
Example:
Declare @index int;Declare @userId uniqueidentifier;Set @index=1;DeclareUser_curcursor for SelectUserid fromT_userOrder byCreatetimedescOpenUser_curFetch Next fromUser_cur into @userId while(@ @FETCH_STATUS=0)begin UpdateT_userSetSort=@index whereUserid=@userId; Set @index=@index+1; Fetch Next fromUser_cur into @userIdEndCloseuser_cur;deallocateUser_cur;
Reference Link: http://www.cnblogs.com/youngberry/archive/2009/07/17/1525647.html
SQL Server Cursors use