使用存储过程删除与记录关联的行

时间:2018-11-24 06:08:39

标签: sql-server

我正在尝试创建一个存储过程,在其中可以删除与一个名称有关的所有数据。这将包括“订单”表,“行项目”表和“客户”表中的数据。我应该以不同的方式子查询吗?enter image description here

CREATE PROCEDURE DELETE_CUSTOMER -- Delete a customer
 @cus_id_arg DECIMAL, -- customer's ID.
 @first_name_arg VARCHAR(30), -- customer’s first name.
 @last_name_arg VARCHAR(40), -- customer's last name.
 @cust_balance_in_arg DECIMAL(12,2) -- customer's balance
AS -- This "AS" is required by the syntax of stored procedures.
BEGIN
 -- Insert the new customer with a 0 balance.
 DELETE FROM CUSTOMER

 WHERE order_id IN (SELECT order_id FROM customer_order where customer_id = @cus_id_arg);

END;

1 个答案:

答案 0 :(得分:1)

  

CASCADE

     

如果从父表中删除了该行,则会从引用表中删除该行。

添加级联约束,删除将很容易

ALTER Customer_Order
ADD CONSTRAINT FK_CustomerID 
FOREIGN KEY(Customer_ID) REFERENCES (Customer_ID) 
ON DELETE CASCADE;

ALTER Line_Item
ADD CONSTRAINT FK_Order_ID 
FOREIGN KEY(Order_ID) REFERENCES Customer_Order(Order_ID) 
ON DELETE CASCADE;

现在,您从Customer表中删除的任何行都将被删除,Customer_Order表中的所有对应行将被删除,而Line_Item表中的所有行也将被删除。

所以您只能写DELETE FROM Customer WHERE Customer_ID = @Customer_ID;