简体   繁体   中英

Get stored procedure resultset inside another stored procedure

Let's say I have multiples stored procedures that uses the same subquery in IN clauses. The subquery select a list of IDs. My reflex was to go a ahead and create a new stored procedure containing this subquery to define it in a single place, and use it inside the others procedures. Now I realize that I cannot get the resultset from the subquery when calling the stored procedure... I searched and found no alternatives other than defining a temporary table, which I found overkill to get a couples Ids. Is there something I'm missing or I simply cannot do this in MYSQL?

To illustrate my problem:

CREATE PROCEDURE subquery()
BEGIN   
    SELECT id from example; # returns a list of IDs
END;

CREATE PROCEDURE procedure1()
BEGIN   
    SELECT * from example2 WHERE id IN (CALL subquery()); # No go, syntax error
END;

CREATE PROCEDURE procedure2()
BEGIN
    SET @resultSet = CALL subquery();
    SELECT * from example2 WHERE id IN (@resultSet); # No go, syntax error
END;

Of course the real subquery is a big chunk of SQL that I prefer to maintain in a single place.

As I understand it, I can't use Functions as they only returns scalars values, and I can't use OUT parameters as they don't allow resultsets.

What are my alternatives here other than multiplying subqueries or using temporary table as defined here ?

Unfotunatelly you cannot use a stored procedure output inside another stored procedure in MySQL. But if your subquery does not require parameters the best option (in my opinion) is a VIEW:

CREATE VIEW myView AS select id from example;

and then you can reference your view as a table (inside other stored procs as well):

SELECT * from example2 WHERE id IN (select id from myView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM