在“IF”或附近的Postgres语法错误 [英] Postgres syntax error at or near "IF"

查看:163
本文介绍了在“IF”或附近的Postgres语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是postgres的新手,我正在完成我的任务。我不得不创建一个只有1列的表,然后我得到了这个声明在pgadmin III上运行:

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:

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;

当我运行此操作时出现此错误:语法错误在IF处或附近

when I run this I get this error: syntax error at or near "IF"

我已经看过这个 38.6.2。 Conditionals38.6.2。条件,我不太了解这一点,我是否需要更改查询

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

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??

推荐答案

IF和其他PL / pgSQL功能仅在PL / pgSQL函数中可用。如果要使用 IF ,则需要将代码包装在函数中。如果您使用的是9.0+,那么您可以使用 DO 编写内联函数:

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:

do $$
begin
  -- code goes here
end
$$

如果你正在使用在早期版本的PostgreSQL中,你必须编写一个包含代码的命名函数,然后执行该函数。

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.

这篇关于在“IF”或附近的Postgres语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆