温馨提示×

oracle外键设置的方法有哪些

小亿
426
2024-05-23 09:32:38
栏目: 云计算

在Oracle中设置外键可以通过以下几种方法:

1、使用CREATE TABLE语句创建表时定义外键约束:

```sql

CREATE TABLE table1 (

id NUMBER PRIMARY KEY,

name VARCHAR2(50)

);

CREATE TABLE table2 (

id NUMBER PRIMARY KEY,

table1_id NUMBER,

CONSTRAINT fk_table1_id FOREIGN KEY (table1_id) REFERENCES table1(id)

);

```

2、使用ALTER TABLE语句添加外键约束:

```sql

ALTER TABLE table2

ADD CONSTRAINT fk_table1_id FOREIGN KEY (table1_id) REFERENCES table1(id);

```

3、使用ALTER TABLE语句修改外键约束:

```sql

ALTER TABLE table2

MODIFY CONSTRAINT fk_table1_id FOREIGN KEY (table1_id) REFERENCES table1(id);

```

4、使用ALTER TABLE语句删除外键约束:

```sql

ALTER TABLE table2

DROP CONSTRAINT fk_table1_id;

```

5、在创建表时使用外键约束选项:

```sql

CREATE TABLE table2 (

id NUMBER PRIMARY KEY,

table1_id NUMBER CONSTRAINT fk_table1_id REFERENCES table1(id)

);

```

6、使用关键字FOREIGN KEY定义外键:

```sql

CREATE TABLE table2 (

id NUMBER PRIMARY KEY,

table1_id NUMBER,

FOREIGN KEY (table1_id) REFERENCES table1(id)

);

```

0