Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write function for optional parameters in postgresql?

My requirement is write optional parameters to a function.Parameters are optional sometimes i will add or i will not pass parameters to function.Can anyone help me how to write function.

I am writing like

select *  from test  where field3 in ('value1','value2')   and ($1 is null or field1 = $1)   and ($2 is null or field2 = $2)   and ($3 is null or field3 = $3); 

i am passing parameters to Query,But my output is not expected.when i pass all three parameters my output is correct,otherwise it is not expected output.

like image 666
indu Avatar asked Oct 06 '16 12:10

indu


People also ask

How do you pass an optional parameter to a function?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

What is optional parameter function?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.


1 Answers

You can define optional parameters by supplying a default value.

create function foo(p_one integer default null,                      p_two integer default 42,                      p_three varchar default 'foo')   returns text as $$ begin     return format('p_one=%s, p_two=%s, p_three=%s', p_one, p_two, p_three); end; $$ language plpgsql; 

You can "leave out" parameters from the end, so foo(), foo(1) or foo(1,2) are valid. If you want to only supply a parameter that is not the first you have to use the syntax that specifies the parameter names.

select foo();  

returns: p_one=, p_two=42, p_three=foo

select foo(1);  

returns: p_one=1, p_two=42, p_three=foo

select foo(p_three => 'bar') 

returns: p_one=, p_two=42, p_three=bar

like image 199
a_horse_with_no_name Avatar answered Sep 21 '22 16:09

a_horse_with_no_name