asa*_*gam 2 postgresql dynamic-sql postgresql-9.4
如果表在模式中不包含该列,您能否给出向所有表添加一列的命令?
例如,模式schema1
包含 50 个表,其中 20 个表包含名为 的列colTest
。
我需要将该列添加colTest
到剩余的 30 个表中。
您可以使用循环和动态 SQL 执行此操作:
do
$$
declare
tname record;
begin
for tname in select t.table_schema, t.table_name
from information_schema.tables t
where table_schema = 'schema1' --<< change schema name here
and not exists (select *
from information_schema.columns c
where (c.table_schema, c.table_name) = (t.table_schema, t.table_name)
and c.column_name = 'coltest')
loop
-- change column definition in the following string
execute format('alter table %I.%I add column coltest integer', tname.table_schema, tname.table_name);
end loop;
end;
$$
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1833 次 |
最近记录: |