Pergunta

Eu estou usando uma tabela Oracle e criaram uma restrição exclusiva sobre quatro colunas. Podem estas colunas dentro a restrição tem NULL neles?

Foi útil?

Solução

Você pode ter nulos em suas colunas a menos que as colunas são NÃO especificado NULL. Você será capaz de armazenar apenas uma instância de nulos no entanto (há dois conjuntos de mesmas colunas será permitida a menos que todas as colunas são NULL):

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

Outras dicas

Sim, a Oracle permite restrições UNIQUE para conter colunas com conteúdo NULL, mas restrições de chave primária não pode conter colunas contendo valores NULL. (Editado: era "... colunas anuláveis ??...", mas o meu exemplo abaixo mostra que não é verdade Colunas em um PK pode ser definido como anulável, mas não pode conter NULL.).

Você não pode ter uma restrição única e uma restrição de chave primária com as mesmas colunas.

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.

Dois nulos não são considerados iguais em Oracle, portanto, essas colunas podem ter valores nulos em si.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top