DF021: The cursor has not been opened.

The topic describes the DF021 T-SQL code analysis rule.

Category

EXECUTION RULES

Message

The cursor has not been opened.

Description

It is recommended to explicitly open the cursor.

Additional information

Explicitly opening the cursor allows you to explicitly define when the cursor starts fetching rows from the result set. By explicitly opening the cursor, you can also specify options such as the cursor type (e.g., forward-only, static, dynamic) and other properties. This helps optimize cursor performance and behavior according to your specific requirements.

Additionally, explicitly opening the cursor makes the code more readable and understandable for other developers who may review or maintain it in the future. It clearly indicates the intent to use the cursor and its associated result set.

Noncompliant code example

DECLARE cur CURSOR LOCAL FOR SELECT
  CustomerID
FROM dbo.Customer
FETCH NEXT FROM cur INTO @CustomerId

Compliant solution

DECLARE cur CURSOR LOCAL FORWARD_ONLY FOR SELECT
  CustomerID
FROM dbo.Customer
OPEN cur
FETCH NEXT FROM cur INTO @CustomerId