postgresql Postgres 默认值 NULL 和空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22834079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:23:35  来源:igfitidea点击:

Postgres default value NULL and empty string

postgresqlpostgresql-9.2

提问by markus

Usually the default value is used if the value to insert is NULL. Is there a way to tell postgres that it should use the default value also on empty string ('')?

如果要插入的值为 NULL,则通常使用默认值。有没有办法告诉 postgres 它也应该在空字符串('')上使用默认值?

回答by Craig Ringer

No, you can't do so directly.

不,你不能直接这样做。

The only valid ways to specify a default value are:

指定默认值的唯一有效方法是:

  • To omit the column from an INSERTcolumn-list; or
  • To explicitly specify the keyword DEFAULTfor a column in an INSERTor UPDATE.
  • INSERT列列表中省略该列;或者
  • 为or 中DEFAULT的列显式指定关键字。INSERTUPDATE

Neither NULLor ''are valid ways to request a default value for a column.

无论是NULL或者''是有效的方法来请求默认值的列。

If you wish to replace NULLor ''with the default you must use a BEFORE ... FOR EACH ROWtrigger to do so.

如果您希望替换NULL''使用默认值,则必须使用BEFORE ... FOR EACH ROW触发器来执行此操作。

Making a generic one isn't especially trivial, as you can't use the DEFAULTkeyword when assigning to the NEWtuple within a trigger; you'd instead have to look up the system catalogs for the default expression.

制作一个泛型并不是特别简单,因为在触发器中DEFAULT分配NEW元组时不能使用关键字;您必须在系统目录中查找默认表达式。

Of course, you can always just repeat the default expression in the trigger if you know it and don't mind coding a trigger specific to it.

当然,如果您知道并且不介意编写特定于它的触发器,您总是可以重复触发器中的默认表达式。

All in all, it's way better to fix the application so it follows the standard and doesn't expect the DB to replace NULLor ''with a default value.

总而言之,修复应用程序的方式更好,因此它遵循标准并且不期望数据库替换NULL''使用默认值。