简体   繁体   English

如何根据mysql中存储过程中的参数创建动态where条件?

[英]How to create dynamic where conditions according to the parameter in stored procedure in mysql?

I have created a stored procedure in which I want to list employees according to the parameter. 我创建了一个存储过程,其中要根据该参数列出员工。 The procedure has some parameters, one of them I want to use for the type(eg:branch, department etc) and the other is the id corresponding to that. 该过程具有一些参数,其中一个我想用于类型(例如:分支,部门等),另一个是与之相对应的id。

I want to create where conditions to variable. 我想创建条件变量。

How can I do that? 我怎样才能做到这一点?

DELIMITER $$

CREATE PROCEDURE Emp_details(IN div_type VARCHAR(100), IN id INT, OUT emp_name VARCHAR(100)) 
BEGIN 

        DECLARE cond VARCHAR(100);

        IF div_type = 'branch' THEN
            SET cond = 'branch_id='+id;
        ELSEIF div_type = 'department' THEN
            SET cond = 'department_id='+id;
        ELSEIF div_type = 'emp' THEN
            SET cond = 'employee_master_id='+id;
        ELSE
            SET cond = '';
        END IF;                                                                                    


        SELECT
         emp_fullname INTO emp_name
            FROM armr_employee_master
        WHERE +cond ;



END$$

Just turn the IF into a WHERE : 只需将IF转到WHERE

SELECT emp_fullname
INTO emp_name
FROM armr_employee_master
WHERE id = CASE div_type
    WHEN 'branch' THEN branch_id
    WHEN 'department' THEN department_id
    WHEN 'emp' THEN employee_master_id
END

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

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