SQL “IF”处或附近的 Postgres 语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20957292/
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
Postgres syntax error at or near "IF"
提问by S. N
I am new to postgres and I am working on an assignment of mine. I had to create a table with only 1 column and, then I was given this statement to run in on pgadmin III:
我是 postgres 的新手,我正在处理我的任务。我必须创建一个只有 1 列的表,然后我得到了这个语句来在 pgadmin III 上运行:
BEGIN;
INSERT INTO mytable VALUES (1);
SAVEPOINT savepoint1;
INSERT INTO mytable VALUES (2);
ROLLBACK TO SAVEPOINT savepoint1;
INSERT INTO mytable VALUES (3);
SAVEPOINT savepoint2;
INSERT INTO mytable VALUES (4);
INSERT INTO mytable VALUES (5);
SAVEPOINT savepoint3;
SELECT * FROM mytable;
--NOTE: You need to run this IF statement as PGScript
--(button next to the normal run button)
IF (CAST ((SELECT MAX(id) FROM mytable) AS INTEGER) = 4)
BEGIN
RELEASE SAVEPOINT savepoint2;
END
ELSE
BEGIN
INSERT INTO mytable VALUES(6);
END
--Run the next steps normally
SAVEPOINT savepoint2;
INSERT INTO mytable VALUES (7);
RELEASE SAVEPOINT savepoint2;
INSERT INTO mytable VALUES (8);
ROLLBACK TO savepoint2;
COMMIT;
when I run this I get this error: syntax error at or near "IF"
当我运行它时,我收到此错误:“IF”处或附近的语法错误
I have already take a look at this 38.6.2. Conditionals38.6.2. Conditionals, I dont understand this very well, Do I need to change the query to have
这个38.6.2我已经看过了。条件 38.6.2。条件,我不太明白这一点,我是否需要更改查询以具有
IF (CAST ((SELECT MAX(id) FROM mytable) AS INTEGER) = 4) THEN
BEGiN
and then when it ends I should end it with:
然后当它结束时,我应该以:
END IF
Why there is an error after all??
为什么会出现错误呢??
回答by mu is too short
IF and other PL/pgSQL features are only available inside PL/pgSQL functions. You need to wrap your code in a function if you want to use IF
. If you're using 9.0+ then you can do use DO
to write an inline function:
IF 和其他 PL/pgSQL 功能仅在 PL/pgSQL 函数内部可用。如果您想使用IF
. 如果您使用的是 9.0+,那么您可以使用DO
来编写内联函数:
do $$
begin
-- code goes here
end
$$
If you're using an earlier version of PostgreSQL then you'll have to write a named function which contains your code and then execute that function.
如果您使用的是较早版本的 PostgreSQL,则必须编写一个包含代码的命名函数,然后执行该函数。
回答by nozem
Not the answer for the OP, but possibly the answer for some who end up here (like myself): If you DECLARE variables within the BEGIN-END block, you will get the same syntax error.
不是 OP 的答案,但可能是某些人(比如我自己)的答案:如果您在 BEGIN-END 块中声明变量,您将得到相同的语法错误。
So this is wrong:
所以这是错误的:
DO $$
BEGIN
DECLARE my_var VARCHAR(50) := 'foo';
IF some_var IS NULL THEN
--some logic
END IF;
END;
$$
This should fix it:
这应该解决它:
DO $$
DECLARE my_var VARCHAR(50) := 'foo';
BEGIN
IF some_var IS NULL THEN
--some logic
END IF;
END;
$$