【问题标题】:i want to make MySQL stored procedure with dynamic clause where [closed]我想用动态子句制作 MySQL 存储过程 where [关闭]
【发布时间】:2020-04-07 23:45:31
【问题描述】:
DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Name4`(
    IN a int(255),
    IN b int(255),
    IN dept_id_in int(255)
)
BEGIN
    SELECT
        emp.emp_id, emp.emp_name,
        emp.emp_job, 
        emp.dept, 
        emp.percent_doctor,
        emp.percent_center,
        patient_exam.exam_id,
        patient_exam.p_id,
        ABS(SUM(patient_exam.exam_price)) as SUM_price,
        ABS((SUM(patient_exam.exam_price)*  emp.percent_center )/100   ) as total_doc,
        ABS((SUM(patient_exam.exam_price)*  emp.percent_doctor )/100   ) as total_center
    FROM emp
    LEFT JOIN patient_exam on emp.emp_id = patient_exam.doctor
    WHERE 
        emp.emp_is_delete = 0 
        and patient_exam.ex_is_delete = 0 
        and 1=1 
        CASE 
            WHEN dept_id_in IS not NULL 
            THEN and patient_exam.dept_id=dept_id_in
        END                         
    GROUP BY emp.emp_id, patient_exam.exam_id 
    ORDER BY emp.emp_id, patient_exam.exam_id DESC 
    LIMIT a,b;
END$$

DELIMITER ;

【问题讨论】:

标签: mysql sql stored-procedures where-clause


【解决方案1】:

我怀疑你想要一些布尔逻辑而不是 case 表达式:

WHERE 
    emp.emp_is_delete = 0 
    AND patient_exam.ex_is_delete = 0 
    AND (dept_id_in IS NULL OR patient_exam.dept_id = dept_id_in)

你也可以用COALESCE()来表达:

WHERE 
    emp.emp_is_delete = 0 
    AND patient_exam.ex_is_delete = 0 
    AND patient_exam.dept_id = COALESCE(dept_id_in, patient_exam.dept_id)

【讨论】:

    猜你喜欢
    • 2013-02-05
    • 2011-02-08
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多