1

我正在为已删除的客户创建以前的客户表。我想在从客户表中删除数据后创建一个触发器。但是,我不希望所有客户都被放置在这个表中,只有那些以前在系统中下过订单的客户。我有两张桌子

Customer                 placed_order
Customer_Id              order_id
first_name               order_date
last_name                employee_ID
address                  fk1_customer_id

怎么可能只插入在下订单表中有记录的客户?

4

2 回答 2

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表的列名和值。

分享和享受。

于 2013-05-12T15:31:33.707 回答
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;
/
于 2013-05-12T15:38:02.077 回答