You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL条件判断后插入数据报分号语法错误如何修复

错误原因

  • 直接语法错误:PL/pgSQL 中的过程式 CASE 控制结构必须以 END CASE; 收尾,你当前只写了 END;,触发语法报错。
  • 隐性逻辑错误:你判断记录是否存在的查询目标表是 config_bundle,但你实际要插入数据的表是 config_plan,哪怕语法修复完成,原代码的判存逻辑也完全不生效。
  • 性能冗余:判存使用 count(id) > 0 会扫描所有符合条件的记录,改用 EXISTS 只要匹配到第一条记录就返回结果,执行效率更高。

修复后完整代码

do
$$
    declare
        v_video_config_bundle_id bigint;
        v_are_records_exist boolean;
    begin
        select id from config_bundle into v_video_config_bundle_id where code = 'video';
    
        -- 修正判存的目标表为config_plan,改用EXISTS提升效率
        select exists(
            select 1 from config_plan
            where config_bundle_id = v_video_config_bundle_id
            and preference = true and amount = 0 and repeatability in (1,7,14,21,30,45) and format='day'
        ) into v_are_records_exist;

        case
        when not v_are_records_exist then
            insert into config_plan(config_bundle_id, amount, repeatability, format, payment_amount, preference_type, preference, trial, weight, status, is_default)
            values (v_video_config_bundle_id, 0, 7, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
                   (v_video_config_bundle_id, 0, 14, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
                   (v_video_config_bundle_id, 0, 21, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false);
        end case; -- 修正CASE结束语法
    end;
$$ language plpgsql;

内容的提问来源于stack exchange,提问作者Maksym Rybalkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 11:18:03