Monday, September 27, 2010

Integrity constraint

 Oracle/PLSQL: ORA-02291 Error
Error      : ORA-02291: integrity constraint <constraint name> violated - parent key not found

Cause    : You tried to reference a table using a unique or primary key, but the columns that you listed did not    match the primary key, or a primary key does not exist for this table.


Action :
The options to resolve this Oracle error are:
  1. This error commonly occurs when you have a parent-child relationship established between two tables through a foreign key. You then have tried to insert a value into the child table, but the corresponding value does not exist in the parent table.
To correct this problem, you need to insert the value into the parent table first and then you can insert the corresponding value into the child table.

For example, if you had created the following foreign key (parent-child relationship).
CREATE TABLE supplier
( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products
( product_id numeric(10) not null,

supplier_id numeric(10) not null,

CONSTRAINT fk_supplier

  FOREIGN KEY (supplier_id)

  REFERENCES supplier (supplier_id)
);

Then you try inserting into the products table as follows:
INSERT INTO products
(product_id, supplier_id)
VALUES (1001, 5000);

You would receive the following error message:


Since the supplier_id value of 5000 does not yet exist in the supplier table, you need to first insert a record into the supplier table as follows:
INSERT INTO supplier
(supplier_id, supplier_name, contact_name)
VALUES (5000, 'Microsoft', 'Bill Gates');
Then you can insert into the products table:
INSERT INTO products
(product_id, supplier_id)
VALUES (1001, 5000);

No comments:

Post a Comment