0

我正在努力使 plpgsql if 语句的语法正确。

我想根据m2函数参数的值使用不同的 where 子句。

但我明白了ERROR: syntax error at or near "if"

create or replace function some_func(m1 int, m2 int)
returns table(match_id int) as
$$
begin
  return query
  select m.match_id from match as m
  if m2 < 1 then  -- ERROR:  syntax error at or near "if"
    where m.match_id > m1;
  else
    where m.match_id > m1 and m.match_id < m2;
  end if;
end;
$$ language 'plpgsql';

文件说我应该做

39.6.2.2. IF-THEN-ELSE

IF boolean-expression THEN
    statements
ELSE
    statements
END IF;

但似乎我已经做到了,所以我一定误解了 plpgsql 如何工作的其他方面。

4

1 回答 1

2

你需要一个 case 语句,而不是 if 语句。仅供参考,因为这是一个糟糕的查询,它应该看起来更像这样:

return query
select m.match_id from match as m
 where case
       when m2 < 1 then m.match_id > m1
       else             m.match_id > m1 and m.match_id < m2
       end;

在您的情况下,只需在没有案例的情况下重写查询:

return query
select m.match_id from match as m
 where m.match_id > m1
   and (m2 < 1 or m.match_id < m2);
于 2013-06-29T20:07:28.690 回答