Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. create or replace function test_function(filter_param1 varchar default null
  2. , filter_param2 varchar default null)
  3. returns integer as
  4. $$
  5. declare
  6. stmt text;
  7. args varchar[];
  8. wher varchar[];
  9. retid integer;
  10. begin
  11. if filter_param1 is not null then
  12. array_append(args, filter_param1);
  13. array_append(wher, 'parameter_name = $1');
  14. end if;
  15. if filter_param2 is not null then
  16. array_append(args, filter_param2);
  17. array_append(wher, 'parameter_name = $2');
  18. end if;
  19.  
  20. stmt := 'select id from mytable where ' || array_to_string(wher, ' or ');
  21. execute stmt into retid using args;
  22.  
  23. return retid;
  24. end;
  25. $$ language plpgsql;
  26.  
  27. create or replace function test_function(_filter1 text = null
  28. , _filter2 text = null
  29. , OUT retid int) as
  30. $func$
  31. declare
  32. _args text[] := ARRAY[_filter1, _filter2];
  33. _wher text[];
  34. begin
  35. if _filter1 is not null then
  36. _wher := _wher || 'parameter_name = $1[1]'; -- note array subscript
  37. end if;
  38.  
  39. if _filter2 is not null then
  40. _wher := _wher || 'parameter_name = $1[2]'; -- assign the result!
  41. end if;
  42.  
  43. IF _args IS NULL -- check whether all params are NULL
  44. RAISE EXCEPTION 'At least one parameter required!';
  45. END IF;
  46.  
  47. execute 'select id from mytable where ' -- cover the case with all params NULL
  48. || array_to_string(_wher, ' or ')
  49. || ' ORDER BY id LIMIT 1'; -- For a single value (???)
  50. into retid
  51. using _args;
  52. end
  53. $func$ language plpgsql;
  54.  
  55. CREATE OR REPLACE FUNCTION test_function(_filter1 text = null
  56. , _filter2 text = null)
  57. RETURNS SETOF int AS
  58. $func$
  59. DECLARE
  60. _wher text := concat_ws(' OR '
  61. , CASE WHEN _filter1 IS NOT NULL THEN 'parameter_name = $1' END
  62. , CASE WHEN _filter2 IS NOT NULL THEN 'parameter_name = $2' END);
  63. BEGIN
  64. IF _wher = '' -- check whether all params are NULL
  65. RAISE EXCEPTION 'At least one parameter required!';
  66. END IF;
  67.  
  68. RETURN QUERY EXECUTE 'SELECT id FROM mytable WHERE ' || _wher
  69. USING $1, $2;
  70. -- USING _filter1 , filter2; -- alternatively use func param names
  71. END
  72. $func$ LANGUAGE plpgsql;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement