Oracle PL\SQL 空输入参数 WHERE 条件
截至目前,我正在使用 IF ELSE 来处理这种情况,
IF INPUT_PARAM IS NOT NULL
SELECT ... FROM SOMETABLE WHERE COLUMN = INPUT_PARAM
ELSE
SELECT ... FROM SOMETABLE
有没有更好的方法可以在没有 IF ELSE 循环的单个查询中执行此操作。随着查询变得复杂,将会有更多这样的输入参数,并且所需的 IF ELSE 数量会太多。
As of now I am using IF ELSE to handle this condition
IF INPUT_PARAM IS NOT NULL
SELECT ... FROM SOMETABLE WHERE COLUMN = INPUT_PARAM
ELSE
SELECT ... FROM SOMETABLE
Is there any better way to do this in a single query without IF ELSE loops. As the query gets complex there will be more input parameters like this and the amount of IF ELSE required would be too much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是使用
There's 的变体,但是这里有两个陷阱:
如果列可为空,则此子句将过滤空值,而在您的问题中,在第二种情况下您不会过滤空值。您可以修改此子句以将空值考虑在内,但它会变得很难看:
当然,如果以某种方式插入了
impossible_value
,您将遇到其他类型的(有趣)问题。这就是为什么当有很多参数时(例如大表单中的多个搜索字段),我喜欢使用动态 SQL:
您还可以使用 EXECUTE IMMEDIATE l_query INTO l_result USING param1;
One method would be to use a variant of
There are two pitfalls here however:
if the column is nullable, this clause will filter null values whereas in your question you would not filter the null values in the second case. You could modify this clause to take nulls into account but it turns ugly:
Of course if somehow the
impossible_value
is ever inserted you will run into some other kind of (fun) problems.nvl
, you will get full scan even if perfectly valid indexes are present.This is why when there are lots of parameters (several search fields in a big form for example), I like to use dynamic SQL:
You can also use
EXECUTE IMMEDIATE l_query INTO l_result USING param1;
这应该有效
This should work