动态PL/SQL查询,如何忽略空参数?
我有一个带有多个参数的 PL/SQL 过程。当 web 应用程序调用该过程时,如果它不使用某个参数,它就会将 is 作为 null 传递,即
procedure test (param1 in varchar2, param2 in varchar2, param3 in varchar2, cursor out sys_refcursor)
...
end procedure test;
我想进行一个 SQL 查询,仅当参数不为 null 时,我才在 WHERE 子句中包含给定的参数。除了在字符串中构建 SQL 查询然后打开该字符串的游标之外,有没有一种方法可以以优雅的方式实现此目的,如下所示
vSQL := 'SELECT * from TABLE WHERE something = something_else';
if param1 IS NOT NULL
vSQL := vSQL || 'AND some_param = ' || param1;
I have a PL/SQL procedure with multiple parameters. When a webapp calls the procedure, if it's not using a certain parameter, it passes is as null, ie
procedure test (param1 in varchar2, param2 in varchar2, param3 in varchar2, cursor out sys_refcursor)
...
end procedure test;
I want to make an SQL query where I include the given parameters in the WHERE clause only if the parameter is not null. Is there a way to achieve this in an elegant way, other than building the SQL query in a string and then opening the cursor for that string, like this
vSQL := 'SELECT * from TABLE WHERE something = something_else';
if param1 IS NOT NULL
vSQL := vSQL || 'AND some_param = ' || param1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在 dba.stackexchange.com 上回答了类似的问题
I have answered a similar question on dba.stackexchange.com
您可以将其全部编码为一个选择
You can code it all into a single select
创建一个测试表:
创建您的过程:
然后像这样调用它:
Create a test table:
Create your procedure:
Then call it like this: