Search code examples
t-sqlcursor

T-SQL error Possibly a scope issue?


I have this T-SQL code in a procedure, I'm only posting the relevant parts for brevity.

declare @tIDs TABLE (ID int)

While 1=1
    begin
    set @iCnt = @iCnt + 1
    if @iCnt > @iNumberDuplication break
    set @iLoop = 0
    declare PHcursor cursor for (select REPORT_CUBE_ID from @tPULSE_HYPERCUBE)
    open PHcursor
    While 1=1
        begin
            set @iLoop = @iLoop + 1
            if  @iLoop > @iPHrows break
            fetch next from PHcursor into @tIDs
            set @iCurrID = (select ID from @tIDs)

            set @iIDloop = @iIDloop + 1
            set @iREPORT_CUBE_ID = 90000000000000 + @iIDloop
            UPDATE @tPULSE_HYPERCUBE    SET REPORT_CUBE_ID = @iREPORT_CUBE_ID WHERE REPORT_CUBE_ID = @iCurrID
            UPDATE @tPULSE_METRIC_DETAILS   SET REPORT_CUBE_ID = @iREPORT_CUBE_ID WHERE REPORT_CUBE_ID = @iCurrID
            DELETE FROM @tIDs

        end
    CLOSE PHcursor
    DEALLOCATE PHcursor

    insert into X_PULSE_HYPERCUBE (REPORT_CUBE_ID, CM_PHY_OWNER_ID, CM_LOG_OWNER_ID,INTERVAL_C,INTERVAL_START_DATE,PULSE_METRIC_ID,USER_ID) (select * from @tPULSE_HYPERCUBE)


    end

I am getting an error that I must declare the scalar variable @tIDs I already have declared it though. Is this a scope issue? It wont go away.


Solution

  • Try this...

    declare @loop integer = 30000;
    
    while @loop > 0 begin
    
      insert into @tPULSE_HYPERCUBE (REPORT_CUBE_ID, col2, col3...)
      select REPORT_CUBE_ID + 90000000000000 + @loop, col2, col3...
      from @tPULSE_HYPERCUBE 
      where REPORT_CUBE_ID < 90000000000000;
    
      set @loop = @loop - 1;
    
    end