MYSQL存储过程字符串参数列表并使用IN子句

时间:2014-05-27 05:04:49

标签: mysql vb.net stored-procedures

我有这个存储过程查询。我在我的vb.net数据集中使用此代码,所以我需要在我的每个where子句中传递参数。或者我可以从我的vb.net传递我的整个where子句在这个存储过程中。如果不能我怎么做“where IN子句”,因为如果我调用我的存储过程我会收到错误。

也许有人可以告诉我如何处理这个问题。

DELIMITER $$

DROP PROCEDURE IF EXISTS `lcs_rdb`.`sp_MissedCallsReport`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_MissedCallsReport`()
BEGIN
    select
    cdr_extension_no, cdr_charge_to, COUNT(cdr_call_type_code) as answered, 
    SUM(cdr_call_type_code = 'BSY') as Busy,
    sum(cdr_call_type_code = 'ABN') as abandon, 
    sum(cdr_call_type_code in ('BSY','ABN')) as total,
    coalesce((sum(case cdr_call_type_code when 'ABN' then cdr_duration_number/60000 else 0 end) / sum(cdr_call_type_code = 'ABN')),0) as avg_abandon,
    coalesce((sum(cdr_call_type_code in ('BSY','ABN')) / 
    (sum(cdr_call_type_code in ('BSY','ABN')) + COUNT(cdr_call_type_code))) *100,0) as missed_calls_rate
    from cdr_departments 
        where cdr_site_id = '{0}' AND 
    cdr_datetime BETWEEN '{1}' AND '{2}' 
    AND cdr_call_class_id IN({3}) AND cdr_call_type_id IN({4}) 
    AND cdr_extension_id IN({5}) or cdr_route_member_id IN ({6})
GROUP BY cdr_extension_no;
    END$$

    DELIMITER ;

1 个答案:

答案 0 :(得分:0)

我建议您使用IN参数存储过程与WHERE子句一起使用。

示例

PROCEDURE `sp_MissedCallsReport`(
   IN param_cdr_site_id INT
 , IN param_cdr_datetime_min DATETIME
 , IN param_cdr_datetime_max DATETIME
 , IN param_cdr_call_class_id_csv VARCHAR(1024) -- csv integers
 , IN param_cdr_call_type_id_csv VARCHAR(1024) -- csv integers
 , IN param_cdr_extension_id_csv VARCHAR(1024) -- csv integers
 , IN param_cdr_route_member_id_csv VARCHAR(1024) -- csv integers
)

对于参数占位符编号3,4,5和6,我建议将int valuess的CSV格式设为varchar参数。这是因为,您希望将它们与IN一起使用一组用于搜索它们。由于我们无法将一组值作为过程参数传递,因此我们可以使用CSV格式作为替代。 由于输入采用CSV格式,因此IN不适合用于搜索 我们可以将FIND_IN_SET与CSV值一起使用。

示例 :(对于您的where子句):

where cdr_site_id = param_cdr_site_id
  AND cdr_datetime BETWEEN param_cdr_datetime_min AND param_cdr_datetime_max 
  AND FIND_IN_SET( cdr_call_class_id, param_cdr_call_class_id_csv ) 
  AND FIND_IN_SET( cdr_call_type_id, param_cdr_call_type_id_csv ) 
  AND (    FIND_IN_SET( cdr_extension_id, param_cdr_extension_id_csv ) 
        or FIND_IN_SET ( cdr_route_member_id, param_cdr_route_member_id_csv ) )

请参阅