all groups > sql server programming > july 2006 >
You're in the

sql server programming

group:

Can you LOOP through records with 2005 T-SQL?


Re: Can you LOOP through records with 2005 T-SQL? Dan Guzman
7/29/2006 4:23:50 PM
sql server programming: [quoted text, click to view]

You can use a server-side cursor, just like older versions. Example below.
However, set-based processing usually performs better.

DECLARE @Col1 int, @Col2 int

DECLARE MyCursor CURSOR
LOCAL FAST_FORWARD READ_ONLY FOR
SELECT Col1, Col2 FROM dbo.MyTable
OPEN MyCursor
WHILE 1 = 1
BEGIN
FETCH NEXT FROM MyCursor INTO @Col1, @Col2
IF @@FETCH_STATUS = -1 BREAK
EXEC AnotherProc @Col1, @Col2
END
CLOSE MyCursor
DEALLOCATE MyCursor

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Re: Can you LOOP through records with 2005 T-SQL? Aaron Bertrand [SQL Server MVP]
7/29/2006 5:23:55 PM
DECLARE @ColumnA <datatype>, @ColumnB <datatype>;

DECLARE foo CURSOR
LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
SELECT ColumnA, ColumnB FROM table;

OPEN foo;

FETCH NEXT FROM foo INTO @ColumnA, @ColumnB;

WHILE (@@FETCH_STATUS != -1)
BEGIN
EXEC dbo.AnotherStoredProcedure @ColumnA, @ColumnB;
FETCH NEXT FROM foo INTO @ColumnA, @ColumnB;
END

CLOSE foo;

DEALLOCATE foo;


But you can probably get around this in various ways, since processing a
table row by row is almost guaranteed to be slow.



[quoted text, click to view]

Can you LOOP through records with 2005 T-SQL? D. Patrick
7/29/2006 9:09:42 PM
I want to do a loop inside a stored procedure, such as:

FOR EACH record in (SELECT * from table)
PASS FIELD A, B TO ANOTHER STORED PROCEDURE
END

Is this possible with 2005 now? If yes, how?

Re: Can you LOOP through records with 2005 T-SQL? D. Patrick
7/30/2006 3:58:58 AM
Thank you both. Works great.

[quoted text, click to view]

AddThis Social Bookmark Button