Thursday, August 25, 2011

What is a SQL Cursor ?


 SQL Server is very good at handling sets of data. For example, you can use a single UPDATE statement to update many rows of data. There are times when you want to loop through a series of rows a perform processing for each row. In this case you can use a cursor.

 Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row.  In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

/* First, declare items in the cursor */
DECLARE @cur_CustomerID nchar (5),
@cur_ContactTitle nvarchar(30)
/* Next, declare the cursor itself */
DECLARE changes_cursor cursor
for SELECT customerid, contacttitle
FROM dbo.customers
OPEN changes_cursor
/* first fetch starts the process */
FETCH changes_cursor INTO @cur_CustomerID, @cur_ContactTitle
WHILE @@fetch_status = 0 /* while there's still records to process */
BEGIN
IF @cur_ContactTitle = 'owner'
BEGIN
UPDATE orders SET [freight] = 0
WHERE CustomerID = @cur_CustomerID
END
/* keep fetching till done */
FETCH changes_cursor INTO @cur_CustomerID, @cur_ContactTitle
END
CLOSE changes_cursor
DEALLOCATE changes_cursor


Read more:



No comments:

Post a Comment