递归 SQL CTE 查询出现错误

问题描述 投票:0回答:1

我在 postgresql 中使用以下查询来使用 CTE 生成连续日期的列表,并遇到两个问题:

  1. 如果我按如下方式运行查询,则会收到与最后一行相关的语法错误 (OPTION (MAXRECURSION 0))
  2. 如果删除最后一行,我会收到错误“有一个名为“datecalendar”的WITH项目,但无法从查询的这一部分引用它。提示:使用WITH RECURSIVE,或重新排序要删除的WITH项目转发参考文献。”
WITH datecalendar
     AS (SELECT cast ('2023-08-08' as date) AS thedate
         UNION ALL
         SELECT Dateadd (day, 1, datecalendar.thedate) AS thedate
         FROM   datecalendar
         WHERE  Dateadd (day, 1, datecalendar.thedate) <= cast ('2023-08-12' as date))
SELECT * FROM datecalendar
OPTION (MAXRECURSION 0);

有人可以建议我如何解决上述两个问题吗?我已经做了很多寻找解决方案的工作。对于“1”,建议是确保 OPTION ... 放置在语句中的正确位置(例如,如何以及在哪里设置 MAXRECURSION 选项?),我似乎正在这样做。

对于“2”,我还没有找到类似的解决方案。

sql recursive-query
1个回答
0
投票

您似乎正在尝试使用递归公用表表达式 (CTE) 在 PostgreSQL 中生成一系列日期,但您正在混合 Microsoft SQL Server 的典型语法。让我们解决您的每个问题:

  1. 选项 (MAXRECURSION 0): 此行特定于 SQL Server。 PostgreSQL 没有这个选项。相反,如果您需要限制递归,您可以在递归查询本身中执行此操作,就像使用 'WHERE' 子句一样。
  2. WITH 项目名为“datecalendar”: 您看到的错误是因为在 PostgreSQL 中使用递归 CTE 时需要指定 'WITH RECURSIVE' 关键字。

让我们重写您的查询以使用 PostgreSQL:

WITH RECURSIVE datecalendar AS (
    SELECT cast('2023-08-08' as date) AS thedate
    UNION ALL
    SELECT thedate + interval '1 day'
    FROM datecalendar
    WHERE thedate + interval '1 day' <= cast('2023-08-12' as date)
)
SELECT * FROM datecalendar;

主要变化:

  • WITH替换为WITHRECURSIVE
  • 使用 PostgreSQL 的日期运算 ('thedate + Interval '1 day'') 而不是 SQL Server 的 DateAdd() 函数。
  • 删除了 OPTION (MAXRECURSION 0) 行,因为它不适用于 PostgreSQL。

在 PostgreSQL 数据库中运行上述查询将为您提供所需的日期序列。

© www.soinside.com 2019 - 2024. All rights reserved.