我正在尝试创建一个存储过程,在其中可以删除与一个名称有关的所有数据。这将包括“订单”表,“行项目”表和“客户”表中的数据。我应该以不同的方式子查询吗?
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;
答案 0 :(得分:1)
如果从父表中删除了该行,则会从引用表中删除该行。
添加级联约束,删除将很容易
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;