【问题标题】:using execute in postgres returns syntax error在 postgres 中使用执行返回语法错误
【发布时间】:2021-08-09 13:58:03
【问题描述】:

我正在尝试调试此广告并找出出现语法错误的原因:

CREATE OR REPLACE FUNCTION public.myfunc(_report_id integer, _cutoff_date date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
    _deliverable_id RECORD  ;
BEGIN
FOR _deliverable_id IN
      SELECT deliverable_id FROM public.deliverables where report_id=_report_id
   LOOP
      execute format('DROP TABLE IF EXISTS report.products_%I',_deliverable_id);
   END LOOP;
    
END
$function$
;

当我执行这个时,我得到:

syntax error at or near ""(1111)""

1111 肯定是一个交付物,所以这让我认为它与执行语句格式或我使用 %I 的方式有关?

【问题讨论】:

    标签: postgresql syntax-error execute


    【解决方案1】:

    %I 被替换为一个整体标识符。如果你想连接事物,你需要在之前替换。

    您可以通过检查format() 函数的结果自行测试/调试:

    select format('DROP TABLE IF EXISTS report.products_%I',42);
    

    返回DROP TABLE IF EXISTS report.products_"42"

    你需要使用:

    select format('DROP TABLE IF EXISTS report.%I',concat('products_', 42));
    

    正确返回DROP TABLE IF EXISTS report.products_42

    (显然你需要用你的变量替换42

    【讨论】:

    • @Matias 如果该答案解决了您的问题,那么请accept 它,以便您的问题被标记为已解决。
    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 2016-04-04
    • 1970-01-01
    • 2014-08-29
    • 2021-06-13
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多