I'm writing a Stored Procedure in SQL Server 2005 that declares a CTE (Common Table Expression) called foo.
foo calls itself recursively, but loops infinitely when one of the SP's parameters (@bar) is null.
To stop this infinite loop, I've been trying to use the option MAXRECURSION:
- when
@baris null, set MAXRECURSION to 1; - when
@baris not null, set MAXRECURSION to 0 (no limit).
So I've declared a local variable @maxrec that takes 1 or 0 depending on whether @bar is null or not.
DECLARE @maxrec INT;
SET @maxrec = 0;
if (@dim_course_categories is null)
begin
SET @maxrec = 1;
end
;WITH foo AS (
...
)
SELECT * FROM foo
OPTION (MAXRECURSION @maxrec)
When I parse the code, I get the following error:
Incorrect syntax near '@maxrec'., which refers to the line OPTION (MAXRECURSION @localvar).
So what am I doing wrong? Is it forbidden to use a local variable within an OPTION clause?
MAXRECURSIONdoes not accept a variable, only a constant from 0 to 32767, unfortunately. See query hints.@bar = NULL. Or simply use anifto execute one of two queries, one with the full CTE and the other with only the initialselectbut nounion.IF...ELSEstatement). The code of the SP ends up being almost twice as long, but it's still more readable than having the entire code in red.