Saturday, April 5, 2008

SQL Cursor Example

I am rarely required to do anything very difficult in SQL, and really SQL doesn’t get THAT difficult so this is maybe the second time I have used a cursor. What follows is a very basic SQL cursor example that I used earlier today. If it mattered more and I had more time I probably would have taken a look at doing this without using a cursor as cursors are non-performant. None-the-less it was a fun exercise. Another fine example,including the non-cursor implementation, can be seen here http://www.sql-server-performance.com/articles/per/operations_no_cursors_p1.aspx


DECLARE @customerId int,

@firstName nvarchar(255)


DECLARE Customer CURSOR FOR

SELECT customerId,

firstName,

FROM CustomerTable

OPEN Customer


FETCH Customer INTO @customerId,

@firstName


WHILE @@Fetch_Status = 0

BEGIN

-- row by row operations

Print

FETCH Customer INTO @customerId,

@firstName,

@vchCustomerName

END

CLOSE Customer

DEALLOCATE Customer

Go

No comments: