6

我可以在SQLite中的TEXT列上创建数据库约束,不允许该列的值为空字符串""吗?

我想允许该列为null,但不允许空字符串。

4

3 回答 3

12

是的,您可以

sqlite> create table foo (bar TEXT, CHECK(bar <> ''));
sqlite> insert into foo values (NULL);
sqlite> insert into foo values ('bla');
sqlite> insert into foo values ('');
Error: constraint failed
于 2012-04-29T09:57:09.737 回答
3

您可以使用 CHECK 约束(http://www.sqlite.org/lang_createtable.html):

SQLite version 3.5.9
Enter ".help" for instructions
sqlite> create table example(col, CHECK (col is null or length(col) > 0));
sqlite> insert into example values ('');
SQL error: constraint failed
sqlite> insert into example values (null);
sqlite> insert into example values ('sample');
sqlite> .nullvalue NULL
sqlite> select col from example;
NULL
sample
于 2012-04-29T09:57:23.680 回答
1

据我所知,SQLite 中不存在类似的约束,但也许您可以使用触发器解决方法,该触发器INSERT和/或UPDATE上自动将字符串更改为 NULL 为空。

于 2012-04-29T09:36:18.020 回答