0

I would like to know if there is a way to move arguments from the WHERE clause into a function call:

For example:

SELECT * FROM table1
WHERE a1 = ‘abc’ AND a2 = ‘def’;

But I would like the query to be rewritten as something like:

SELECT * FROM func1('a1=abc','b1=def');

It doesn’t matter what object table1 is, but I would imagine it could be a VIEW. In any case, I would like to provide an interface to the users like shown above, whereby the function-call gets hidden.

3
  • What exactly do you mean with "the function call gets hidden"? Commented Jan 26, 2012 at 14:40
  • I mean that it gets hidden from the users. So that, users can use these functions like they would tables, and likewise, could join using other tables via the WHERE clause. Commented Jan 26, 2012 at 15:23
  • see my answer. You can do that with a set returning function Commented Jan 26, 2012 at 15:28

1 Answer 1

1

You can create a set returning function that you can call like this:

SELECT *
FROM func1('abc', 'def');

The function looks something like this:

create or replace function func1(text, text)
  returns setof table1
as 
$body$
   SELECT * FROM table1 WHERE a1 = $1 and a2 = $2
$body$ 
LANGUAGE SQL;

More details in the manual:
http://www.postgresql.org/docs/current/static/xfunc-sql.html

You can also append a where clause to the select:

SELECT *
FROM func1('abc', 'def')
WHERE some_col > 100;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.