How to return a multiple tables result in stored procedure or function in PostgreSQL?
I need to return multiple tables result set in PostgreSQL and fetch the details in Nest.JS Application, Can any one explain on this work?
How to return a multiple tables result in stored procedure or function in PostgreSQL?
I need to return multiple tables result set in PostgreSQL and fetch the details in Nest.JS Application, Can any one explain on this work?
2
Answers
In PostgreSQL, you can use a function that returns a set of rows or multiple result sets using the RETURNS TABLE syntax. Here is an example of how you can create a function that returns multiple tables:
Let’s say you want to return two tables with different structures. You can define a custom type for each table, and then the function can return a set of these custom types.
In this example:
table1_type and table2_type are custom types representing the structure of your tables.
The get_multiple_tables function returns a set of rows with two columns, each of the custom types.
Inside the function, you can perform queries for each table and assign the results to the corresponding variables of custom types.
To call this function:
Remember to replace your_table1 and your_table2 with the actual names of your tables.
This is just a basic example, and you might need to adjust it based on your specific use case and table structures.
PostgreSQL doesn’t support multirecordset, and it doesn’t support return result from procedures, so you cannot to do it. You can open lot of cursors inside procedure, and you can read from these cursors outside – until the related transaction end.
This pattern commonly used in MSSQL is not supported by Postgres, and you should to rewrite your code to not use it.