我有一个问题,也许它很简单(对您来说,古鲁斯)。
我正在将我的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%'
??
谢谢你们。
如果允许他们查询整个数据库,最简单的方法是在语句中添加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%'"
}
您可以使用CASE
语句检查@keywords
的值,例如
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
DELIMITER $$