postgresql SQL Not Empty 而不是 Not NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7951120/
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-20 23:23:34  来源:igfitidea点击:

SQL Not Empty instead of Not NULL

sqlpostgresqlnotnull

提问by kamaci

I am using postgreSQL. I have a column that:

我正在使用 postgreSQL。我有一个专栏:

NOT NULL

However when I want to insert a row with an empty string as like:

但是,当我想插入带有空字符串的行时,如下所示:

''

it doesn't give me an error and accepts. How can I check insert value should be not empty? (Neither empty nor null)

它不会给我错误并接受。我怎样才能检查插入值应该是not empty?(既不为空也不为空)

PS:My column defined as:

PS:我的专栏定义为:

"ads" character varying(60) NOT NULL

回答by Avo Murom?gi

Add a constraint to column definition. For example something like:

向列定义添加约束。例如类似的东西:

ads character varying(60) NOT NULL CHECK (ads <> '')

For more, see http://www.postgresql.org/docs/current/static/ddl-constraints.html

有关更多信息,请参阅http://www.postgresql.org/docs/current/static/ddl-constraints.html

回答by micfra

Found in the current documentation of postgreSQLyou can do the following to achieve what you want:

postgreSQL当前文档中找到,您可以执行以下操作来实现您想要的:

CREATE TABLE distributors (
    did    integer PRIMARY KEY DEFAULT nextval('serial'),
    name   varchar(40) NOT NULL CHECK (name <> '')
);

From the documentation:

从文档:

CHECK ( expression )

The CHECK clause specifies an expression producing a Boolean result which new or updated rows must satisfy for an insert or update operation to succeed. Expressions evaluating to TRUE or UNKNOWN succeed. Should any row of an insert or update operation produce a FALSE result an error exception is raised and the insert or update does not alter the database. A check constraint specified as a column constraint should reference that column's value only, while an expression appearing in a table constraint may reference multiple columns.

Currently, CHECK expressions cannot contain subqueries nor refer to variables other than columns of the current row.

CHECK ( expression )

CHECK 子句指定产生布尔结果的表达式,新的或更新的行必须满足插入或更新操作才能成功。评估为 TRUE 或 UNKNOWN 的表达式成功。如果插入或更新操作的任何行产生 FALSE 结果,则会引发错误异常并且插入或更新不会更改数据库。指定为列约束的检查约束应仅引用该列的值,而出现在表约束中的表达式可能引用多个列。

目前,CHECK 表达式不能包含子查询,也不能引用当前行列以外的变量。