Sql-Server

刪除表中引用另一個引用的所有記錄

  • October 19, 2018

對不起,如果這個問題的標題沒有意義。我真的不知道該怎麼說我需要做的。

所以我的數據庫中有以下表格:

customers
   customer_id (PK)
   customer_name
   website

customer_address
   customer_id (FK) (PK-A)
   street (PK-B)
   city
   region
   code

customer_contact
   contact_id (PK)
   contact_name
   customer_id (FK)

customer_contact_phone
   contact_id (FK) (PK-A)
   phone_number (PK-B)
   extension

我正在嘗試建立一個程序,允許我刪除與特定客戶有關的所有數據。現在我知道如何刪除與我要刪除其數據的客戶有關的任何或所有地址。但是,我不知道如何正確刪除所有聯繫人數據。

我的問題是一個客戶可以有多個聯繫人,每個聯繫人可以有多個電話號碼。由於設置了多少外鍵,我不確定如何設置這些記錄以進行刪除。

您只需要向後遍歷關係,首先從最後一個孩子刪除,然後是下一個孩子,依此類推。

假設您要刪除特定客戶的所有數據,您可以執行以下過程:

CREATE PROCEDURE dbo.ObliterateACustomer
 @delete_me int
AS
BEGIN
 SET NOCOUNT ON;

 DELETE dbo.customer_contact_phone 
   WHERE contact_id IN
   (
      SELECT contact_id 
        FROM dbo.customer_contact 
        WHERE customer_id = @delete_me
   );

 DELETE dbo.customer_contact WHERE customer_id = @delete_me;

 DELETE dbo.customer_address WHERE customer_id = @delete_me;

 DELETE dbo.customer WHERE customer_id = @delete_me;
END
GO

對於從關係中刪除,有幾種方法可以做到這一點。IN可以說是最直接的,但您也可以從連接中刪除:

DELETE p
FROM dbo.customer_contact_phone AS p
INNER JOIN dbo.customer_contact AS c
 ON c.contact_id = p.contact_id
 WHERE c.customer_id = @delete_me;

或使用EXISTS

DELETE p
FROM dbo.customer_contact_phone AS p
WHERE EXISTS
(
 SELECT 1 FROM dbo.customer_contact AS c
 WHERE c.contact_id = p.contact_id
   AND c.customer_id = @delete_me
);

您甚至可以使用MERGE,但我不會向您展示如何使用,因為我認為這通常是一個糟糕的主意。:-)

引用自:https://dba.stackexchange.com/questions/220580