1

I have a function with several IN params.

I need to build a complex select and use the params in the WHERE CLAUSE.

Is there any way I can add some conditioning like this:

if ($1 > 0)  then
 condition1 ='col1 = $1';
end if;

SELECT * from table1 WHERE || condition1 ;
johnlemon
  • 20,761
  • 42
  • 119
  • 178

2 Answers2

1

You can use dynamic SQL

http://www.postgresql.org/docs/current/static/plpgsql-statements.html

Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
0

Yes, you can execute dynamic commands using "execute"

if ($1 > 0)  then
 condition1 ='col1 = '||$1::varchar;
end if;

execute 'select * from table1 where '||condition1;

http://www.postgresql.org/docs/8.3/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Cesar
  • 500
  • 5
  • 12