postgresql使用游标批量给表添加、修改字段

遇到的问题

在写项目的数据库升级脚本的时候,有一个批量给一些表添加字段的需求,这样每个表写一个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;
$$;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值