项目在做postgresql数据库适配时遇到了某些问题,需要统一将某个模式含id字段的全部表,将id字段由小写转换为大写,可以通过PL/pgSQL脚本实现。
先确保当前用户有足够的权限
DO $$
DECLARE current_table text;current_column text;
BEGIN -- 获取所有表名FOR current_table IN (SELECT table_name FROM information_schema.tables WHERE table_schema = '你的模式名' AND table_type = 'BASE TABLE') LOOP -- 获取所有列名FOR current_column IN (SELECT column_name FROM information_schema.columns WHERE table_schema = '你的模式名' AND table_name = current_table AND column_name = 'id') LOOP -- 生成新的列名EXECUTE format('ALTER TABLE %I.%I RENAME COLUMN %I TO %I', '你的模式名', current_table, current_column, 'ID'); END LOOP; END LOOP;
END $$;
同理,可以更换为其他字段