在触发期间访问表

时间:2015-11-01 04:24:50

标签: database oracle triggers oracle10g

我有三张桌子:

  

客户(客户ID,名称)

     

CustInvoice(InvoiceID,CustomerID(FK to Customer),CustName)

     

ProductOrder(OrderID,OrderDate,CustomerID(FK to。)   顾客))

我想写下面的触发器:

"只要ProductOrder表中有新订单,此触发器就会生成一个CustInvoice"

我试图这样写:

CREATE OR REPLACE TRIGGER DoCustInvoice
    AFTER INSERT ON ProductOrder
        INSERT INTO CustInvoice(InvoiceSEQ.NEXTVAL,????)
    END;
/

但是我不知道如何在触发期间访问Customer表以使用Trigger访问Customer表中的Name! 任何人都可以向我解释我该怎么做?

由于

2 个答案:

答案 0 :(得分:2)

首先,您需要在触发声明影响的每一行之后更改触发时间以触发"。 See here

其次,在这种情况下,Pseudorecords可以使用ProductOrder表中的CustomerID和CustomerName。 See here

CREATE OR REPLACE TRIGGER DoCustInvoice
AFTER INSERT ON ProductOrder
FOR EACH ROW
BEGIN
    INSERT INTO CustInvoice(InvoiceID,CustomerID,CustName) 
    VALUES (InvoiceSEQ.NEXTVAL, :NEW.CustomerID, :NEW.CustomerName);
END;
/

但是,如果需要,可以在触发器中使用select语句。

CREATE OR REPLACE TRIGGER DoCustInvoice
AFTER INSERT ON ProductOrder
FOR EACH ROW
DECLARE
  v_custname Customer.Name%TYPE;
BEGIN
SELECT Customer.Name 
INTO v_custname 
FROM Customer 
WHERE CustomerID = :NEW.CustomerID;
INSERT INTO CustInvoice (InvoiceID,CustomerID,CustName ) 
VALUES (InvoiceSEQ.NEXTVAL, :NEW.CustomerID, v_custname);
END;
/

答案 1 :(得分:0)

delimiter $$
CREATE TRIGGER DoCustInvoice AFTER INSERT ON ProductOrder FOR EACH ROW BEGIN
    INSERT INTO CustInvoice(CustomerID,CustName) VALUES(new.CustomerID,new.CustomerName);
END