动态MySQL存储过程中的子句

时间:2013-02-20 15:18:30

标签: mysql sql procedure

我有一个问题,也许它很简单(对你来说是大师)。

我将我的SQL Paging类从C#转换为MySQL存储过程。在我的C#自制对象中,查询是根据条件动态构建的。例如:

if(keywords is not null)
{ 
  whereClause += "WHERE description LIKE '%keywords%'"
}
if(price is not null)
{
  whereClause += "AND price = '%price%'"
}

...

string query = "SELECT col1, col2 FROM tblThreads " + whereClause

现在,我的问题是:我如何在MySQL中执行类似于此的动态where子句?或者更确切地说,如果他们没有为这些参数输入任何内容,我将如何告诉存储过程中的MySQL跳过这些参数? IE:

SELECT col1, col2 FROM tblThreads

如果这些参数为空,会是这样的吗?

SELECT col1, col2 FROM tblThreads WHERE (IS NULL @keywords OR description like '%@keywords%'

...

谢谢你们。

4 个答案:

答案 0 :(得分:3)

您可以使用CASE语句检查@keywords的值,例如

SELECT  col1, col2 
FROM    tblThreads 
WHERE   description LIKE  CASE WHEN @keywords IS NULL 
                            THEN description
                            ELSE CONCAT('%', @keywords, '%')
                            END
        AND
        price LIKE  CASE WHEN @price IS NULL 
                            THEN price
                            ELSE CONCAT('%', @price, '%')
                            END

答案 1 :(得分:1)

如果您允许他们查询整个数据库,最简单的方法就是在您的语句中添加1 = 1类似

whereClause = "WHERE 1 = 1"

if(keywords is not null)
{ 
 whereClause += "AND description LIKE '%keywords%'"
}
if(price is not null)
{
 whereClause += "AND price = '%price%'"
}

答案 2 :(得分:0)

SELECT col1, col2 
FROM tblThreads 
WHERE case when @keywords is not null then description like '%' + @keywords + '%' when @price is not null then price like'%' + @price + '%' end 

答案 3 :(得分:-2)

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 ;