I’m facing a problem declaring the maxrecursion option for a CTE inside a TVF.
Here is the CTE (a simple calendar):
DECLARE @DEBUT DATE = '1/1/11', @FIN DATE = '1/10/11';
WITH CTE as(
SELECT @debut as jour
UNION ALL
SELECT DATEADD(day, 1, jour)
FROM CTE
WHERE DATEADD(day, 1, jour) <= @fin)
SELECT jour FROM CTE option (maxrecursion 365)
and the TVF:
CREATE FUNCTION [liste_jour]
(@debut date,@fin date)
RETURNS TABLE
AS
RETURN
(
WITH CTE as(
SELECT @debut as jour
UNION ALL
SELECT DATEADD(day, 1, jour)
FROM CTE
WHERE DATEADD(day, 1, jour) <= @fin)
SELECT jour FROM CTE
--option (maxrecursion 365)
)
The above TVF is running OK without the maxrecursion option
but there is a syntax error with the option.
What is the solution?
From this MSDN forums thread I learn that
and further
So in your example, you must specify the
OPTIONwhen you call your function:(later)
Note that you can’t work round this by having a second TVF that just does the above line – you get the same error, if you try. “[the]
OPTIONclause can be used only at the statement level”, and that’s final (for now).