views:

36

answers:

2

i want to implement for loop to fetch the data from select statement.

A: 

Do you mean Cursor?

If so, check the links.

http://www.mssqltips.com/tip.asp?tip=1599

http://www.sqlteam.com/article/cursors-an-overview

hgulyan
To which I'd say: just DON'T - don't even get started with cursors - do not use cursor, they're a) unnecessary, b) a performance killer, and c) evil
marc_s
You're right, but in some cases, especially if it's one time action, cursor is the only(or the best) solution.
hgulyan
A: 

Your asking abour cursors, but cursors are evil, because they have a bad performance. Mosts of times there is a better aproach to solve the problem without using it. But if you still want to do it, here is a very simple snippet of code.

DECLARE @somevariable VARIABLE_TYPE_HERE
DECLARE @sampleCursor CURSOR
SET @sampleCursor = CURSOR FOR
SELECT somefield... from bla bla bla...
OPEN @sampleCursor 
FETCH NEXT
FROM @sampleCursor INTO @somevariable 
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @somevariable 
FETCH NEXT
FROM @sampleCursor INTO @somevariable 
END
CLOSE @sampleCursor 
DEALLOCATE @sampleCursor 
Jonathan