Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table variable inside a cursor loop

I noticed that when I declare a table variable inside a cursor loop, the variable persist trough the cursor lifetime. my question is, if there is a way to declare the variable in such a way that it's lifetime will only persist trough the iteration? here is a sample:

DECLARE @SourceTable TABLE(Id INT IDENTITY(1,1),Remarks VARCHAR(10))
INSERT INTO @SourceTable VALUES ('First')
INSERT INTO @SourceTable VALUES ('Second')
INSERT INTO @SourceTable VALUES ('Third ')

/* declare variables */
DECLARE @variable INT

DECLARE my_cursor CURSOR FAST_FORWARD READ_ONLY FOR SELECT Id FROM @SourceTable

OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @variable

WHILE @@FETCH_STATUS = 0
BEGIN
    --Dose not creates a new instance
    DECLARE @VarTable TABLE (Remarks VARCHAR(10))

    INSERT INTO @VarTable
    SELECT TOP 1 Remarks FROM @SourceTable
    WHERE Id = @variable


    --Works as intended if you drop when done
    CREATE TABLE #TempTable  (Remarks VARCHAR(10))

    INSERT INTO #TempTable
    SELECT TOP 1 Remarks FROM @SourceTable
    WHERE Id = @variable

    DROP TABLE #TempTable

    FETCH NEXT FROM my_cursor INTO @variable
END

CLOSE my_cursor
DEALLOCATE my_cursor

SELECT * FROM @VarTable

But it gets even more confusing. if you try to query the temptable outside the cursor, you will get an error. it appears as if temp table is the only correct way for such situation?

like image 579
Slime recipe Avatar asked Sep 02 '25 15:09

Slime recipe


1 Answers

The scope of a TSQL variable is from it's declaration to the end of batch.

so in inside cursor every loop you need to delete the data from table variable

I know its strange that in every loop table variable inside cursor is declared but that's how it works

Declare the table variable outside and perform Insert/Delete statements inside CURSOR

DECLARE @VarTable TABLE (Remarks VARCHAR(10))

DECLARE my_cursor CURSOR FAST_FORWARD READ_ONLY FOR SELECT Id FROM @SourceTable

OPEN my_cursor
.......
.......
  DROP TABLE #TempTable

  DELETE FROM @VarTable

  FETCH NEXT FROM my_cursor INTO @variable
END
....
like image 54
Pரதீப் Avatar answered Sep 05 '25 13:09

Pரதீப்