我正在为已删除的客户创建以前的客户表。 我想在从客户表中删除数据后创建一个触发器。 但是,我不希望所有客户只在此表中放置那些之前已在系统中下订单的客户。 我有两张桌子
Customer placed_order
Customer_Id order_id
first_name order_date
last_name employee_ID
address fk1_customer_id
如何只插入在已下订单表中有记录的客户?
答案 0 :(得分:1)
像
这样的东西CREATE OR REPLACE TRIGGER CUSTOMER_AD
AFTER DELETE ON CUSTOMER
REFERENCING OLD AS OLD
FOR EACH ROW
DECLARE
nPlaced_order_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO nPlaced_order_count
FROM PLACED_ORDERS p
WHERE p.FK1_CUSTOMER_ID = :OLD.CUSTOMER_ID;
IF nPlaced_order_count > 0 THEN
INSERT INTO PREVIOUS_CUSTOMER(whatever, whatever, whatever)
VALUES(whatever, whatever, whatever);
END IF;
-- Now clean up the PLACED_ORDERS table
DELETE FROM PLACED_ORDERS p
WHERE p.FK1_CUSTOMER_ID = :OLD.CUSTOMER_ID;
END CUSTOMER_AD;
将whatever
替换为适合您的PREVIOUS_CUSTOMER
表的列名和值。
分享并享受。
答案 1 :(得分:0)
首先,您必须在placed_order
。fk1.customer_id
列上指定要在删除时级联的约束。只需更改该列的外键约束即可。
试试这个:
ALTER TABLE placed_order
MODIFY CONSTRAINT fk1_fk_customer_id
FOREIGN KEY (fk1_customer_id) REFERENCES customer(customer_id)
ON DELETE CASCADE;
接下来,客户需要BEFORE DELETE
触发器,以便对那些在placed_order
表中有条目的客户进行审核。
CREATE OR REPLACE TRIGGER trg_customer_delete
BEFORE DELETE ON customer
FOR EACH ROW
REFERENCING new AS new old AS old
AS
cnt INTEGER;
BEGIN
SELECT COUNT(*)
INTO cnt
FROM placed_order
WHERE fk_customer_id = :old.customer_id
IF cnt > 0 THEN
INSERT INTO previous_customer
(customer_id, first_name, last_name, address)
VALUES
(:old.customer_id, :old.first_name, :old.last_name, :old.address);
END IF;
END;
/