Search code examples
sql-servert-sqldatabase-cursor

Can I reset cursor's position to the beginning?


As in the topic. Can I simply reset cursor's position to the beginning in Transact-SQL, so it can run again over the table? I want to reset it in the following context:

DECLARE @userID INT
DECLARE user_cursor CURSOR FOR SELECT userID FROM users

WHILE /* some condition */
BEGIN
...

    FETCH NEXT FROM user_cursor INTO @userID

    IF @@FETCH_STATUS = 0
    BEGIN
        /*... here goes the reset of the cursor ...*/
    END

...
END

Solution

  • you need to declare your cursor as scroll, like this

    declare c scroll cursor for (select statement); 
    

    then at any time for locating to the first just use the following

    fetch first from c;