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
相关产品推荐
相关产品推荐

