SQL:取消空参数上的“where" [英] SQL: Cancel 'where' on null parameter
问题描述
这可能很明显,但我很困惑.
This may be obvious but I'm getting very confused.
我有一个带有 where 子句的 SQL 查询(其中包含参数列表).如果所有这些参数都为空,我需要 SQL 忽略 where 子句并检索所有记录.这在 SQL 中容易做到吗?我知道一种解决方法是,如果参数为空,则使用代码删除 where 子句.
I have an SQL query with a where clause (where in with a list of parameters). If all of these parameters are null, I need the SQL to ignore the where clause and retrieve all the records. Is this easy to do in SQL? I know one way around it is to just remove the where clause using code if the parameters are null.
推荐答案
你可以尝试这样做:
select *
from foo
where (@parameter1 is null AND @parameter2 is null)
OR (@parameter1 = 'value1'
AND
@parameter2 = 'value2')
当然,它需要在您自己的查询中进行一些调整,但现在您将检查参数是否为空或执行您原来的 where 子句.
Offcourse it needs a bit of tuning in your own query, but now you will check if the parameters are null or do your original where-clause.
这篇关于SQL:取消空参数上的“where"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!