简体   繁体   English

如何一次将 NOT NULL 设置为我数据库的所有表中存在的列?

[英]How to set NOT NULL to a column present in all the tables of my database at once?

I'm working with PostgreSQL.我正在使用 PostgreSQL。 I have to set the NOT NULL property on a column that exists in all the tables of my database.我必须在我的数据库的所有表中存在的列上设置NOT NULL属性。 I know how to set in one table, using:我知道如何在一张桌子上设置,使用:

ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;

But I have about 400 tables in my database, so I need something to do it at once, does anybody the way?但是我的数据库中有大约 400 个表,所以我需要立即执行此操作,有人可以吗?

Thank you in advance!先感谢您!

Use psql 's \gexec :使用psql\gexec

SELECT format(
          'ALTER TABLE %I.%I ALTER column_name SET NOT NULL;',
          table_schema,
          table_name
       )
FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema') \gexec

Alternatively, you can run the statement, save the output to a script and execute that.或者,您可以运行该语句,将 output 保存到脚本并执行该脚本。

You can also write a DO statement with PL/pgSQL code that loops through the results of the query and uses EXECUTE to execute them as dynamic SQL.您还可以使用 PL/pgSQL 代码编写DO语句,循环查询结果并使用EXECUTE将它们作为动态 SQL 执行。

As laurenz stated, you can achieve it by executing the ALTER commands in the DO statement like below,正如 laurenz 所说,您可以通过在DO语句中执行 ALTER 命令来实现它,如下所示,

DO $$
DECLARE
    selectrow record;
BEGIN
    FOR selectrow IN
        SELECT format(
                  'ALTER TABLE %I.%I ALTER %s SET NOT NULL;',
                  table_schema,
                  table_name,
                  'my_column'
               ) AS script
        FROM information_schema.tables
        WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
    LOOP
        EXECUTE selectrow.script
    END LOOP;
END;
$$;

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

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