Search code examples
sqlsql-servercursor

Cursor Infinite Loop before Return Keyword


I have this code snippet in my stored procedure

FETCH NEXT FROM MY_CURSOR into @id
WHILE @@FETCH_STATUS = 0
BEGIN

    IF @Res == NULL
    BEGIN 
        SET @Var = false
        RETURN;
    END
    
    --some other code here
    
    FETCH NEXT FROM MY_CURSOR into @id
    END

If for example the variable @Res is NULL and the variable @Var is set to FALSE then the RETURN keyword is called, will it cause an infinite loop if I don't call the FETCH NEXT before the RETURN keyword?

UPDATE 1: ok, so apparently when it enters the if-else block, and the control proceeds to the RETURN block, the control goes out of the WHILE loop. My goal is for the loop to continue after setting the @Var variable.

UPDATE 2: Accepted Gordon Linoff's answer about checking for null values.


Solution

  • This logic:

    IF @Res == NULL
    

    does not do what you expect. Almost any comparison to NULL returns NULL -- which is treated as false.

    The correct logic is:

    IF @Res IS NULL
    

    That said, you should probably be avoiding cursors in your code. And you should learn about NULL values in SQL.