简体   繁体   English

具有IF比较的Oracle SQL触发器

[英]Oracle SQL Trigger with IF Comparison

I want to create a trigger TR_rate, that checks a "features" field on new rows as they are inserted and adjusts a rate based on the features included. 我想创建一个触发器TR_rate,在插入新行时检查其“功能”字段,并根据所包含的功能来调整速率。

The features field can contain multiple values, and I want the condition to apply for each value. 功能字段可以包含多个值,我希望条件适用于每个值。 So if the field contains 'Feature1, Feature2', the rate should go up by 35. 因此,如果该字段包含“ Feature1,Feature2”,则速率应提高35。

My current code approach only works if there is one feature. 我当前的代码方法仅在具有一项功能的情况下有效。 How can I rewrite it to accomodate for multiple features? 如何重写它以适应多种功能?

CREATE OR REPLACE TRIGGER TR_rate
BEFORE INSERT 
ON rates_table 
FOR EACH ROW
BEGIN
    IF(:NEW.features = 'Feature1') THEN 
        :NEW.rate := (:NEW.rate + 15); 
    IF(:NEW.features = 'Feature2') THEN 
        :NEW.rate := (:NEW.rate + 20); 
    IF(:NEW.features = 'Feature3') THEN 
        :NEW.rate := (:NEW.rate + 30); 
    END IF; 
    END IF; 
    END IF; 
END;
/

You need your if statements to be sequential rather than nested, as well as using like : 您需要if语句是顺序的而不是嵌套的,并且需要使用like

IF(:NEW.features like '%Feature1%') THEN 
    :NEW.rate := (:NEW.rate + 15); 
END IF;
IF(:NEW.features like '%Feature2%') THEN 
    :NEW.rate := (:NEW.rate + 20); 
END IF;
IF(:NEW.features like '%Feature3%') THEN 
    :NEW.rate := (:NEW.rate + 30); 
END IF; 

However, I would just do this using a select : 但是,我只是使用select做到这一点:

select (new.rate +
        (case when :new.features like '%Feature1%' then 15 else 0 end) +
        (case when :new.features like '%Feature2%' then 20 else 0 end) +
        (case when :new.features like '%Feature3%' then 30 else 0 end)
       )
into :new.rate;

You can do the same thing at the PL/SQL level, but this captures the logic in a single statement. 您可以在PL / SQL级别上执行相同的操作,但这会在一条语句中捕获逻辑。

对所有三个重复以上操作:

IF(:NEW.features like '%Feature1%') THEN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM