PostgreSQL IF-THEN-ELSE控制结构 [英] PostgreSQL IF-THEN-ELSE control structure

查看:816
本文介绍了PostgreSQL IF-THEN-ELSE控制结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我总是从Postgres收到以下错误消息?

Why do I always get the following error from Postgres?

syntax error at or near "IF"

我阅读了 PostgreSQL:文档:8.3:控制结构.首先,我尝试执行一个困难的查询(带有子查询),但是随后我尝试执行一个简单的查询,如下所示:

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:

IF 2 <> 0 THEN select * from users; END IF;

错误仍然相同.我在做什么错了?

The error is still the same. What am I doing wrong?

推荐答案

IF 2 <> 0 THEN select * from users; END IF;

您不能在plpgsql函数之外使用PL/pgSQL语句.而且,如果此片段来自plpgsql函数,那么它也是无稽之谈.您不能像T-SQL一样直接返回查询结果.

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.

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;

当要从函数中获得某些结果时,必须使用RETURN语句-plpgsql仅知道函数,它不支持过程-因此无限制的SELECT毫无意义.

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.

这篇关于PostgreSQL IF-THEN-ELSE控制结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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