求助:PostgreSQL动态SQL重命名含survey_列无生效问题
问题排查与修正
你的脚本执行无报错但未生效,核心问题是把REPLACE函数直接写在了ALTER TABLE的SQL模板里,导致它没有被当作函数执行,而是被当成了新列名的字面量。比如原列名是survey_name,实际生成的SQL会试图把列重命名为"REPLACE(survey_name, 'survey', '')",而非预期的name。
另外你的需求是移除列名中的survey_,但脚本里只替换了survey,且匹配条件column_name like 'survey%'仅覆盖以survey开头的列,和需求的“包含survey_”不符,也需要调整。
修正后的脚本
do $$ declare l_rec record; new_col_name text; begin for l_rec in (select table_schema, table_name, column_name from information_schema.columns where table_schema = 'LUCAS_LF2022' and table_name = 'l2022_survey_lf_tst_pkg' and column_name like '%survey_%') loop -- 匹配包含survey_的列 new_col_name := replace(l_rec.column_name, 'survey_', ''); -- 提前计算好目标列名 execute format ('alter table %I.%I rename column %I to %I', l_rec.table_schema, l_rec.table_name, l_rec.column_name, new_col_name); end loop; end; $$
关键修改点
- 新增
new_col_name变量,在循环内提前执行replace函数生成目标列名,确保函数逻辑生效 - 修改
like条件为%survey_%,覆盖所有包含survey_的列(若仅需匹配以survey_开头的列,可改为survey_%) - 用
%I转义新列名,避免列名含特殊字符时出现语法错误
内容的提问来源于stack exchange,提问作者Momchill
相关产品推荐
相关产品推荐

