Cursors
SQL Server is a relational database management system (RDBMS), and T-SQL is a transactional programming language. This means that it is designed to execute its work in all-or-nothing runs. The database engine is optimized to work in this manner.
Cursors however, like WHILE loops, break away from the transactional nature of T-SQL and allow for programmers to treat each result of a SELECT statement in a certain way by looping through them.
In SQL Server the cursor is a tool that is used to iterate over a result set, or to loop through each row of a result set one row at a time.
Example
Step 1: Declare variables to hold the output from the cursor.
Step 2: Declare the cursor object.
Step 3: Assign the query to the cursor.
Step 4: Open the cursor.
Step 5: Fetch the first row.
Step 6: Loop until there are no more results. In the loop print out the ID and the name from the result set and fetch the net row.
Step 7: Close the cursor.
Step 8: Deallocate the cursor to free up any memory or open result sets.
Last updated