简体   繁体   English

如果以防查询,Postgres嵌套

[英]Postgres nested if in case query

Could you tell my why the following isnt working in postgres sql?: 你能告诉我为什么以下不能在postgres sql中工作吗?:

See updated code below

UPDATE: 更新:

I expect the query to return "0.30" as float. 我希望查询返回“0.30”作为浮点数。 This construct is only for testing purposes, i have some complex querys which depend on this conditional structure... BUt i dont know how to fix it.. 这个构造仅用于测试目的,我有一些复杂的查询依赖于这个条件结构... BUt我不知道如何解决它..

Result is: 结果是:

ERROR:  syntax error at or near "1"
LINE 4:     if 1=1 then

UPDATE: 更新:

This construction appears in a function... so I want to do following: 这个结构出现在一个函数中......所以我想做以下事情:

CREATE FUNCTION f_test(myvalue integer) RETURNS float AS $$
  BEGIN
    select (
      case (select '1')
      when '1' then
        if 1=1 then
          0.30::float
        else
          0.50::float
        end
      else
         1.00::float
      end
    );
  END;
$$ LANGUAGE plpgsql;

select f_test(1) as test;

Error message see above. 错误信息见上文。

There is no IF expr THEN result ELSE result END syntax for normal SQL queries in Postgres. 对于Postgres中的普通SQL查询,没有IF expr THEN result ELSE result END语法。 As there is neither an IF() function as in MySQL, you have to use CASE : 由于MySQL中既没有IF()函数,也必须使用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. 如果输入值为1,则函数返回0.3,否则返回1. 编辑:注意函数永远不会返回0.5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM