postgresql - Using IF in function for different queries as a result - Stack Overflow

I need to create a PostgreSQL function that will execute a query depending on the input value.Like thi

I need to create a PostgreSQL function that will execute a query depending on the input value.

Like this on

FUNCTION public.get_data( in_param smallint)
...

BEGIN

WITH cte1 as ( 
  select * from tbl1),

  IF in_param=1 THEN
  cte2 as (
  select * from tbl2
  where tbk2.col1 > 5 
  )
  ELSE 
  cte2 as (
  select * from tbl2
  where tbl2.col3 < 0 
  )
  END IF


  select * from cte1, cte2
  ...

END  

How I can do it?

I need to create a PostgreSQL function that will execute a query depending on the input value.

Like this on

FUNCTION public.get_data( in_param smallint)
...

BEGIN

WITH cte1 as ( 
  select * from tbl1),

  IF in_param=1 THEN
  cte2 as (
  select * from tbl2
  where tbk2.col1 > 5 
  )
  ELSE 
  cte2 as (
  select * from tbl2
  where tbl2.col3 < 0 
  )
  END IF


  select * from cte1, cte2
  ...

END  

How I can do it?

Share Improve this question edited Jan 31 at 10:18 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Jan 31 at 10:13 EducatEducat 51 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 2

A case expression in the where clause rather than an if statement will do the job.

WITH cte1 as 
( 
  select * from tbl1
),
cte2 as 
(
  select * from tbl2
  where case when in_param = 1 then (col1 > 5) else (col3 < 0) end
)
...

Unrelated but cte1 is trivial and equivalent to tbl1 therefore unnecessary.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745269560a4619661.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信