I have a stored procedure
DECLARE cursor FOR SELECT [FooData] From [FooTable];
OPEN cursor ;
FETCH NEXT FROM cursor INTO @CurrFooData;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @CurrFooData AS FooData;
INSERT INTO Bar (BarData) VALUES(@CurrFooData);
FETCH NEXT FROM cursor INTO @CurrFooData;
END;
CLOSE cursor
DEALLOCATE cursor
But in result I have a lot of tables, not one. How can I return one table with ‘FooData’ column and all ‘@CurrFooData’ rows?
Dmitry, I think you should really try to get rid of that cursor all together. In the second example, you’re selecting two fields
FooData1andFooData2, but in the end, you’re only ever inserting of the values….You could rewrite that second query easily – something like:
That’s all that your entire cursor and everything is really doing.
Try to avoid cursors at all costs – 99% of the time, they’re not needed – start to think in SETS of data – do not stick to procedural loops and cursor in SQL – that’s just not a good match!
If you need to output what you’ve just inserted, use the
OUTPUTclause: