CODECUBE VENTURES

SQL Server Cursor

This is an example of how you can use cursors to let the server handle some of the processing


Declare empid_cursor cursor
--This SQL sTatement will be the contents of the cursor
--The example shown here gets all the empids where they
--Joined before the first of the year
for SELECT userid FROM users
WHERE dateJoined < 01/01/2001
for read only

Open empid_cursor
While (0 = 0) Begin

declare @userID varchar(15)
declare @datejoined datetime
fetch  userid_cursor into @userid
If (@@Fetch_Status <>0) Break

Perform any actions here get their join date


SELECT @datejoined = datejoined FROM users
WHERE userid = @userid

Were gonna insert a record for every userid into a table


INSERT INTO contest (userid, datejoined)
VALUES (@userid, @datejoined)

End
Close empid_cursor
Deallocate empid_cursor

Of course there are other ways to go about this, but this is just a demo of how this technique could be used.

Latest post: Digging Up the First Version of CodeCube

See more in the archives