CURSOR FETCH on SQL Server

although CURSOR and FETCH is classified as ‘evil‘ in SQL server, but sometimes we cannot avoid using it. Cause in some scenarios, pivot and other similiar method to perform looping and transformation is not sufficient enough. here’s a link of good example implementing cursor.

all example copy from microsoft sites,

http://msdn.microsoft.com/en-us/library/ms180152.aspx

A. Using FETCH in a simple cursor

The following example declares a simple cursor for the rows in the Person.Person table with a last name that starts with B, and uses FETCH NEXT to step through the rows. The FETCH statements return the value for the column specified in DECLARE CURSOR as a single-row result set.

B. Using FETCH to store values in variables

The following example is similar to example A, except the output of the FETCH statements is stored in local variables instead of being returned directly to the client. The PRINT statement combines the variables into a single string and returns them to the client.

C. Declaring a SCROLL cursor and using the other FETCH options

The following example creates a SCROLL cursor to allow full scrolling capabilities through the LAST, PRIOR, RELATIVE, and ABSOLUTE options.

Leave A Comment

Your email address will not be published. Required fields are marked *