【问题标题】:Can I create a named default constraint in an add column statement in Postgres?我可以在 Postgres 的添加列语句中创建命名默认约束吗?
【发布时间】:2021-08-31 14:30:27
【问题描述】:

我是 Postgres 的新手,想知道是否可以在 Postgresql 中创建一个命名的默认值约束。我在 SqlServer Can I create a named default constraint in an add column statement in SQL Server? 中发现了类似的东西,但对于 Postgresql 却想不通。

为了提供一些上下文,我正在尝试将一列添加到表中,并且在添加时我正在尝试将此命名约束添加到列中。

任何帮助将不胜感激。

提前致谢

【问题讨论】:

  • Postgres(以及基本上所有其他数据库)具有默认的。在(标准 SQL)中没有“默认约束”之类的东西。所以,不,你不能给默认的 value 一个名字。

标签: postgresql constraints


【解决方案1】:

像这样:

\d foo 
                 Table "public.foo"
  Column  |  Type   | Collation | Nullable | Default 
----------+---------+-----------+----------+---------
 fooid    | integer |           |          | 
 foosubid | integer |           |          | 
 fooname  | text    |           |          | 

alter  table foo add column bar varchar constraint u2_idx UNIQUE;
ALTER TABLE

 \d foo
                      Table "public.foo"
  Column  |       Type        | Collation | Nullable | Default 
----------+-------------------+-----------+----------+---------
 fooid    | integer           |           |          | 
 foosubid | integer           |           |          | 
 fooname  | text              |           |          | 
 bar      | character varying |           |          | 
Indexes:
    "u2_idx" UNIQUE CONSTRAINT, btree (bar)

更新。 为了更接近您链接到的帖子显示的内容:


alter  table foo add column baz varchar default ''  constraint nn_constraint NOT NULL;

\d foo
                             Table "public.foo"
  Column  |       Type        | Collation | Nullable |        Default        
----------+-------------------+-----------+----------+-----------------------
 fooid    | integer           |           |          | 
 foosubid | integer           |           |          | 
 fooname  | text              |           |          | 
 bar      | character varying |           |          | 
 baz      | character varying |           | not null | ''::character varying
Indexes:
    "u2_idx" UNIQUE CONSTRAINT, btree (bar)

虽然NOT NULL 约束实际上并没有被命名。

【讨论】:

  • SQL Server 所谓的“默认约束”只是其他所有数据库中的“默认”。
  • @Adrian Klaver 我认为这与 a_horse_with_no_name 发表的评论一致。它只是默认值。与 sqlserver 不同,它不能被命名。如果我错了,请纠正我。
  • 如果您谈论的是DEFAULT 值,那么它无法命名。如果在您的问题中,“将此命名约束添加到列中”,那么可以做到。它归结为您定义为约束的内容。
猜你喜欢
  • 2011-04-15
  • 1970-01-01
  • 2011-05-17
  • 2020-12-11
  • 1970-01-01
  • 2013-01-08
  • 2016-07-08
  • 1970-01-01
相关资源
最近更新 更多