Rule Definition
Cursors are loops which number of iterations is based on the number of rows returned by an SQL query. Having a cursor inside a loop means having an SQL query inside a loop which number of iterations can be very high (dependent on the data returned from the database).
This iterative pattern has proved to be very dangerous for application performance and scalability. Database servers handle in a much better set-oriented pattern rather than pure iterative ones.
Remediation
The remediation is often to replace the iterative approach with a set-oriented one and thus replace a cursor with a query.
Violation Code Sample
CREATE PROCEDURE Salary
as
begin
DECLARE @Dep_Id INT
DECLARE @Emp_Id INT
DECLARE EmpCursor CURSOR FOR
SELECT dep_id, id FROM employee
OPEN EmpCursor
FETCH NEXT FROM EmpCursor INTO @Dep_Id, @Emp_Id
WHILE 1=1
BEGIN
UPDATE employee SET salary = (salary * 1.1) WHERE id = @Emp_Id
FETCH NEXT FROM EmpCursor INTO @Dep_Id, @Emp_Id
END
CLOSE EmpCursor
DEALLOCATE EmpCursor
end
GO
Fixed Code Sample
CREATE PROCEDURE Salary
as
begin
UPDATE employee SET salary = (salary * 1.1)
end
GO
Reference
https://www.mssqltips.com/sqlservertip/6148/sql-server-loop-through-table-rows-without-cursor/
https://www.dotnettricks.com/learn/sqlserver/sql-server-cursor-alternatives
https://www.sqlshack.com/using-sql-server-cursors-advantages-and-disadvantages/
Related Technologies
Technical Criterion
CWE-1050 - Excessive Platform Resource Consumption within a Loop
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.