本文介绍了防止在CHARACTER VARYING字段中出现空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用PostgreSQL,并希望阻止某些必需的CHARACTER VARYING(VARCHAR)字段允许输入空字符串.
I am using PostgreSQL and would like to prevent certain required CHARACTER VARYING (VARCHAR) fields from allowing empty string inputs.
这些字段还需要包含唯一值,因此我已经在使用唯一约束;但是,这不会阻止原始的(唯一的)空值.
These fields would also need to contain unique values, so I am already using a unique constraint; however, this does not prevent an original (unique) empty value.
基本示例,其中用户名必须唯一且不能为空
Basic example, where username needs to be unique and not empty
| id | username | password |
+----+----------+----------+
| 1 | User1 | pw1 | #Allowed
| 2 | User2 | pw1 | #Allowed
| 3 | User2 | pw2 | #Already prevented by constraint
| 4 | '' | pw2 | #Currently allowed, but needs to be prevented
推荐答案
使用检查约束:
CREATE TABLE foobar(
x TEXT NOT NULL UNIQUE,
CHECK (x <> '')
);
INSERT INTO foobar(x) VALUES('');
这篇关于防止在CHARACTER VARYING字段中出现空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!