外键约束

外键列上所有值得取值必须在主键列的值范围内。

constraint fk_xx foreign key(columnName) references tableName(colNmae);

on delete cascade;

ondelete set null;

alter table emp add foreign key emp(dno) references dept(did);

测试例子如下:

SQL> create table test_fk(
  2  id int,
  3  name varchar2(20));

Table created.

SQL> alter table test_fk add constraint pk_name primary key (name);

Table altered.

SQL> desc test_fk;
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID						    NUMBER(38)
 NAME					   NOT NULL VARCHAR2(20)

SQL> alter table test_fk rename to test_pk;

Table altered.


SQL> desc test_pk
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID						    NUMBER(38)
 NAME					   NOT NULL VARCHAR2(20)

SQL> create table test_fk(
  2  dept varchar(20),  
  3  name varchar(20));

Table created.

SQL> alter table test_fk add constraint fk_name foreign key name references test_pk(name);
alter table test_fk add constraint fk_name foreign key name references test_pk(name)
                                                       *
ERROR at line 1:
ORA-00906: missing left parenthesis

SQL> ed
Wrote file afiedt.buf

  1* alter table test_fk add constraint fk_name foreign key (name) references test_pk(name)
SQL> /

Table altered.

SQL> desc test_fk;
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPT						    VARCHAR2(20)
 NAME						    VARCHAR2(20)

SQL> insert into test_fk values ('test','peter');
insert into test_fk values ('test','peter')
*
ERROR at line 1:
ORA-02291: integrity constraint (SYS.FK_NAME) violated - parent key not found


SQL> insert into test_pk(101,'peter');
insert into test_pk(101,'peter')
                    *
ERROR at line 1:
ORA-00928: missing SELECT keyword


SQL> ed
Wrote file afiedt.buf

  1* insert into test_pk values(101,'peter')
SQL> /

1 row created.

SQL> commit
  2  ;

Commit complete.

SQL> ed
Wrote file afiedt.buf

  1* commit
  2  
SQL> desc test_fk;
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPT						    VARCHAR2(20)
 NAME						    VARCHAR2(20)

SQL> insert into test_fk values ('test','peter');

1 row created.

SQL> delete from test_pk where name='peter';
delete from test_pk where name='peter'
*
ERROR at line 1:
ORA-02292: integrity constraint (SYS.FK_NAME) violated - child record found


SQL> alter table test_pk drop primary key ;
alter table test_pk drop primary key
*
ERROR at line 1:
ORA-02273: this unique/primary key is referenced by some foreign keys


SQL> ed
Wrote file afiedt.buf

  1* alter table test_pk drop primary key cascade
SQL> /

Table altered.

SQL> insert into test_fk values ('sales','allen');

1 row created.

SQL> commit;

Commit complete.

SQL> 

  

原文地址:https://www.cnblogs.com/jycjy/p/7404445.html