Mysql – How to access a result set from a stored procedure in another stored procedure

MySQLstored-procedures

I have a non-trivial SELECT statement and I don't want to write it twice (standard SW development considerations). I want to use the results in two stored procedures. I am imagining something like this:

CREATE PROCEDURE consumerProcedureA()
BEGIN
    CALL supplierProcedure();
    -- ** insert magic here **
END;

CREATE PROCEDURE consumerProcedureB()
BEGIN
    CALL supplierProcedure();
    -- ** insert magic here **
END;

CREATE PROCEDURE supplierProcedure()
BEGIN
    SELECT field1, field2, field3, MESSYEXPR AS field4
    FROM (complicated sub-SQL query) -- blah blah blah
    ;
END;

Grant you, I could create a view to capture the common query, but is there a way to have a calling stored procedure access and process the result set returned by a called stored procedure?

Best Answer

I am looking for a way to do this myself (in a way that satisfies me..), but a perfectly valid way to do so is described in this Stack Overflow Q & A:

Calling a Stored Procedure in a Stored Procedure in MySQL

The accepted answer by AhamedMustafaM demonstrates a technique using OUT parameters with the following code:

    CREATE PROCEDURE innerproc(OUT param1 INT)
    BEGIN
     insert into sometable;
     SELECT LAST_INSERT_ID() into param1 ;
    END
    -----------------------------------
    CREATE PROCEDURE outerproc()
    BEGIN
    CALL innerproc(@a);
    // @a gives you the result of innerproc
    SELECT @a INTO variableinouterproc FROM dual;
    END

I'm sure not always the answer for what you are trying to accomplish, but it is certainly an option. While you couldn't get the direct result of what the procedure called, this would help you get individual values, possibly using multiple OUT parameters to get what you need.