我正在努力使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如何工作的其他方面。
答案 0 :(得分: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);