Ask Your Question
2

Can you perform a PostgreSQL stored procedure call and fetch query simultaneously?

asked 2023-06-21 05:22:42 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-21 05:52:02 +0000

scrum gravatar image

Yes, it is possible to perform a PostgreSQL stored procedure call and fetch query simultaneously using the INOUT parameter.

Here's an example:

CREATE OR REPLACE FUNCTION get_employee_details(INOUT emp_id INTEGER, OUT emp_name VARCHAR, OUT emp_salary NUMERIC) 
LANGUAGE plpgsql
AS $$
BEGIN
     SELECT name, salary INTO  emp_name, emp_salary FROM employees WHERE id = emp_id;

     SELECT count(*) INTO emp_id FROM employees WHERE salary > emp_salary;
END;
$$;

DECLARE
    emp_id INTEGER := 1;
    emp_name VARCHAR;
    emp_salary NUMERIC;
BEGIN
    SELECT emp_id, emp_name, emp_salary 
    FROM get_employee_details(emp_id, emp_name, emp_salary);

    -- Do something with the results
END;

In this example, we have defined a stored procedure get_employee_details that takes an INOUT parameter emp_id and two OUT parameters emp_name and emp_salary.

Inside the stored procedure, we first fetch the name and salary of the employee with the given emp_id and assign them to the emp_name and emp_salary parameters.

Then, we run another query to count the number of employees whose salary is greater than the fetched employee's salary and assign the count to the same emp_id parameter.

Finally, in the main program, we call the stored procedure by passing the emp_id, emp_name, and emp_salary variables as arguments. The stored procedure modifies the emp_id parameter, which is then used to fetch the results and do something with them.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-21 05:22:42 +0000

Seen: 12 times

Last updated: Jun 21 '23