[英]Postgres Trigger function syntax error near BEGIN
I use PostgreSQL 12我使用 PostgreSQL 12
I have the following two tables:我有以下两个表:
table_a:表_a:
table_a_id | version
1 | v1
2 | v1
3 | v1
4 | v2
5 | v2
6 | v2
table_b:表_b:
table_b_id | version | table_a_id
1 | v1 | 1
2 | v1 | 2
3 | v1 | 3
4 | v2 | 4
5 | v2 | 5
6 | v2 | 6
table_b must reference same version table_a_id ie The below data is valid entry because table_a_id -> 1 belongs to version 'v1' table_b 必须引用相同的版本 table_a_id 即以下数据是有效条目,因为 table_a_id -> 1 属于版本'v1'
table_b_id | version | table_a_id
1 | v1 | 1
But the below data is invalid entry because table_a_id -> 4 belongs to version 'v2'但以下数据是无效条目,因为 table_a_id -> 4 属于版本 'v2'
table_b_id | version | table_a_id
1 | v1 | 4
I am new to Postgres trigger functions我是 Postgres 触发器函数的新手
I have created the following trigger function to validate ON BEFORE INSERT OR UPDATE to table_b:我创建了以下触发器 function 以在插入或更新到 table_b 之前验证 ON:
CREATE FUNCTION version_check()
RETURNS TRIGGER AS
$BODY$
BEGIN
IF NOT EXISTS (
SELECT
*
FROM
"table_a"
WHERE
"table_a"."table_a_id" = NEW."table_a_id"
AND
"table_a"."version" = NEW."version";
)
THEN
RAISE EXCEPTION 'table_a and table_b Version do not match';
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER "version_check" BEFORE INSERT OR UPDATE ON "table_b"
FOR EACH ROW EXECUTE PROCEDURE version_check();
I am getting the following error on saving the Trigger function in pgAdmin 4在 pgAdmin 4 中保存触发器 function 时出现以下错误
ERROR: syntax error at or near "BEGIN"
LINE 8: BEGIN
^
Am i doing any syntax error?我在做任何语法错误吗? Also will the above trigger function work fine for my requirement?
上述触发器 function 也能满足我的要求吗?
Thanks in advance!提前致谢!
You need to remove the ;
您需要删除
;
in your nested select在您的嵌套 select
IF NOT EXISTS (
SELECT
*
FROM
"table_a"
WHERE
"table_a"."table_a_id" = NEW."table_a_id"
AND
"table_a"."version" = NEW."version" --<< no semicolon here
)
One of the syntax errors is the semi colon ;
语法错误之一是分号
;
in nested Select statement在嵌套的 Select 语句中
I would like to add one more point that caused error while creating Trigger function is, in pgAdmin 4, you will have to open a new Query tool and execute the trigger function script rather than directly creating a Trigger function from pgAdmin 4 UI. I would like to add one more point that caused error while creating Trigger function is, in pgAdmin 4, you will have to open a new Query tool and execute the trigger function script rather than directly creating a Trigger function from pgAdmin 4 UI.
This solved my problem.这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.