如何在表值函数内为CTE设置maxrecursion选项 [英] How to set the maxrecursion option for a CTE inside a Table-Valued-Function

查看:116
本文介绍了如何在表值函数内为CTE设置maxrecursion选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在声明TVF中CTE的maxrecursion选项时遇到问题。

I'm facing a problem declaring the maxrecursion option for a CTE inside a TVF.

这里是CTE(简单的日历):

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)

和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)
 )

上面的TVF在没有maxrecursion选项$ b的情况下运行正常$ b,但该选项存在语法错误。
解决方案是什么?

The above TVF is running OK without the maxrecursion option but there is a syntax error with the option. What is the solution?

推荐答案

来自此MSDN论坛线程我了解到


[the] OPTION 子句只能在语句级别使用

[the] OPTION clause can be used only at the statement level

所以您不能在视图定义或内联TVF等内部的查询表达式中使用它。在您的情况下,使用它的唯一方法是创建没有 OPTION 子句的TVF,并在使用TVF的查询。我们有一个错误可跟踪允许在任何查询表达式内使用 OPTION 子句的请求(例如, if exist()或CTE或视图)。

So you cannot use it within a query expression inside view definitions or inline TVFs etc. The only way to use it in your case is to create the TVF without the OPTION clause and specify it in the query that uses the TVF. We have a bug that tracks request for allowing use of OPTION clause inside any query expression (for example, if exists() or CTE or view).

并进一步


您不能在udf中更改该选项的默认值。您必须在引用udf的语句中执行

You can not change the default value of that option inside a udf. You will have to do it in the statement referencing the udf.

因此,在您的示例中,必须指定 OPTION ,当您调用函数时:

So in your example, you must specify the OPTION when you call your function:

 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 -- no OPTION here
 )

(以后)

SELECT * FROM [liste_jour] ( @from , @to ) OPTION ( MAXRECURSION 365 )

请注意,您不能通过仅执行上述操作的第二个TVF来解决此问题-如果您遇到相同的错误,尝试。 [the OPTION 子句只能在语句级别使用,这是最终的(目前)。

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] OPTION clause can be used only at the statement level", and that's final (for now).

这篇关于如何在表值函数内为CTE设置maxrecursion选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆