Not empty string contraint in SQLite

陌路散爱 提交于 2019-12-10 17:46:36

问题


Can I create a database constraint on a TEXT column in SQLite disallowing the value of the column to be empty string ""?

I want to allow the column to be null, but disallow empty string.


回答1:


Yes you can:

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



回答2:


You can use a CHECK constraint (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



回答3:


As far as i know doesn't exist a similar constraint in SQLite, but maybe you can workaround with a Trigger that on INSERT and/or UPDATE automatically change the string empty in NULL.



来源:https://stackoverflow.com/questions/10371077/not-empty-string-contraint-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!