简体   繁体   English

使用MySQL存储过程的动态IN语句

[英]Dynamic IN statement with MySQL Stored Procedure

I'd like to build a dynamic IN Statement within a MySQL Stored Proc. 我想在MySQL存储过程中构建动态IN语句 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 . 这是我最接近成功的方法,但它仅处理列表中的第一个值: 103

I would prefer to use a stored proc and not to build this SQL statement completely in the client and then execute it. 我宁愿使用存储的proc而不是在客户端中完全构建此SQL语句然后执行它。 Does anyone know the general rules for dynamically building SQL statements in a stored procedure, esp in regards to the IN Statement? 有谁知道在存储过程中动态构建SQL语句的一般规则,尤其是IN语句方面的规则?

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. 怎样对MySQL使用FIND_IN_SET呢? I think this link may help you ( How to pass a list of IDs to MySQL stored procedure? ) 我认为此链接可能对您帮助( 如何将ID列表传递给MySQL存储过程?

The crucial part is to define 关键是要定义

szList as TEXT 

and use 和使用

FIND_IN_SET(Ex_Value, szlist) 

instead of Ex_Value IN (szlist) 代替Ex_Value IN(szlist)

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

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