插入/更新时的Oracle sql触发器计算2个值并更新第三个值

时间:2015-04-23 15:03:10

标签: triggers oracle-sqldeveloper

我想创建一个触发器,通过计算2个值来更新行并更新第三个值:

CREATE TABLE Customers (
    Cust_ID INTEGER PRIMARY KEY,
    Dates TIMESTAMP WITH LOCAL TIME ZONE,
    Quantity dec(7,2) NOT NULL,
    Price_per_item dec(7,2) NOT NULL,
    Total_price dec(7,2)
);

我做到了:

CREATE OR REPLACE TRIGGER cust_after_insert AFTER INSERT 
ON Customers
FOR EACH ROW
BEGIN
    UPDATE Customers
    SET 
    DATES = CURRENT_TIMESTAMP,
    Total_price = Quantity * Price_per_item;
END;

我遇到了一些我尝试同时查看和编辑表格的错误。

我也试过这个:

CREATE SEQUENCE cust_Seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER cust_trig BEFORE INSERT ON Customers
FOR EACH ROW
BEGIN
  SELECT cust_Seq.nextval INTO :new.Fuel_ID FROM dual;
  SELECT CURRENT_TIMESTAMP INTO :new.DATES FROM dual;
  SELECT Quantity * Price_per_item INTO :new.Total_price FROM dual;
END;
/

我更喜欢第二个选项,如果UPDATE也会出现,我会需要一些东西。

1 个答案:

答案 0 :(得分:0)

第二种方法是正确的方向,但需要进行一些调整以处理Total_price计算并处理update

CREATE SEQUENCE cust_Seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER cust_trig BEFORE INSERT OR UPDATE ON Customers
FOR EACH ROW
BEGIN
  IF INSERTING THEN
    SELECT cust_Seq.nextval INTO :new.Fuel_ID FROM dual;
    SELECT CURRENT_TIMESTAMP INTO :new.DATES FROM dual;
  END IF;
  :new.Total_price :=  :new.Quantity * :new.Price_per_item;
END;
/