Why do I always get the following error from Postgres?
为什么我总是从Postgres得到以下错误?
syntax error at or near "IF"
“IF”处或附近的语法错误
I read PostgreSQL: Documentation: 8.3: Control Structures. First I tried to execute a difficult query (with subquery), but then I tried to execute a simple one like this:
我读了PostgreSQL:文档:8.3:控制结构。首先,我尝试执行一个困难的查询(使用子查询),但后来我尝试执行这样一个简单的查询:
IF 2 <> 0 THEN select * from users; END IF;
The error is still the same. What am I doing wrong?
错误仍然相同。我究竟做错了什么?
3 个解决方案
#1
18
IF 2 <> 0 THEN select * from users; END IF;
You cannot use PL/pgSQL statements outside plpgsql functions. And if this fragment is from plpgsql function, then it is nonsense too. You cannot directly return result of query like T-SQL does.
您不能在plpgsql函数之外使用PL / pgSQL语句。如果这个片段来自plpgsql函数,那么它也是无意义的。你不能像T-SQL那样直接返回查询结果。
CREATE OR REPLACE FUNCTION test(p int)
RETURNS SETOF users AS $$
BEGIN
IF p = 1 THEN
RETURN QUERY SELECT * FROM users;
END IF;
RETURN;
END;
$$ LANGUAGE plpgsql;
When you would get some result from function, you have to use RETURN statement - plpgsql knows only function, it doesn't support procedures - so unbounded SELECT has not sense.
当你从函数得到一些结果时,你必须使用RETURN语句 - plpgsql只知道函数,它不支持程序 - 所以无限制的SELECT没有意义。
#2
4
You're not enclosing that PL/pgSQL control structure in an anonymous block or a PL/pgSQL function.
您没有将该PL / pgSQL控件结构包含在匿名块或PL / pgSQL函数中。
For the SQL version of this control structure see the docs for CASE
.
对于此控件结构的SQL版本,请参阅CASE的文档。
#3
1
You're not enclosing that PL/pgSQL. They need to be enclosed with anonymous code block. Example for your code:
你没有附上那个PL / pgSQL。它们需要包含匿名代码块。代码示例:
DO $$ BEGIN
IF 2 <> 0 THEN select * from users; END IF;
END$$;
#1
18
IF 2 <> 0 THEN select * from users; END IF;
You cannot use PL/pgSQL statements outside plpgsql functions. And if this fragment is from plpgsql function, then it is nonsense too. You cannot directly return result of query like T-SQL does.
您不能在plpgsql函数之外使用PL / pgSQL语句。如果这个片段来自plpgsql函数,那么它也是无意义的。你不能像T-SQL那样直接返回查询结果。
CREATE OR REPLACE FUNCTION test(p int)
RETURNS SETOF users AS $$
BEGIN
IF p = 1 THEN
RETURN QUERY SELECT * FROM users;
END IF;
RETURN;
END;
$$ LANGUAGE plpgsql;
When you would get some result from function, you have to use RETURN statement - plpgsql knows only function, it doesn't support procedures - so unbounded SELECT has not sense.
当你从函数得到一些结果时,你必须使用RETURN语句 - plpgsql只知道函数,它不支持程序 - 所以无限制的SELECT没有意义。
#2
4
You're not enclosing that PL/pgSQL control structure in an anonymous block or a PL/pgSQL function.
您没有将该PL / pgSQL控件结构包含在匿名块或PL / pgSQL函数中。
For the SQL version of this control structure see the docs for CASE
.
对于此控件结构的SQL版本,请参阅CASE的文档。
#3
1
You're not enclosing that PL/pgSQL. They need to be enclosed with anonymous code block. Example for your code:
你没有附上那个PL / pgSQL。它们需要包含匿名代码块。代码示例:
DO $$ BEGIN
IF 2 <> 0 THEN select * from users; END IF;
END$$;