Postgres nested if in case query

為{幸葍}努か 提交于 2019-12-03 13:30:24

There is no IF expr THEN result ELSE result END syntax for normal SQL queries in Postgres. As there is neither an IF() function as in MySQL, you have to use CASE:

select (
  case (select '1')
  when '1' then
    case when 1=1 then 0.30::float else 0.50::float end
  else
     1.00::float
  end
);

I don't know what you're trying to achieve with this function, but here's a working version.

CREATE FUNCTION f_test(myvalue integer) RETURNS float AS $$
BEGIN
    IF myvalue = 1 THEN
            IF 1=1 THEN
                    RETURN 0.30::FLOAT;
            ELSE
                    RETURN 0.50::FLOAT;
            END IF;
    ELSE
            RETURN 1.0::FLOAT;
    END IF;
END;

The function returns 0.3 if input value is 1, otherwise it'll return 1. Edit: Note that 0.5 is never returned by the function.

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