Here is the basic structure of a cursor, with comments to explain each section:
/* Create one or more variables to capture the values returned by the cursor query. */
declare @my_cursor_value as varchar(100)
/* Declare the cursor with the SELECT statement. */
/* Use fast_forward to optimize the cursor when you don't need to move backward in it. */
/* Use local to isolate the cursor so there is no chance of conflict with another instance of a cursor with the same name. */
declare [my_cursor] cursor fast_forward local for
select
[my_column]
from
[my_table]
/* Open the cursor, which prepares the query results. */
open [my_cursor]
/* Get the first set of values from the cursor
and put the results in the defined parameters. */
fetch next from
[my_cursor]
into
@my_cursor_value
/* Start a loop to use the already-fetched values,
then pull the next set of cursor values. */
while @@Fetch_Status = 0
/* Enclose the steps you want to take using BEGIN...END */
begin
print @my_cursor_value
/* Always include FETCH NEXT to avoid an endless loop. */
fetch next from [my_cursor] into @my_cursor_value
end
/* Drop the results. */
close [my_cursor]
/* Release the cursor definition from memory. */
deallocate [my_cursor]
Here is the code stripped of comments, for a quick copy-and-paste of the essential structure:
declare @my_cursor_value as varchar(100)
declare [my_cursor] cursor fast_forward local for
select
[my_column]
from
[my_table]
open [my_cursor]
fetch next from
[my_cursor]
into
@my_cursor_value
while @@Fetch_Status = 0
begin
print @my_cursor_value
fetch next from [my_cursor] into @my_cursor_value
end
close [my_cursor]
deallocate [my_cursor]