Wednesday, April 18, 2007

Cursors

You need a variable to hold the cursor value each time, so declare that first. Afterwards, we declare the cursor and set a one column returning select statement. These are teh values we will curse through... after this we'll do a couple things that assure the list of things we're cursing through hasn't ended, then we'll get into contents of what happens at each itteration, and then we'll wrap up by deallocating the cursor.


DECLARE @AuthorID char(11)

DECLARE c1 CURSOR FOR
SELECT au_id
FROM authors

OPEN c1


FETCH NEXT FROM c1
INTO @AuthorID


WHILE @@FETCH_STATUS = 0
BEGIN

PRINT @AuthorID

FETCH NEXT FROM c1
INTO @AuthorID
END

CLOSE c1
DEALLOCATE c1


And that's the gist of it. Source is here.

No comments: