A technical blog about my projects, challenges, and discoveries in the world of data warehousing using SQL Server, Power BI Desktop, DevExpress, and more.

Thursday, January 16, 2020

Basic T-SQL Cursor syntax

I'm always looking for the basic syntax to create a cursor. I do it rarely, as is proper for SQL Server, so I have to remind myself of the details. The examples on Microsoft's online documentation are too elaborate, and I have to eliminate pieces in my mind to get to the core elements. Instead, I'm writing this blog post to cut to the chase. The varchar(100) specification is just a placeholder for whatever data type you need to store the value from the cursor query.

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]


Followers