我试图在 Oracle 的不可空列中插入一个空字符串,但失败了。案例如下:
create table trademark (
name varchar2(100) not null
);
insert into trademark (name) values ('Kodak');
insert into trademark (name) values (' '); -- one space
insert into trademark (name) values (''); -- empty string
Error: ORA-01400: cannot insert NULL into ("USER1"."TRADEMARK"."NAME")
我做错了什么?
在 Oracle 中,空字符串等同于 NULL
。
在几乎任何其他数据库中,两者都是不同的,但这就是 Oracle 为字符串定义 NULL
值的方式(默认情况下)。
这在 documentation 中有解释,连同这个诱人的注释:
Note:
Oracle Database currently treats a character value with a length of
zero as null. However, this may not continue to be true in future
releases, and Oracle recommends that you do not treat empty strings
the same as nulls.
突出显示的部分是我的。我不确定您应该如何遵循该建议。我认为这意味着在您打算使用 NULL
时显式使用 NULL
,而不是 ''
。
请注意,在 SQL 中,NULL
表示一个未知 值,而不是一个空值。没有字符的字符串(完全有效的字符串)和未知的 NULL
值之间存在很大差异。在实践中,NULL
通常用于缺失,但这更像是一种约定而非定义。