【问题标题】:Recursive in Postgresql 12.2Postgresql 12.2 中的递归
【发布时间】:2020-04-29 21:40:19
【问题描述】:

我正在使用 Ora2Pg 工具从 Oracle 迁移到 Postgresql。我的甲骨文代码是

for rec_site in (select regexp_substr(p_site, '[^,]+', 1, level) site
                     from dual
            connnect by regexp_substr(p_site, '[^,]+', 1, level) is not null) 
loop

该工具已将此连接转换为之前的 postgresql 脚本。

for rec_site in (WITH RECURSIVE cte AS (
             select (SELECT array_to_string(a, '') FROM regexp_matches(p_site, '[^,]+', 'g') AS foo(a) LIMIT 1 OFFSET (level - 1)) site

             (SELECT array_to_string(a, '') FROM regexp_matches(p_site, '[^,]+', 'g') AS foo(a) LIMIT 1 OFFSET (level - 1)) is not null  

UNION ALL

             select (SELECT array_to_string(a, '') FROM regexp_matches(p_site, '[^,]+', 'g') AS foo(a) LIMIT 1 OFFSET (level - 1)) site

             SELECT array_to_string(a, '') FROM regexp_matches(p_site, '[^,]+', 'g') AS foo(a) LIMIT 1 OFFSET (level - 1)) is not null JOIN cte c ON ()
) SELECT * FROM cte;
) loop

这段代码给了我语法错误。 SQL 表达式末尾缺少“LOOP”。

【问题讨论】:

  • 您遇到的语法错误到底是什么?
  • 这是一个 pl/pgsql 脚本吗?你能尝试使用一致的缩进和大小写吗?这将有助于发现语法错误。

标签: postgresql


【解决方案1】:

对于 Oracle 中的 hack 来说,这是一个非常糟糕的翻译(并且再次表明,程序代码的自动翻译通常比手动翻译需要更多的工作)

最初的 Oracle 查询是一种将分隔列表拆分为行的技巧。这可以在 Postgres 中轻松完成:

select *
from unnest(string_to_array(p_site, ',')) as t(site)

所以你可以使用这个:

for rec_site in select *
                from unnest(string_to_array(p_site, ',')) as t(site)
                where site is not null
loop
   ....
end loop;

这可以通过直接遍历数组来进一步简化:

foreach site in array string_to_array(p_site, ',')
loop
  ...
end loop;

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 2016-04-25
    • 1970-01-01
    • 2017-05-12
    • 2021-11-27
    • 2010-10-17
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多