Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TSQL:避免内联函数中的MAXRECURSION限制_Sql_Sql Server_Tsql_Inline Table Function - Fatal编程技术网

TSQL:避免内联函数中的MAXRECURSION限制

TSQL:避免内联函数中的MAXRECURSION限制,sql,sql-server,tsql,inline-table-function,Sql,Sql Server,Tsql,Inline Table Function,我有一个函数,给定初始和最终日期,给出该范围内的相应年/月: CREATE FUNCTION [dbo].[fnYearMonth] ( @Initial Date, @Final Date ) RETURNS TABLE AS RETURN With dateRange(StatDate) as ( select @Initial union all select dateadd(month, 1, StatDate) from dateR

我有一个函数,给定初始和最终日期,给出该范围内的相应年/月:

CREATE FUNCTION [dbo].[fnYearMonth]
(
    @Initial Date,
    @Final Date 
)
RETURNS TABLE 
AS
RETURN
With dateRange(StatDate) as 
(
    select @Initial
    union all
    select dateadd(month, 1, StatDate)
    from dateRange 
    where dateadd(month, 1, StatDate) <= CAST(DATEADD(month,DATEDIFF(month,0,@Final)+1,0)-1 as Date)
)
select DATEPART(year, StatDate) AS MyYear, DATEPART(month, StatDate) AS MyMonth From dateRange where StatDate <= @Final
问题在于,默认的MAXRECURSION限制为100,只能提供最多8年零4个月的日期范围。这是不够的

我尝试使用选项MAXRECURSION 2000;在使用此函数但不起作用的函数中,因为我在WITH语句中调用了此函数

我现在唯一的解决方案是将此内联函数转换为多语句函数,并使用选项MAXRECURSION 2000;。但出于性能原因,我更愿意避免使用此选项。还有其他选择吗

感谢您的帮助。

尝试在底部添加选项MAXRECURSION 0或递归限制,如下所示

您还可以使用a避免所有这些计算,从而获得所需的输出

我在数据库中填充了一个日历表,输出很容易计算,如下所示。我建议使用一个表,而不是重复计算

select distinct month,year from dbo.calendar
where dAte>=getdate()-200 and date<=getdate()

您必须使用选项MAXRECURSION。。。关于最后一个问题。例如,我使用递归cte获取函数,我在另一个cte中运行此函数,然后从中选择。我将使用选项MAXRECURSION。。。在最后一个选择中,创建日期表插入100年*365天=36500行是一个好主意吗?我觉得那排太多了。第二种选择是不可能的。在内联函数中,选项语句不可用。Sql management studio给出了一个语法错误。我认为创建表是一个好主意,我已经尝试过递归cte,让我尝试使用内联函数并更新question@ajmena40k行int值不算什么。从表中读取数据要比不断执行函数快。似乎只支持多表值函数,我会选择表选项,因为它可以在很多情况下帮助您,而不是this@ajmena一个日期表和一个时间表是最好的选择。
alter function 
dbo.getnum_test
(
@n int
)
returns table
as return
With cte as
(
select @n as n
union all
select @n+1
from cte
)

select * from cte
where  n<1000
option (maxrecursion 0)

alter function dbo.itvftest
(
@n int
)
returns
@numbers table
(
n int
)
as 
begin

With cte as
(
select @n as n
union all
select n+1
from cte
where cte.n<10000
)
Insert into @numbers
select * from cte
where  n<1000
option (maxrecursion 0)

return
end