Using Cursors with Microsoft SQL Server
Posted September 19th, 2008 in Microsoft SQL Server
Just about everything I've ever read about cursors for Microsoft SQL Server say not to use them for a variety of reasons. There are some cases where using a cursor is a lot simpler or faster etc than using another method and so I've decided to quickly document an examaple of a SQL Server cursor here for my own reference.
A database cursor is a way of traversing data from a select query within SQL. With a database server like Microsoft SQL Server you would normally run a cursor within a stored procedure. Anway, without further ado, here is my example:
DECLARE
@id int,
@foo varchar(100),
@bar varchar(100)
DECLARE mycursor CURSOR READ_ONLY
FOR SELECT id, foo, bar
FROM foobar
WHERE somefield = 'somevalue'
OPEN mycursor
FETCH NEXT FROM mycursor
INTO @id, @foo, @bar
WHILE @@FETCH_STATUS = 0
BEGIN
... do something ...
FETCH NEXT FROM mycursor
INTO @id, @foo, @bar
END
CLOSE mycursor
DEALLOCATE mycursor
I'm not going to explain further what each step in the process does - this is really just a quick reference example layout. You can easily modify it to suit your data and table structure.
Recent posts:
- MySQL queries for article summaries part 2 of 2 (Tuesday, January 6th 2009)
- Aims for 2009 (Monday, January 5th 2009)
- Weekly Roundup - January 5th 2008 (Monday, January 5th 2009)
- MySQL queries for article summaries part 1 of 2 (Sunday, January 4th 2009)
- 2008 Summary of Posts (Saturday, January 3rd 2009)
- 2008 / 2009 overview (Friday, January 2nd 2009)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
Posts are made using the following schedule (although it may vary some weeks): Mondays & Fridays = PHP; Tuesdays & Saturdays = MySQL; Wednesdays & Sundays = Javascript/jQuery; Thursdays = HTML/CSS.
