0

I need to create a function in PostgreSQL for the following :

  • Query multiple tables based on a business logic (all result sets return the same type of data)

  • Compile all result sets into one table and return that table

    Is it possible to accomplish this without using the temp tables in PostgreSQL?

    I currently do this in Microsoft SQL server using Table Variables, below is a sample function:


create  FUNCTION test(@search_in nvarchar(500))

RETURNS @data_table TABLE
( 
    item_id int, 
    item_type nvarchar(1), 
    first_name nvarchar(100), 
    last_name nvarchar(100))
) AS
BEGIN
    -- from first table
    if charindex('search_in_authors', @search_in) > 0
        insert into @data_table
        select item_id, 'a', first_name, last_name
        from authors
        where first_name = 'james'

    -- from second table
    if charindex('search_in_editors', @search_in) > 0

        insert into @data_table
        select item_id, 'e', first_name, last_name
        from editors
        where first_name = 'james'

    -- from third table
    if charindex('search_in_publishers', @search_in) > 0
        insert into @data_table
        select item_id, 'p', first_name, last_name
        from publishes
        where first_name = 'james'

    -- there could be more like these based on the business logic...

    (...)

    -- finally return the records compiled in @data_table

    RETURN

END

Sample calls to the function:

select * from dbo.test('search_in_authors')

select * from dbo.test('search_in_authors, search_in_editors')

select * from dbo.test('search_in_authors, search_in_editors,search_in_publishers ')

Are there any options in PostgreSQL to achieve this other than using a temp table ?

Thanks, San

1 Answer 1

1

You can use RETURN QUERY to add the result of various queries to the output.

CREATE OR REPLACE FUNCTION public.testf() 
RETURNS TABLE(id INTEGER, name text)
STABLE  
AS $$
  DECLARE

  BEGIN
    RETURN QUERY select 1 as id, 'abc' as name;

    RETURN QUERY select 2 as id, 'def' as name;

    RETURN QUERY select 3 as id, 'xyz' as name;

    -- Final return as set is now complete.
    return;

  END;
$$ LANGUAGE plpgsql;


select * from public.testf();

 id | name
----+------
  1 | abc
  2 | def
  3 | xyz
(3 rows)
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.