oracle 使用触发器更改插入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20021644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 02:05:29  来源:igfitidea点击:

Change inserted value with trigger

oracleplsqldatabase-trigger

提问by hepifish

I've just started to learn SQL a few weeks ago and I'm trying to make a trigger which changes the inserted value into 10 if it's smaller than 10. I searched for 4h now and I've found a lot of answers but none was good(for me). I really don't understand where the problem is. Here is the code:

几周前我刚刚开始学习 SQL,我正在尝试制作一个触发器,如果​​插入的值小于 10,它会将插入的值更改为 10。我现在搜索了 4h,我找到了很多答案,但没有很好(对我来说)。我真的不明白问题出在哪里。这是代码:

CREATE OR REPLACE TRIGGER NumberOfBooks
BEFORE INSERT
ON Book
FOR EACH ROW
BEGIN 
  IF new.nobook < 10
  THEN
    SET new.nobook = 10;
  END IF;
  END;

采纳答案by Mureinik

In Oracle's trigger syntax the newly inserted record is referred to by :new, not new(notice the colon). Additionally, SETis a part of an update statement, not a way to set field values - those are done by simple assignments, but note that these are done with :=rather than =.
So, your trigger should read:

在 Oracle 的触发器语法中,新插入的记录由:new, not new(注意冒号)引用。此外,SET是更新语句的一部分,而不是设置字段值的方法 - 这些是通过简单的赋值完成的,但请注意,这些是用:=而不是=.
所以,你的触发器应该是:

CREATE OR REPLACE TRIGGER NumberOfBooks
    BEFORE INSERT
    ON book
    FOR EACH ROW
BEGIN
    IF :new.nobook < 10
    THEN
        :new.nobook := 10;
    END IF;
END;