Oracle unique constraint and primary key not null

北城余情 提交于 2020-01-04 04:24:16

问题


Can a table have a primary key attribute and a unique constraint to another attribute?

I have the following

CREATE TABLE BRANCH(
BRA_CODE NUMBER NOT NULL PRIMARY KEY,
BRA_NAME VARCHAR(15),
BRA_ADDR VARCHAR(30),
 CITY_ID NUMBER);

and im trying to add

ALTER TABLE BRANCH ADD CONSTRAINT UNIQUE_BRANCH_NAME UNIQUE (BRA_NAME);

and i get the following error;

ERROR at line 1:
ORA-02261: such unique or primary key already exists in the table

回答1:


Q: Can a table have a primary key attribute and a unique constraint to another attribute?

A: Yes:

  • A table can have no more than one primary key.

  • A primary key may consist of multiple columns (a "composite primary key")

  • Any column may have a "unique constraint", whether or not it's a primary key column

  • A primary key is always "unique", and always has a "unique" constraint

ERROR at line 1: ORA-02261: such unique or primary key already exists in the table

A: Check your schema. You've already already got a primary key, and/or you already defined the same unique constraint.

For example:

http://www.shutdownabort.com/dbaqueries/Structure_Constraints.php

col type format a10
col cons_name format a30
select  decode(constraint_type,
        'C', 'Check',
        'O', 'R/O View',
        'P', 'Primary',
        'R', 'Foreign',
        'U', 'Unique',
        'V', 'Check view') type
,   constraint_name cons_name
,   status
,   last_change
from  dba_constraints
where  table_name like 'BRANCH'
order by 1



回答2:


You can have a unique contraint apart from the primary key, but the message indicates that you already added such a constraint.



来源:https://stackoverflow.com/questions/9864299/oracle-unique-constraint-and-primary-key-not-null

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