简体   繁体   English

PostgreSQL:如何在数据库的每个表中添加一列?

[英]PostgreSQL: How to add a column in every table of a database?

I have a database with 169 tables我有一个包含 169 个表的数据库

I need this column in every table:我在每个表中都需要此列:

wid integer not null primary key

I tried this(Thanks https://stackoverflow.com/users/27535/gbn for the solution):我试过了(感谢https://stackoverflow.com/users/27535/gbn的解决方案):

SELECT 
  'ALTER TABLE ' + T.name + ' ADD foo int NULL'
FROM
  sys.tables AS T
WHERE
  T.is_ms_shipped = 0

But it didn't work on PostgreSQL.但它不适用于 PostgreSQL。

It only worked on tsql.它只适用于 tsql。

How to add this column in every table at once ?如何一次在每个表中添加此列?

do $$
declare
    selectrow record;
begin
for selectrow in
    select 
      'ALTER TABLE '|| T.mytable || ' ADD COLUMN foo integer NULL' as script 
   from 
      ( 
        select tablename as mytable from  pg_tables where schemaname  ='public' --your schema name here
      ) t
loop
execute selectrow.script;
end loop;
end;
$$;

You can test whether all your tables altered with the new column using the following select您可以使用以下选择测试是否所有表都使用新更改

select 
     table_name,COLUMN_NAME
 from 
     INFORMATION_SCHEMA.COLUMNS 
 where 
   COLUMN_NAME='foo' -- <whatever your column name here>

Try this (change 'public' to whatever schema you're doing this in)试试这个(将“公共”更改为您正在执行此操作的任何架构)

DO $$
DECLARE 
    row record; 
    cmd text;
BEGIN
    FOR row IN SELECT schemaname, tablename FROM pg_tables WHERE schemaname = 'public' LOOP
        cmd := format('ALTER TABLE %I.%I ADD COLUMN foo SERIAL PRIMARY KEY ', row.schemaname, row.tablename);
        RAISE NOTICE '%', cmd;
        -- EXECUTE cmd;
    END LOOP;
END
$$ LANGUAGE plpgsql;

If you run as is, it'll show you the commands.如果按原样运行,它会向您显示命令。 Uncomment the EXECUTE line to actually perform the alterations.取消注释 EXECUTE 行以实际执行更改。

I'd run within a transaction so you can roll back if you're not happy with the results.我会在事务中运行,因此如果您对结果不满意,您可以回滚。

Note that the type is SERIAL - the column type will be integer, but also creates a sequence owned by the table and defaults the column value to the next value of that sequence.请注意,类型是SERIAL - 列类型将为整数,但也会创建表拥有的序列,并将列值默认为该序列的下一个值。

We may need to check column is already exist or not .我们可能需要检查列是否已经存在

Tested on PostgreSQL V10在 PostgreSQL V10 上测试

do $$
declare selectrow record;
begin
for selectrow in
    select 'ALTER TABLE '|| T.mytable || ' ADD COLUMN x_is_exported boolean DEFAULT FALSE' as script 
   from (select tablename as mytable from  pg_tables where schemaname  ='public') t
loop
    begin
        execute selectrow.script;
        EXCEPTION WHEN duplicate_column THEN CONTINUE;
    END;
end loop;
end;
$$;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM