-1

Consider the following procedure:

CREATE PROCEDURE `getFoo`()
BEGIN
    select 'bar' as foo;
END;

Once call-ed, it outputs:

{"foo":"bar"}

But what if getFoo is invoked within a different stored procedure, how do I catch its result content into a variable, like this?

CREATE PROCEDURE `masterProc`()
BEGIN
    call `getFoo`() into @foo;
    select @foo as foo;
END;

This outputs the following error when invoked: sqlMessage: "FUNCTION db.getFoo does not exist"

I am aware of the available options involving out parameters, but those are not viable resolution(s) to my problem.

Obligation(s)

getFoo cannot be altered. It will output the results of a SELECT statement without involving any variables nor parameters.

What I've tried

Unfortunately, all will output errors.

set @foo = exec getFoo(); set @foo = call getFoo(); select getFoo() into @foo; call getFoo() into @foo;

Constantin
  • 848
  • 8
  • 23

2 Answers2

0

You cannot catch the result set (from SELECT) from another procedure. You have couple of options to do similar thing:

  1. Put the result set in temporary table. Works for multiple rows.
  2. Use OUT-variable (best for single values)
  3. Use user-defined variable (@var) (be careful with these as calls to other procedure can change the values)

Create the getFoo():

CREATE PROCEDURE getFoo()
BEGIN
drop temporary table if exists temptable;

create temporary table temptable 
as 
select col1, col2 FROM table1;

END;

Create the masterProc():

CREATE PROCEDURE masterProc()
BEGIN
    call getFoo();

    select *
    from temptable;
END $$

Call masterProc():

call masterProc();
slaakso
  • 8,331
  • 2
  • 16
  • 27
-1

The only way you can invoke an SP in mysql is with a CALL the error you get is because you are attempting to invoke a function which does not exist. User defined variables (at variables) are available anywhere

drop procedure if exists getfoo;
drop procedure if exists masterproc;
delimiter $$

CREATE PROCEDURE `getFoo`()
BEGIN
    set @foo = 'foo';
END $$

CREATE PROCEDURE `masterProc`()
BEGIN
    call `getFoo`();
    select @foo as foo;
END $$

delimiter ;

call masterproc();

+------+
| foo  |
+------+
| foo  |
+------+
1 row in set (0.001 sec)
P.Salmon
  • 17,104
  • 2
  • 12
  • 19
  • Your solution does not catch a *stored procedure*'s `SELECT` output into a variable of a master procedure. Your master procedure selects a variable persisting in the nested procedure, instead. – Constantin Nov 02 '20 at 11:13
  • @Constantin *catch a stored procedure's SELECT output into a variable of a master procedure* Impossible. – Akina Nov 02 '20 at 11:17