Brettb.Com
  HOME | ABOUT ME | BIOTECHNOLOGY | ARTICLES | GALLERY | CONTACT
Search: Go
TECHNICAL ARTICLES
 ASP
 ASP.NET
 JavaScript
 Transact SQL
 Other Articles
 Software Reviews

PHOTO GALLERIES
 Canon EOS 300D Samples
 Akihabara Maids!
 More Galleries...

TRAVEL LOG
 2009: China
 2008: Tokyo
 2007: Tokyo
 2006: Hong Kong
 2005: New York City

MORE STUFF
 Search Engine Optimisation
 Build an ASP Search Engine
 My Tropical Fishtank
 Autoglass
 SQL Month Name
 SQL Get Date Today
 SQL Year Month
 Other New Stuff...

POPULAR STUFF
 Regular Expressions
 Index Server & ASP
 JavaScript Ad Rotator

Home > Articles > Transact SQL Programming Articles

SQL Server Help: Using Cursors in Transact-SQL

What are cursors and how are they useful?

It is useful to know how to use Cursors in SQL Server's Transact SQL, as they can sometimes be used to perform SQL queries that would be very difficult to write without them. Unfortunately Cursors can be quite resource intensive, so they should only be used if there is no alternative way of writing a query.

The most useful feature of Cursors is the ability for them to process a set of database rows and perform some operation on each of the rows in turn. For example, the SQL query below uses a cursor to return a results set for each employee's orders:

USE Northwind
GO

DECLARE @Counter INT
DECLARE @EmployeeID INT

DECLARE Employees_Cursor CURSOR FOR
SELECT EmployeeID FROM Employees
OPEN Employees_Cursor
FETCH NEXT FROM Employees_Cursor into @EmployeeID
WHILE @@FETCH_STATUS = 0
BEGIN

SELECT * FROM Orders WHERE EmployeeID = @EmployeeID


FETCH NEXT FROM Employees_Cursor into @EmployeeID
END
CLOSE Employees_Cursor
DEALLOCATE Employees_Cursor

Useful Links

  • The SQL Documentation Tool automatically builds technical documentation for Microsoft SQL Server databases, saving you time and money. A trial version is available for download.

  Site Map | Privacy Policy

All content is 1995 - 2012