PostgreSQL IF-THEN-ELSE control structure

左心房为你撑大大i 提交于 2019-12-03 12:11:53
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.

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.

You're not enclosing that PL/pgSQL control structure in an anonymous block or a PL/pgSQL function.

For the SQL version of this control structure see the docs for CASE.

You're not enclosing that PL/pgSQL. They need to be enclosed with anonymous code block. Example for your code:

DO $$ BEGIN

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

END$$;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!