2011-05-24 14 views
2

我有一個存儲樹的表。有一個node_id和parent_id。什麼是使用Oracle從一個表插入到另一個表的最佳方式

當我嘗試以下方法:

insert into table1 select * from table2 start with node_id = 1 connect by prior node_id = parent_id order by parent_id nulls first 

我得到這個錯誤:

Error starting at line 6 in command: 
insert into table1 select * from table2 start with node_id = 1 connect by prior node_id = parent_id order by parent_id nulls first 
Error report: 
SQL Error: ORA-02291: integrity constraint (XVTEST.REGIONAL_DEFAULT_DELETE) violated - parent key not found 
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found" 
*Cause: A foreign key value has no matching primary key value. 
*Action: Delete the foreign key or add a matching primary key. 

我明白爲什麼我收到此錯誤。我只是想知道是否有辦法做出這種做出一個遞歸的PL/SQL程序。思考?如果不可能有人有這樣的程序,我可以用作樣本?

回答

4

一種選擇是將FOREIGN KEY約束創建爲DEFERRABLE,然後爲您的事務設置DEFERRED,以便將外鍵約束的實施推遲到COMMIT。

請注意,您不希望在表中的內容違反約束條件時執行任何SELECT操作。在某些情況下,某些SELECT語句將返回意外或不一致的結果。 (一定要考慮觸發器執行的SELECT語句。)


-- to create foreign key constraints as deferrable 
ALTER TABLE my_table ADD CONSTRAINT my_table_fk1 
FOREIGN KEY (other_table_id) REFERENCES other_table (id) 
DEFERRABLE INITIALLY IMMEDIATE; 

-- defer all deferrable constraints until the next commit 
ALTER SESSION SET CONSTRAINTS=DEFERRED; 
-- or 
SET CONSTRAINTS ALL DEFERRED; 

-- dml operations may now temporarily violate constraints 
INSERT ... ; 
UPDATE ... ; 

-- you can check the constraints before the commit 
SET CONSTRAINTS ALL IMMEDIATE; 

-- all deferred constraints will be enforced at the next commit 
-- (a fk violation exception will be raised here, rather than by the DML) 
COMMIT; 

一些有用的參考文獻:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:914629004506

http://download.oracle.com/docs/cd/B10500_01/server.920/a96524/c22integ.htm#4666


附加說明:

該方法專門適用於Oracle數據庫,可能不適用於其他關係數據庫引擎。

約束被推遲時針對錶執行SELECTS的警告僅適用於推遲約束的會話。其他會話將看到一致的狀態,因爲他們不會看到任何未提交的更改。

使用DEFERRED約束優於禁用和重新啓用約束,因爲禁用約束會影響所有會話,並且重新驗證約束會消耗大量資源(對於大型表)。

+0

我甚至沒有聽說過延期......謝謝!這正是我需要的! – testing123 2011-05-24 23:38:09

相關問題