添加具有空值的约束唯一列

时间:2017-07-11 18:20:03

标签: sql oracle constraints unique

我需要创建一个完整性约束,以确保在一列表中只有一个空值。经典的UNIQUE不好用,因为它没有检测到多个空值...... 我怎么办?

1 个答案:

答案 0 :(得分:3)

CREATE TABLE qwe(
  id int
);

CREATE UNIQUE INDEX qwe_idx ON qwe( 
      CASE WHEN id IS null THEN 'NULL' ELSE to_char(id) END 
);
INSERT INTO qwe VALUES(1);
1 row inserted.

INSERT INTO qwe VALUES(1);
Error starting at line : 9 in command -
INSERT INTO qwe VALUES(1)
Error report -
ORA-00001: naruszono więzy unikatowe (TEST.QWE_IDX)
INSERT INTO qwe VALUES(NULL);
1 row inserted.

INSERT INTO qwe VALUES(NULL);
Error starting at line : 9 in command -
INSERT INTO qwe VALUES(NULL)
Error report -
ORA-00001: naruszono więzy unikatowe (TEST.QWE_IDX)
SELECT * FROM qwe;

        ID
----------
         1
    (null)