Oracleテーブルを使用しており、4つの列に一意の制約を作成しました。制約内のこれらの列にNULLを含めることはできますか?
86080 次
3 に答える
69
列がNOTNULLに指定されていない限り、列にNULLを含めることができます。ただし、NULLのインスタンスを1つだけ格納できます(すべての列がNULLでない限り、同じ列の2つのセットは許可されません):
SQL> CREATE TABLE t (id1 NUMBER, id2 NUMBER);
Table created
SQL> ALTER TABLE t ADD CONSTRAINT u_t UNIQUE (id1, id2);
Table altered
SQL> INSERT INTO t VALUES (1, NULL);
1 row inserted
SQL> INSERT INTO t VALUES (1, NULL);
INSERT INTO t VALUES (1, NULL)
ORA-00001: unique constraint (VNZ.U_T) violated
SQL> /* you can insert two sets of NULL, NULL however */
SQL> INSERT INTO t VALUES (NULL, NULL);
1 row inserted
SQL> INSERT INTO t VALUES (NULL, NULL);
1 row inserted
于 2009-12-03T17:16:43.350 に答える
5
はい、OracleではUNIQUE制約にNULLの内容を含む列を含めることができますが、PRIMARYKEY制約にNULL値を含む列を含めることはできません。(編集:「... null許容列...」でしたが、以下の例では、trueではないことを示しています。PKの列はnull許容として定義できますが、NULLを含めることはできません。)
同じ列でUNIQUE制約とPRIMARYKEY制約を持つことはできません。
SQL> create table stest (col1 integer not null, col2 integer null);
Table created.
SQL> alter table stest add constraint stest_uq unique (col1, col2);
Table altered.
SQL> insert into stest values (1, 3);
1 row created.
SQL> insert into stest values (1, null);
1 row created.
SQL> insert into stest values (1, null);
insert into stest values (1, null)
*
ERROR at line 1:
ORA-00001: unique constraint (SUSAN_INT.STEST_UQ) violated
SQL> insert into stest values (2, null);
1 row created.
SQL> commit;
Commit complete.
SQL> select * from stest;
COL1 COL2
---------- ----------
1 3
1
2
SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2);
alter table stest add constraint stest_pk PRIMARY KEY (col1, col2)
*
ERROR at line 1:
ORA-01449: column contains NULL values; cannot alter to NOT NULL
SQL> truncate table stest;
Table truncated.
SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2);
alter table stest add constraint stest_pk PRIMARY KEY (col1, col2)
*
ERROR at line 1:
ORA-02261: such unique or primary key already exists in the table
SQL> alter table stest drop constraint stest_uq;
Table altered.
SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2);
Table altered.
于 2009-12-03T17:15:56.673 に答える
2
Oracleでは2つのnullは等しくないと見なされるため、これらの列にはnullを含めることができます。
于 2009-12-03T17:14:25.233 に答える