简体   繁体   English

MySQL-使用存储过程结果定义一个IN语句

[英]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. 我想使用存储过程来定义select语句的IN子句。

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 . myStoredProc在数据库中执行一些复杂的逻辑,并返回columnName可能匹配值的列表。 The statement above does not work obviously. 上面的陈述显然不起作用。 The select statement may be performed in another stored procedure if that makes a difference. 如果不同,可以在另一个存储过程中执行select语句。

Is this at all possible in mySQL? 这在MySQL中根本可行吗?

What return type does your current stored procedure have? 您当前的存储过程有什么返回类型? You are speaking of "a list", so TEXT? 您说的是“列表”,所以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. 为此,我们需要解决MySQL的两个限制:a)要在存储过程中执行动态SQL,它必须是准备好的语句。 b) Prepared statements can only be created out of user variables. b)只能从用户变量中创建预准备语句。 So the complete SQL is: 因此,完整的SQL是:

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 . 您需要制作一个临时表来解决此限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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