将值插入具有约束的表中

时间:2016-05-17 10:55:38

标签: sql oracle

我有两个具有二元关系的表,它们彼此关联,如何在这些表中插入值?

create table t1 
(
    cola_1 integer constraint t1_cola_1_pk primary key,
    cola_2 integer
);

create table t2 
(
    colb_1 integer constraint t2_colb_1_pk primary key,
    colb_2 integer constraint t2_colb_2_fk references t1(cola_1)
);

alter table t1 
modify cola_2 constraint t1_cola_2_fk references t2(colb_1);

如何将值插入t1表?

3 个答案:

答案 0 :(得分:4)

You can create DEFERRED constraints, so that they are checked at commit time:

SQL> create table t1
  2  (
  3  cola_1 integer constraint t1_cola_1_pk primary key,
  4  cola_2 integer
  5  );

Table created.

SQL> create table t2
  2  (
  3  colb_1 integer constraint t2_colb_1_pk primary key,
  4  colb_2 integer constraint t2_colb_2_fk  references t1(cola_1) INITIALLY DEFERRED
  5  );

Table created.

SQL> alter table t1
  2  modify cola_2 constraint t1_cola_2_fk references t2(colb_1 ) INITIALLY DEFERRED;

Table altered.

You can do run your insert statements, without having any check:

SQL> insert into t2(colb_1, colb_2) values (10, 20);

1 row created.

SQL> insert into t1(cola_1, cola_2) values (40, 40);

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (ALEK.T2_COLB_2_FK) violated - parent key not
found

The check is performed when you try commit; in this case I have a failure and a rollback, because I tried to insert wrong values. If I insert correct data, even commit is ok:

SQL> insert into t2(colb_1, colb_2) values (10, 10);

1 row created.

SQL> insert into t1(cola_1, cola_2) values (10, 10);

1 row created.

SQL> commit;

Commit complete.

SQL>

However, if you don't have a strong reason, creating tables recursively referencing may be not such a good idea; probably you can change your DB design to avoid this situation

答案 1 :(得分:1)

答案 2 :(得分:-1)

INSERT INTO t1 (cola_1, cola_2) VALUES (0, 2);

If you using an oracle db, you should create a sequence for autoincrementing id.

Link: http://www.techonthenet.com/oracle/sequences.php