遇到的问题
在写项目的数据库升级脚本的时候,有一个批量给一些表添加字段的需求,这样每个表写一个sql脚本就重复了很多工作.
解决方案
我的思路是使用数据库的游标.进行遍历需要维护的表,进行判断后进行操作,写数据库升级脚本一定写判断,保证不出错.
示例代码
do $$
declare
sql_string text;
tablename text default '';
table_info cursor for
select distinct table_name from information_schema.columns where table_name in ('a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'j',
'k',
'l');
begin
open table_info;
loop
fetch table_info into tablename;
Exit when NOT found;
IF (select count(*) from information_schema.columns where table_name = tablename and column_name = 'optime' ) = 0
THEN
sql_string := 'alter table '||tablename||' ADD optime timestamp without time zone';
execute sql_string;
END IF;
end loop;
close table_info;
end;
$$;