I want to write a function like this:
CREATE OR ALTER FUNCTION TestFunction()
RETURNS TABLE
AS RETURN
WITH NumberList AS (
SELECT 1 AS Number
UNION ALL
SELECT Number + 1
FROM NumberList
WHERE Number < 1000
)
SELECT Number
FROM NumberList
OPTION (MAXRECURSION 0)
However, when running this query, SQL Server returns the following error:
Msg 156, Level 15, State 1, Procedure TestFunction, Line 13 [Batch Start Line 0]
Incorrect syntax near the keyword 'OPTION'.
If I remove the row OPTION (MAXRECURSION 0)
from the function it works:
CREATE OR ALTER FUNCTION TestFunction()
RETURNS TABLE
AS RETURN
WITH NumberList AS (
SELECT 1 AS Number
UNION ALL
SELECT Number + 1
FROM NumberList
WHERE Number < 1000
)
SELECT Number
FROM NumberList
But when executing this function:
SELECT *
FROM TestFunction()
Then it returns the following error:
Msg 530, Level 16, State 1, Line 1
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
Is it possible to add the clause OPTION (MAXRECURSION 0)
inside the function? I think it would be convenient for the user of the function not having to remember to add the option clause when executing the function.