'Must declare the scalar variable' in FETCH



  • I'm new in StackExchange, working with Microsoft SQL Server (also new). I'm trying to recover data from a table using a cursor. I've declared all temporary fields but I'm getting an error when I do the FETCH NEXT. The code is:

    CREATE TABLE #RedsRisk (
        PolicyCode int,
        LocationCode int,
        OriginalCurrency varchar(10),
        BusinessUnitCode varchar(30)
    );
    

    --I feed correctly the table in the process, then

    DECLARE @PolicyCode AS int, 
            @LocationCode AS int, 
            @OriginalCurrency AS varchar(10), 
            @BusinessUnitCode AS varchar(30);
    

    DECLARE RRisk CURSOR FOR
    SELECT
    PolicyCode,
    LocationCode,
    OriginalCurrency,
    BusinessUnitCode
    FROM #RedsRisk;

    OPEN RRisk;

    FETCH NEXT FROM RRisk INTO
    @PolicyCode,
    @LocationCode,
    @OriginalCurrency,
    @BusinessUnitCode;

    And then I have the error:

    Msg 137. Must declare the scalar variable "@PolicyCode".

    What's wrong here?

    Thanks.



  • I can recreate the described error but only when highlighting the FETCH NEXT FROM Part and executing that (like @J.D. commented).

    When completing the example with CLOSE RRisk, DEALLOCATE RRisk and DROP TABLE #RedsRisk and not selecting any code the code runs multiple times without error.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2