2012-10-03 32 views
0

我在DB更改FK爲空值,如果其中包含了PK的表被刪除

Collection_ ( #Id_Collection, Libelle_Collection, Id_Editeur_Editeur )

Editeur ( #Id_Editeur, Libelle_Editeur )

兩個表當我想從表「Editeur」刪除一些記錄,它給了我這個錯誤:

The DELETE statement conflicted with the REFERENCE constraint "FK_Collection_Id_Editeur_Editeur". The conflict occurred in database "Gestion_bib", table "dbo.Collection_", column 'Id_Editeur_Editeur'. The statement has been terminated.

我知道錯誤,因爲在Collection_表的外鍵是在Editeur表中的PK,我用的是瀑布聲明另一個數據庫,但我不得不與它的問題,所以我不要」不喜歡使用它也使用另一種方法使用ADO.Net:

for (int i = 0; i < myClass.ds.Tables["Collection_"].Rows.Count; i++) 
         if (valToDelete == myClass.ds.Tables["Collection_"].Rows[i][2].ToString()) 
          myClass.ds.Tables["Collection_"].Rows[i][2] = DBNull.Value; 
        SqlCommandBuilder cmb = new SqlCommandBuilder(adapter); 
        adapter.Update(myClass.ds, "Editeur"); 

但是,當我處理包含許多FK的表時,這種方法變得越來越複雜。

那麼,如果我刪除了包含PK的表格,請問是否有其他方法將FK更改爲Null值?

+5

一個可能級聯操作是'ON DELETE SET NULL'的。這是你說你不想使用的選項嗎? –

+0

你真的想孤兒你的數據嗎?這對其他查詢中的連接將不再起作用的影響是什麼? – Jodrell

+0

不需要觸發器。正如@Martin所說的,你可以用'ON DELETE SET NULL'選項來定義FK。 –

回答

0

嘗試做這個使用SQL查詢:

Update Collection_ SET Id_Editeur_Editeur = NULL WHERE Id_Editeur_Editeur IN 
(CommaSeperatedValuesToDelete); 

然後,

Delete From Editeur Where Id_Editeur IN (CommaSeperatedValuesToDelete); 
+1

可能希望在事務中 – Jodrell

+0

我認爲這與我使用ADO.NET的方法相同,尊重是我使用斷開模式,我聽說我可以使用觸發器,但我不知道如何。 –

相關問題