SQL PostgreSQL IF-THEN-ELSE 控制结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10011862/
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
PostgreSQL IF-THEN-ELSE control structure
提问by Pavel Stehule
Why do I always get the following error from Postgres?
为什么我总是从 Postgres 收到以下错误?
syntax error at or near "IF"
syntax error at or near "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?
错误还是一样。我究竟做错了什么?
回答by Pavel Stehule
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 没有意义。
回答by Milen A. Radev
You're not enclosing that PL/pgSQL control structure in an anonymous blockor a PL/pgSQL function.
您没有将该 PL/pgSQL 控制结构包含在匿名块或 PL/pgSQL 函数中。
For the SQL version of this control structure see the docs for CASE
.
有关此控制结构的 SQL 版本,请参阅CASE
.
回答by user
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$$;