简体   繁体   中英

Dynamic IN statement with MySQL Stored Procedure

I'd like to build a dynamic IN Statement within a MySQL Stored Proc. I've tried a number of ways but am unable to get something that works. This is the closest I've come to success, but it only process the first value in the list: 103 .

I would prefer to use a stored proc and not to build this SQL statement completely in the client and then execute it. Does anyone know the general rules for dynamically building SQL statements in a stored procedure, esp in regards to the IN Statement?

call foo2('103,104,105,106');

Here is the stored proc:

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `foo2`(
szList VARCHAR(256)
)
BEGIN

SELECT 
    E_Id, EX_Value

FROM 
    E

WHERE 
    EX_Value IN (szList);

END

what about use FIND_IN_SET for MySQL. I think this link may help you ( How to pass a list of IDs to MySQL stored procedure? )

The crucial part is to define

szList as TEXT 

and use

FIND_IN_SET(Ex_Value, szlist) 

instead of Ex_Value IN (szlist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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