简体   繁体   English

如何一次将所有表列设置为 NOT NULL?

[英]How to set all table columns to NOT NULL at once?

Is this even possible, if so how?这甚至可能吗,如果可以的话怎么办? if not then I would be happy with a way that doesn't require typing each column name one by one.如果不是,那么我会对一种不需要逐个键入每个列名的方式感到满意。 My use-case is that I create a table from a query and would like to make all columns NOT NULL because I later do ORM using Slick and it is a lot nicer to have all those column types not null (and therefore non Option[X]).我的用例是我从查询创建一个表,并希望所有列都不是 NULL 因为我后来使用 Slick 做 ORM 并且所有这些列类型不是 Z37A6259CC46[X9DFFAE299A ])。 This is static data so the column values will not be null and won't change either.这是 static 数据,因此列值不会是 null 也不会改变。

Unlike MySQL, Postgres doesn't figure out that the originating query columns are all NOT NULL already.与 MySQL 不同,Postgres 并没有发现原始查询列都不是 NULL。

I'd like to avoid in my script adding the constraint one by one and be prone to breaking the solution whenever the query schema is changed ie我想避免在我的脚本中一一添加约束,并且每当更改查询架构时都容易破坏解决方案,即

CREATE TABLE dentistry_procedure AS SELECT * FROM ...
ALTER TABLE dentistry_procedure ALTER column * SET NOT NULL;

How?如何?

You could use metadata table and build dynamic query:您可以使用元数据表并构建动态查询:

SELECT format('ALTER TABLE %I '||STRING_AGG(format('ALTER COLUMN %I SET NOT NULL', COLUMN_NAME),CHR(13)||',')
              , MIN(TABLE_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE IS_NULLABLE = 'YES'
  AND TABLE_NAME = 't';

db<>Fiddle demo db<>小提琴演示

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

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