简体   繁体   中英

Can't add foreign key constraint to table

CREATE TABLE CUSTOMER
(
    CNUM VARCHAR(25) NOT NULL,
    CNAME VARCHAR(75) NOT NULL,
    CTYPE VARCHAR(20) NOT NULL,

    CONSTRAINT CUSTOMER_PK PRIMARY KEY(CNUM),
    CONSTRAINT CHECK_CTYPE CHECK(CTYPE IN('INDIVIDUAL', 'INSTITUTION'))
);

CREATE TABLE CREDIT_TERM
(
    CREDITSTATUS VARCHAR(20) NOT NULL,
    STARTDATE DATE NOT NULL,
    ENDDATE DATE NOT NULL,

    CONSTRAINT CREDIT_TERM_PK PRIMARY KEY(CREDITSTATUS)
);


insert into CREDIT_TERM values('ONE-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('TWO-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('THREE-MONTH','15-05-2015','15-06-2015');

ALTER TABLE CUSTOMER 
ADD CONSTRAINT CUSTOMER_FK_CREDITSTATUS 
    FOREIGN KEY(CREDITSTATUS) REFERENCES CREDIT_TERM(CREDITSTATUS);

I am trying to add a foreign key constraint, but I don't understand why I get this error:

ERROR at last line :
ORA-00904: "CREDITSTATUS": invalid identifier

You're trying to add a foreign key constraint for a foreign key named CREDITSTATUS on the CUSTOMER table. However, the CUSTOMER table doesn't have a foreign key for CREDITSTATUS .

You'll have to create a foreign key in CUSTOMER for CREDITSTATUS , then rerun the last line to add the constraint.

EDIT

Use ALTER TABLE to add the column to CUSTOMER:

ALTER TABLE CUSTOMER ADD CREDITSTATUS VARCHAR(20);

Docs: http://www.techonthenet.com/oracle/tables/alter_table.php

As I noted in the comments, your customer table does not have a creditstatus column. You'd first have to add it:

ALTER TABLE customer ADD creditstatus VARCHAR2(20);

And then make it a foreign key, with the statement you already have.

You can add the column and the foreign key constraint in one statement:

alter table customer add (
   creditstatus varchar2(20) constraint customer_fk_creditstatus references credit_term
   );

A few notes. First, I enclosed the column definition in parentheses. It may work without them, but the official syntax seems to require them. http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_3001.htm#i2103924

Second, in an in-line constraint (defined at the column level, not at the table level), you may not use the words FOREIGN KEY. The word REFERENCES already identifies the constraint type. Third, if you reference the PRIMARY KEY of the referenced table, you are not required to (but you may if you wish) name the referenced column in the referenced table. If you don't name the column, the PRIMARY KEY of the referenced table will be used by default - which is what you want anyway, in the vast majority of cases.

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