[英]Getting error in Postgres trigger creation
I'm trying to create this trigger in my PostgresSql environment:我正在尝试在我的 PostgresSql 环境中创建此触发器:
CREATE TRIGGER MYTRIGGER
BEFORE INSERT
ON MYTABLE
FOR EACH ROW
BEGIN
IF( LENGTH( :NEW.VAL ) > 10 )
THEN
RAISE_APPLICATION_ERROR( -20003,
'Cannot exceed 10 chars' );
END IF;
IF :NEW.FQN_ID IS NULL THEN
:NEW.FQN_ID :=
CASE :NEW.SUBTYPECODE
WHEN NULL THEN 'A:'
WHEN 0 THEN 'B:'
WHEN 1 THEN 'C:'
WHEN 2 THEN 'D:'
ELSE 'Z:' || :NEW.SUBTYPECODE || '::'
--END || :NEW.OBJECTID;
END || STRUCTURE_FQNID_SEQ.NEXTVAL;
END IF;
END;
But I get this error:但我得到这个错误:
ERROR: syntax error at or near "BEGIN" LINE 5: BEGIN ^ SQL state: 42601 Character: 79
I think I'm missing something but I can't get it.我想我错过了一些东西,但我无法得到它。
Any suggestion would be greatly appreciated.任何建议将不胜感激。
Thank you.谢谢你。
Here are my notes about triggers in several DBMSs: https://github.com/iwis/SQL-notes .以下是我对几个 DBMS 中触发器的说明: https://github.com/iwis/SQL-notes 。 I marked the differences between the DBMSs in orange.
我用橙色标记了 DBMS 之间的差异。 I think that the notes are quite complete, so you don't have to read about triggers in Postgres documentation.
我认为注释已经很完整了,因此您不必阅读 Postgres 文档中有关触发器的内容。
I see the following changes that need to done in your example:我看到您的示例中需要进行以下更改:
:NEW
to Postgres NEW
.:NEW
更改为 Postgres NEW
。BEGIN... END
block, write EXECUTE FUNCTION my_trigger_function();
BEGIN... END
块,写EXECUTE FUNCTION my_trigger_function();
, where my_trigger_function
is a function that needs to be created like in the example given by a_horse_with_no_name. my_trigger_function
是一个 function,需要像 a_horse_with_no_name 给出的示例一样创建。 This function should return NEW
in your case - the reason is described here .NEW
- 原因 在此处描述。 If a more complicated code is fired by a trigger, then you also need to understand the differences between PL/SQL and PL/pgSQL languages.如果触发器触发了更复杂的代码,那么您还需要了解 PL/SQL 和 PL/pgSQL 语言之间的区别。 These languages are quite similar, though there are some differences.
这些语言非常相似,尽管存在一些差异。 Your code is simple so the differences are small.
您的代码很简单,因此差异很小。 It's probably enough to:
这可能就足够了:
RETURNS
in the function definition instead of Oracle RETURN
.RETURNS
而不是 Oracle RETURN
。$$
before BEGIN
, and $$ LANGUAGE plpgsql;
BEGIN
之前写$$
和$$ LANGUAGE plpgsql;
after END
.END
之后。RAISE 'Cannot exceed 10 chars';
RAISE 'Cannot exceed 10 chars';
instead of Oracle RAISE_APPLICATION_ERROR(-20003, 'Cannot exceed 10 chars');
RAISE_APPLICATION_ERROR(-20003, 'Cannot exceed 10 chars');
. I don't know if sequences work in the same way in PostgreSQL - I haven't read about them yet.我不知道序列在 PostgreSQL 中是否以相同的方式工作——我还没有读到它们。
Let me know if my notes are understandable - I'm not sure about it because they are super compact so you need to decipher the markings used by me.让我知道我的笔记是否可以理解 - 我不确定,因为它们非常紧凑,所以你需要破译我使用的标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.