简体   繁体   English

Oracle SQL:简单触发器问题,影响if子句中的值更改

[英]Oracle SQL: Simple Trigger Problem affecting change of values in if clause

I want to create a trigger in a table (called seat) with two attributes, seat number and seat class. 我想在具有两个属性(座位号和座位类)的表(称为座位)中创建触发器。 If the seat is higher than let's say 50, the class should be 'high', otherwise it should be 'low'. 如果座位高于例如50,则该班级应为“高”,否则应为“低”。 I want the trigger to automatically give the class when i enter a number! 我希望触发器在输入数字时自动给班级上课!

See what I've got till now, tried some alternates as well .. 看看我到目前为止所得到的,也尝试了一些替代品..

CREATE TRIGGER trigger_class
AFTER INSERT OR UPDATE ON seat
FOR EACH ROW
BEGIN
IF :NEW.seat_no <=50 THEN :NEW.class_code ='high';
ELSE :NEW.class_code = 'low';
END IF;
END; /

I'm very new into database coding, so... any help would be great! 我是数据库编码的新手,所以...任何帮助都将是很大的!

Change "=" to ":=", put the "/" on a new line, change "AFTER" to "BEFORE", and change "<= 50" to "> 50": 将“ =”更改为“:=”,将“ /”放在新行上,将“ AFTER”更改为“ BEFORE”,然后将“ <= 50”更改为“> 50。

CREATE OR REPLACE TRIGGER trigger_class
BEFORE INSERT OR UPDATE ON seat
FOR EACH ROW
BEGIN
IF :NEW.seat_no > 50 THEN :NEW.class_code :='high';
ELSE :NEW.class_code := 'low';
END IF;
END;
/

Apart from the syntax problems that jonearles already described: 除了jonearles已经描述的语法问题之外:

Unless you are just playing around with triggers (or this is some kind of homework), this is not a very good design. 除非您只是在玩触发器(或者这是某种作业),否则这不是一个很好的设计。

One rule in relational databases is that you should not store information that can be derived from existing data. 关系数据库中的一条规则是,您不应存储可以从现有数据派生的信息。

You can easily select the class_code during a select, there is no need to store it: 您可以在选择期间轻松选择class_code,无需存储它:

SELECT seat_no, 
       CASE 
         WHEN seat_no > 50 THEN 'high'
         ELSE 'low'
       END as class_code
FROM seat;

With Oracle 11 you can even define a virtual column that will do the "computation" automatically during retrieval, otherwise you could define a view that will return that information. 使用Oracle 11,您甚至可以定义一个虚拟列,该虚拟列将在检索期间自动执行“计算”,否则,您可以定义一个视图以返回该信息。

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

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