简体   繁体   中英

Oracle - Cannot create new FK on existing table

I'm convinced I must be doing something incredibly stupid, as it can't be this hard to add a new foreign key to an existing table. However, I'm still stuck. Here's what I'm doing.

First, I created a new column in TPM_USER to store which team a user is on:

ALTER TABLE TPM_USER ADD (
  "TEAMID" NUMBER NULL
)

This works without errors, and I can query the TPM_USER table to see the new column has been added. Next, I want TEAMID to refer to a row in the already existing TPM_DEVELOPMENTTEAMS table. So I do:

ALTER TABLE TPM_USER
    ADD CONSTRAINT TPM_USER_FK1
    FOREIGN KEY(TEAMID)
    REFERENCES TPM_DEVELOPMENTTEAMS(TEAMID)

This gives me the error:

ORA-02270: no matching unique or primary key for this column-list

I've checked both TEAMID columns are the same data type (NUMBER) and TEAMID is of course the primary key of the DEVELOPMENTTEAMS table. In fact, here's the schema for DEVELOPMENTTEAMS :

CREATE TABLE TPMDBO.TPM_DEVELOPMENTTEAMS  ( 
    TEAMID      NUMBER NULL,
    NAME        VARCHAR2(100) NOT NULL,
    ISACTIVE    CHAR(1) NULL,
    SORTORDER   NUMBER NULL,
    SHORTNAME   VARCHAR2(100) NULL,
    GROUPID     NUMBER NOT NULL,
    CONSTRAINT TPM_DEVELOPMENTTEAMS_PK PRIMARY KEY(TEAMID)
    NOT DEFERRABLE
     DISABLE NOVALIDATE
)

I even tried the GUI interface in Aqua Data Studio to add the new constraint as well, so I'm sure I didn't misspell anything. What am I doing wrong?

Your PK is disabled. Enable it with:

ALTER TABLE TPM_DEVELOPMENTTEAMS ENABLE CONSTRAINT TPM_DEVELOPMENTTEAMS_PK;

BTW, by declaring it PK, you also made TPM_DEVELOPMENTTEAMS.TEAMID non-NULL (so there is no purpose for NULL after it).

You can only refer the column(or combination of columns) which are either enabled Primary Key or Unique Key for the same/other table.

If you find your constraint disabled in below query then you cant create Foreign Key for that PK/UK. You should enable it.

select constraint_name from dba_constraints
   where constraint_type in ('P','U')
   and status = 'DISABLED'
   and lower(table_name) = lower(:p_table_name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM