开发者

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 st开发者_开发问答atement 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜