SQL多输入查询实现:存储过程多值参数输入失效问题求助
存储过程多参数(逗号分隔值)查询失效问题
我需要通过动态查询获取数据表数据,单参数输入时功能正常,但传入逗号分隔的多值参数时无法正常工作。
以下是我的存储过程:
drop procedure if exists listview; delimiter // create procedure listview( inq_type text, inq_mccd text, inq_prod text, inq_item text) begin declare inq text; SET inq_mccd = IFNULL(inq_mccd,""); SET inq_prod = IFNULL(inq_prod,""); SET inq_item = IFNULL(inq_item,""); select concat(' select distinct ',inq_type,' from condition_history where 1=1 and (case when ? = "" then 1 else MCCODE like concat("%",?,"%") end) and (case when ? = "" then 1 else PRODSTD like concat("%",?,"%") end) and (case when ? = "" then 1 else ITEMCODE like concat("%",?,"%") end) ') into inq; prepare stmt from inq; execute stmt using inq_mccd, inq_mccd, inq_prod, inq_prod, inq_item, inq_item; end// delimiter ;
-- 单参数输入正常
call listview("ITEMCODE", "XMC029" , Null, Null);
-- 多参数输入失效,我希望同时支持如下单输入和多输入形式
call listview("ITEMCODE", "XMC029,XMC030", "X-R-080", Null);
问题原因
当前存储过程会把逗号分隔的多值参数当成单个字符串进行模糊匹配(比如MCCODE like "%XMC029,XMC030%"),而非拆分多个值分别匹配,导致查询结果不符合预期。
修改方案
对每个参数做分支处理:空值时跳过匹配,单值时保留模糊匹配,多值时转为IN精确匹配逻辑。修改后的存储过程如下:
drop procedure if exists listview; delimiter // create procedure listview( inq_type text, inq_mccd text, inq_prod text, inq_item text) begin declare inq text; SET inq_mccd = IFNULL(inq_mccd,""); SET inq_prod = IFNULL(inq_prod,""); SET inq_item = IFNULL(inq_item,""); -- 构建MCCODE匹配条件 set @mccd_cond = case when inq_mccd = "" then "1=1" when locate(',', inq_mccd) > 0 then concat("MCCODE in ('", replace(inq_mccd, ",", "','"), "')") else concat("MCCODE like concat('%', '", inq_mccd, "', '%')") end; -- 构建PRODSTD匹配条件 set @prod_cond = case when inq_prod = "" then "1=1" when locate(',', inq_prod) > 0 then concat("PRODSTD in ('", replace(inq_prod, ",", "','"), "')") else concat("PRODSTD like concat('%', '", inq_prod, "', '%')") end; -- 构建ITEMCODE匹配条件 set @item_cond = case when inq_item = "" then "1=1" when locate(',', inq_item) > 0 then concat("ITEMCODE in ('", replace(inq_item, ",", "','"), "')") else concat("ITEMCODE like concat('%', '", inq_item, "', '%')") end; -- 拼接最终动态SQL select concat(' select distinct ',inq_type,' from condition_history where 1=1 and ', @mccd_cond, ' and ', @prod_cond, ' and ', @item_cond, ' ') into inq; prepare stmt from inq; execute stmt; deallocate prepare stmt; end// delimiter ;
说明
- 多值处理:用
replace将逗号分隔的字符串转为IN ('值1','值2')格式,实现多值精确匹配。 - 单值逻辑:保留原有的模糊匹配规则,兼容单参数场景。
- 空值兼容:参数为空时,条件设为
1=1,不影响原有查询逻辑。
测试多参数调用:
call listview("ITEMCODE", "XMC029,XMC030", "X-R-080", Null);
此时会正确生成MCCODE in ('XMC029','XMC030')的条件,返回符合要求的结果。
内容的提问来源于stack exchange,提问作者han K
相关产品推荐
相关产品推荐

