触发不触发(编译成功)

时间:2019-03-29 07:00:21

标签: sql oracle

我有这两个表

CREATE TABLE Car_Makers ( 
ID NUMBER(5), 
Maker VARCHAR2(15), 
FullName VARCHAR2(25), 
Country NUMBER(5),
MODAL_TOTALS INT, 
CONSTRAINT car_maker_country_id_fk FOREIGN KEY(Country) REFERENCES 
 Countries(CountryID), 
CONSTRAINT car_maker_id PRIMARY KEY(ID) 
 );

CREATE TABLE Model_Details ( 
ModelID NUMBER(5), 
Maker NUMBER(5), 
Model VARCHAR2(25), 
CONSTRAINT model_unique UNIQUE(Model), 
CONSTRAINT model_details_id_pk PRIMARY KEY(ModelID), 
CONSTRAINT model_maker_fk FOREIGN KEY(Maker) REFERENCES Car_Makers(ID) 
);

我想创建一个触发器,当在MODEL_TOTALS中插入新行时,将在Car_Makers中更新Model_Details。但是我的触发器运行成功,但是没有触发。我没有收到任何错误,但是当我在Model_details中插入一行时,相应的MODEL_TOTAL值不会更新。任何帮助将不胜感激,这是我的触发器

   CREATE OR REPLACE TRIGGER trg_modeltotals_up 
   AFTER INSERT ON MODEL_DETAILS
   REFERENCING NEW AS NEWROW
   FOR EACH ROW
   BEGIN
   UPDATE CAR_MAKERS SET MODEL_TOTALS = MODEL_TOTALS+1 WHERE 
   CAR_MAKERS."ID" = :NEWROW.MAKER;
    END;

2 个答案:

答案 0 :(得分:1)

可能是null s引起了问题。在更新中添加coalesce

UPDATE CAR_MAKERS SET MODAL_TOTALS = COALESCE(MODAL_TOTALS,0) +1 WHERE 
   CAR_MAKERS."ID" = :NEWROW.MAKER;

DEMO

答案 1 :(得分:1)

您触发无效,因为您犯了一个错误。该列为 MODAL _TOTALS而不是 MODEL _TOTALS

为使列MODAL_TOTALS总是在Car_Makers中获得一个值,您可以添加一个not null约束,或者可以将默认值设置为0

MODAL_TOTALS INT not null, 

MODAL_TOTALS INT Default 0,