DF022: The cursor name is reused.

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

Category

BEST PRACTICE

Message

The cursor name is reused.

Description

A cursor with the same name has been declared earlier. Avoid reusing cursor names.

Additional information

It’s important to avoid reusing cursor names to prevent potential conflicts and confusion in the code. Unique cursor names ensure clarity and maintainability, making it easier to understand and debug the code. Additionally, reusing cursor names can lead to unintended consequences or errors, especially in complex or multi-part scripts.

Noncompliant code example

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

Compliant solution

DECLARE cur CURSOR LOCAL FOR
SELECT CustomerID FROM dbo.Customer
OPEN cur
FETCH NEXT FROM cur INTO @CustomerId
 
DECLARE curCountry CURSOR LOCAL FOR
SELECT CountryID FROM dbo.Country
OPEN curCountry
FETCH NEXT FROM curCountry INTO @CoutryId