In this example (excerpted from a much larger T-SQL stored procedure), I defined a cursor (recordset) from which I have pulled values (stored in variables whose names start with "@") that I will use to produce "dynamic SQL" that I will then run to pull the desired results into a temporary table.
As a rule, I avoid cursors as there are usually options that are less complex and system-taxing. In the example below, given the nature of where my inputs were coming from, I had no choice but to use a cursor.
I chose this atypical example because it illustrates how I handle complex coding; specifically, how I code so the next programmer after me will understand what is going on:
- I add a lot of comments.
- I indent to facilitate understanding.
- I use verbose object names for clarity (e.g., @PRODUCT_CLASS_CODE).
The repeated "SET @SQL...CONCAT" statements were to keep the need for single and double quotation marks to a minimum since I have to add a lot of single quotes within my dynamic SQL.
Click the graphic below to view a larger version.