MySQL - Using stored procedure results to define an IN statement

I'd like to use a stored procedure to define the IN clause of a select statement.

This is (a simplified version of) what I'm trying to do:

SELECT * 
FROM myTable 
WHERE columnName IN (CALL myStoredProc)

myStoredProc performs some complicated logic in the database and returns a list of possible matching values for columnName. The statement above does not work obviously. The select statement may be performed in another stored procedure if that makes a difference.

Is this at all possible in mySQL?

Asked By: Ryan
||

Answer #1:

What return type does your current stored procedure have? You are speaking of "a list", so TEXT?

Maybe there's an easier way, but one thing you can do (inside another stored procedure) is to build another query.

To do that, we need to work around two limitations of MySQL: a) To execute dynamic SQL inside a stored procedure, it needs to be a prepared statement. b) Prepared statements can only be created out of user variables. So the complete SQL is:

SET @the_list = myStoredProc();
SET @the_query = CONCAT('SELECT * FROM myTable WHERE columnName IN (' , @the_list , ')');
PREPARE the_statement FROM @the_query;
EXECUTE the_statement;

If you're talking about returning a result set from a stored routine and then using it as table, that is not possible. You need to make a temporary table to work around this limitation.

Answered By: AndreKR
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles