Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- create or replace function test_function(filter_param1 varchar default null
- , filter_param2 varchar default null)
- returns integer as
- $$
- declare
- stmt text;
- args varchar[];
- wher varchar[];
- retid integer;
- begin
- if filter_param1 is not null then
- array_append(args, filter_param1);
- array_append(wher, 'parameter_name = $1');
- end if;
- if filter_param2 is not null then
- array_append(args, filter_param2);
- array_append(wher, 'parameter_name = $2');
- end if;
- stmt := 'select id from mytable where ' || array_to_string(wher, ' or ');
- execute stmt into retid using args;
- return retid;
- end;
- $$ language plpgsql;
- create or replace function test_function(_filter1 text = null
- , _filter2 text = null
- , OUT retid int) as
- $func$
- declare
- _args text[] := ARRAY[_filter1, _filter2];
- _wher text[];
- begin
- if _filter1 is not null then
- _wher := _wher || 'parameter_name = $1[1]'; -- note array subscript
- end if;
- if _filter2 is not null then
- _wher := _wher || 'parameter_name = $1[2]'; -- assign the result!
- end if;
- IF _args IS NULL -- check whether all params are NULL
- RAISE EXCEPTION 'At least one parameter required!';
- END IF;
- execute 'select id from mytable where ' -- cover the case with all params NULL
- || array_to_string(_wher, ' or ')
- || ' ORDER BY id LIMIT 1'; -- For a single value (???)
- into retid
- using _args;
- end
- $func$ language plpgsql;
- CREATE OR REPLACE FUNCTION test_function(_filter1 text = null
- , _filter2 text = null)
- RETURNS SETOF int AS
- $func$
- DECLARE
- _wher text := concat_ws(' OR '
- , CASE WHEN _filter1 IS NOT NULL THEN 'parameter_name = $1' END
- , CASE WHEN _filter2 IS NOT NULL THEN 'parameter_name = $2' END);
- BEGIN
- IF _wher = '' -- check whether all params are NULL
- RAISE EXCEPTION 'At least one parameter required!';
- END IF;
- RETURN QUERY EXECUTE 'SELECT id FROM mytable WHERE ' || _wher
- USING $1, $2;
- -- USING _filter1 , filter2; -- alternatively use func param names
- END
- $func$ LANGUAGE plpgsql;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement