1. 程式人生 > >ORA-02291: integrity constraint: parent key not found

ORA-02291: integrity constraint: parent key not found

hibernate operation: Could not execute JDBC batch update; SQL [insert into 

dchnpricecarchancesource (inpricecard_id, pricecard_id, count, sumcount, source_code, reason_code, 

ingroup_id, op_login, op_groupid, op_time, change_source, memo1, memo2, change_id) values (?, ?, 

?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; ORA-02291: integrity constraint 


(DBCHNADM.FK_DCHNPRIC_REFERENCE_DCHNPRIC) violated - parent key not found ; nested exception is 

Java.sql.BatchUpdateException: ORA-02291: integrity constraint 

(DBCHNADM.FK_DCHNPRIC_REFERENCE_DCHNPRIC) violated - parent key not found 

---------------------------------------------------------------------------------------------------------------------------


參看了這本書第八章:
《Oracle Database 11g SQL開發指南》<oracle database 11g SQL Master SQL and PL/SQL in the Oracle Database>

8.5.2  外來鍵約束

所謂外來鍵關係就是一個表中的列引用了其他表中的列。例如,products表中的product_type_id列引用了 

product_types表中的product_type_id列。product_types表稱為父表(parent table),而products表則稱為子

表(child table),這是因為products表中的product_type_id列依賴於product_types表中的product_type_id 


列。

如果試圖向products表中插入一行,但此行的product_type_id不存在,資料庫就會返回ORA-02291錯誤。這個錯

誤說明資料庫無法找到一個匹配的父鍵值(此處父鍵就是product_types表中的product_type_id列)。在下面這個

例子中,就返回這樣一個錯誤,因為product_types表中不存在product_type_id為6的行:

SQL> INSERT INTO products (
2     product_id, product_type_id, name, description, price
3   ) VALUES (
4    13, 6, 'Test', 'Test', NULL
5   );
INSERT INTO products (
*
ERROR at line 1:
ORA-02291: integrity constraint (STORE.PRODUCTS_FK_PRODUCT_TYPES)
violated - parent key not found

同理,如果試圖將products表中一行的product_type_id列設定為一個不存在的父鍵值,資料庫也會返回相同的

錯誤。例如:

SQL> UPDATE products
2   SET product_type_id = 6
3   WHERE product_id = 1;
UPDATE products
*
ERROR at line 1:
ORA-02291: integrity constraint (STORE.PRODUCTS_FK_PRODUCT_TYPES)
violated - parent key not found

如果試圖從父表中刪除已經有依賴子行的一行,資料庫就會返回ORA-02292錯誤。例如,如果試圖刪除

product_types表中 product_type_id列為1的行,資料庫就會返回ORA-02292錯誤,因為products表中包含了

product_type_id列等於1的行:

SQL> DELETE FROM product_types
2   WHERE product_type_id = 1;
DELETE FROM product_types
*
ERROR at line 1:
ORA-02292: integrity constraint (STORE.PRODUCTS_FK_PRODUCT_TYPES)
violated - child record found

如果資料庫允許執行這個刪除操作,那麼子行就無效了,因為它們不能指向父表中的有效值了。

---------------------------------------------------------------------------------------------------------------------

後來發現是在表中外來鍵設定錯誤造成的,引以為戒: