Postgresql Function with optional parameters

£可爱£侵袭症+ 提交于 2021-01-29 09:59:56

问题


Is there a way to create a function which can be called with a variable number of parameters (comma separated, so positional). For example, calling a such function with function1(param1,param2) and possibly calling it with function1(,param2) or function1(param1,) ? I've created a function with default parameters but I've errors when calling it :

select * from iDxi('3 days',) order by "Date" asc
ERROR:  syntax error at or near ")"
LINE 1: select * from iDxi('3 days',) order by "Date" asc

My function definition is like:

CREATE OR REPLACE FUNCTION public.idxi(
    mydated text DEFAULT '99 year'::text,
    mydatef text DEFAULT '-99 year'::text)
RETURNS TABLE...

It works when providing no args select * from idxi() but not when providing only one...

Where am I wrong ?


回答1:


If you only want to pass the second parameter, pass it by name:

select *
from idxi(mydatef => '-3 days');

If you only want to pass the first parameter, you can simply pass it by position (without a , after the parameter)

select *
from idxi('3 days'); 

Or by name as well:

select *
from idxi(mydated => '3 days');

Unrelated, but:

If you want to pass intervals to the function, you should declare the parameters of that type:

CREATE OR REPLACE FUNCTION public.idxi(
    mydated interval DEFAULT '99 year'::interval,
    mydatef interval DEFAULT '-99 year'::interval)
RETURNS TABLE...


来源:https://stackoverflow.com/questions/59091412/postgresql-function-with-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!