HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to FETCH from a cursor into a table variable?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
intofetchhowfromvariabletablecursor

Problem

I have a cursor defined as:

DECLARE idCursor CURSOR         
    FOR SELECT DISTINCT [id], [data]
        FROM #tempTable


And I have a variable defined as:

DECLARE @currentId TABLE (
                            [id] int,
                            [data] char(1)
                         );


But when I try to fetch the next result into @currentId

FETCH NEXT FROM idCursor INTO @currentId


I get this error:

Must declare the scalar variable "@currentId".


How can I get the result of a cursor fetch in a table? I understand that I can declare two variables and store the results individually. But for a table with many columns that would be time consuming.

Solution

No, you can't fetch scalar values from a cursor row into a table variable. You would have to declare the variables, fetch into them, and then insert:

FETCH NEXT FROM idCursor INTO @id, @data;
INSERT @currentId([id],[data]) SELECT @id, @data;


However, perhaps it's the case that you don't need a cursor at all. Why are you processing one row at a time? Why not populate the @table variable with whatever query originally populated #tempRemaining?

INSERT @currentId([id], [data])
SELECT DISTINCT [id], [data]
    FROM #tempTable;


Or even just using #tempTable by itself and skipping the table variable altogether? Maybe even skipping the #temp table? A cursor combined with a table variable and a #temp table just sounds like a nightmare.

At the risk of sounding like Celko, this seems very much like flat file processing from the 1970s... and it's even worse that there are so many columns that declaring those variables would be prohibitive.

Code Snippets

FETCH NEXT FROM idCursor INTO @id, @data;
INSERT @currentId([id],[data]) SELECT @id, @data;
INSERT @currentId([id], [data])
SELECT DISTINCT [id], [data]
    FROM #tempTable;

Context

StackExchange Database Administrators Q#107939, answer score: 7

Revisions (0)

No revisions yet.