2012-08-07 111 views
0

我有2個表:A和BDELETE FROM表A和B的多條記錄與一個FK表B

A包含以下幾列:

Id [uniqueIdentifier] -PK 
checkpointId [numeric(20,0)] 

B包含以下內容:

Id [uniqueIdentifier] – PK 
A_id (FK, uniqueIdentifier) 

B具有從A_ID柱(FK)

問題至A的引用: 我想從表A中刪除所有的記錄,他們的checkpoint_id是小於X

delete from CheckpointStorageObject where checkpointIdentifierIdentifier <= 1000 

但我不能這樣做,因爲"The primary key value cannot be deleted because references to this key still exist"

我試過的B表先刪除沒有加入:

DELETE FROM CheckpointToProtectionGroup 
WHERE EXIST (SELECT * from CheckpointStorageObject 
      WHERE CheckpointStorageObject.CheckpointIdentifierIdentifier <= 1000) 

但它沒有奏效。

我該怎麼辦? 是否可以使用一個執行命令從兩個表中刪除?

結果刪除的記錄可能非常大 - 每張表中超過30K條記錄。

回答

2

試試這個:

首先從tableB的刪除:

delete from tableB where A_id IN (Select Id from tableA where checkpointId <= 1000) 

然後再從表A中刪除:

delete from tableA where checkpointId <= 1000 
0

您必須首先從表B中刪除的條目

delete from tableB where A_id IN (Select Id from tableA where checkpointIdentifierIdentifier <= 1000) 

一旦做到這一點,你可以從表A中刪除,通過檢查不再在表B中的ID

delete from tableA where Id not in (select A_id from tableB) 
0

你的第二個查詢有一定的缺陷:

  • EXISTS而不是EXIST

  • 您需要指定2個表格之間的連接條件。在相關子查詢像這樣的,你WHERE條款

  • 它也usfeul有別名爲表,以減少代碼,並使其更具可讀性,尤其是在這麼長的名字

  • 圍在添加THI scondition事務中的2條語句,以確保它成功 - 並從兩個表中刪除 - 或者失敗並刪除任何內容。如果您不使用事務,則第二次刪除可能會失敗,如果在兩次刪除之間的一小段時間內,在表B處插入一行並引用表A中第二條語句將嘗試刪除的行。

所以,從表B中先刪除(CheckpointToProtectionGroup):

BEGIN TRANSACTION 

    DELETE FROM CheckpointToProtectionGroup AS b 
    WHERE EXISTS         --- EXISTS 
      (SELECT * 
      FROM CheckpointStorageObject AS a 
      WHERE a.id = b.A_id     --- join condition 
       AND a.CheckpointId <= 1000 
     ) ; 

,然後從表A(CheckpointStorageObject):

DELETE FROM CheckpointStorageObject 
    WHERE CheckpointId <= 1000 ; 

COMMIT TRANSACTION ; 
+0

我editted到存在EXIST – Haimon 2012-08-07 14:04:16