关键字' OPTION'附近的语法不正确在CTE声明中

时间:2014-06-12 15:31:45

标签: sql sql-server-2008 common-table-expression

我在关键字' OPTION'"附近找到了"不正确的语法尝试在SQL Server 2008中保存视图时出错。我尝试在公共表表达式的末尾添加MAXRECURSION选项。我所见过的所有例子和我曾经创建过的CTE都没有考虑过" OPTION(MAXRECURSION 0)"在CTE结束时。

有人知道为什么我收到此错误? CTE在没有OPTION子句的情况下工作,尽管它达到了最大递归次数(100)。

WITH CTE AS
(
  SELECT
    CDay,
    InvAcct,
    BuyerCode,
    PartNumber,
    ROP,
    ROP_ROQ,
    DailyDemand,
    StartingInvQty,
    SchedDeliveryQty,
    CAST(StartingInvQty - DailyDemand/2.0 AS decimal(18,4)) AS ProjInvQty
  FROM
    qryInventorySimulation
  WHERE
    MBC = 'B' AND
    CDay = CAST(CAST(GETDATE()AS date) as datetime)

  UNION ALL

  SELECT
    qryInventorySimulation.CDay,
    qryInventorySimulation.InvAcct,
    qryInventorySimulation.BuyerCode,
    qryInventorySimulation.PartNumber,
    qryInventorySimulation.ROP,
    qryInventorySimulation.ROP_ROQ,
    qryInventorySimulation.DailyDemand,
    qryInventorySimulation.StartingInvQty,
    qryInventorySimulation.SchedDeliveryQty,
    CAST(CTE.ProjInvQty + qryInventorySimulation.SchedDeliveryQty - qryInventorySimulation.DailyDemand AS decimal(18,4)) AS ProjInvQty
  FROM
    qryInventorySimulation INNER JOIN CTE ON qryInventorySimulation.InvAcct = CTE.InvAcct AND qryInventorySimulation.PartNumber = CTE.PartNumber AND qryInventorySimulation.CDay = DATEADD(d,1,CTE.CDay)
  WHERE
    qryInventorySimulation.CDay <= DATEADD(d,120,GETDATE())
)

SELECT * FROM CTE
OPTION (MAXRECURSION 0);

1 个答案:

答案 0 :(得分:0)

您无法在视图中应用此选项。您需要将其应用于调用视图的查询。 e.g。

CREATE VIEW dbo.V
AS
    WITH CTE AS
    (   SELECT 1 AS A 
        UNION ALL
        SELECT A + 1
        FROM    CTE
        WHERE   A < 50
    )
    SELECT  *
    FROM    CTE;
GO
SELECT  *
FROM    dbo.V
OPTION (MAXRECURSION 0);

如果您将视图更多地视为存储的子查询而不是存储的查询(是的,它可以自己调用,但不一定),并记住它的定义已扩展到主查询中(除非您是使用NOEXPLAND - 你无法在包含递归CTE的视图中使用它,所以本质上你试图做这样的事情:

WITH RecursiveCTE AS (...)
SELECT *
FROM T
    INNER JOIN 
    (   SELECT  *
        FROM    RecursiveCTE
        OPTION (MAXRECURSION 0)
    ) c
        ON c.SomeField = T.SomeField;

正确的语法是:

WITH RecursiveCTE AS (...)
SELECT *
FROM T
    INNER JOIN 
    (   SELECT  *
        FROM    RecursiveCTE
    ) c
        ON c.SomeField = T.SomeField;
OPTION (MAXRECURSION 0)