DB2 Conditional WHERE clause

邮差的信 提交于 2020-01-04 09:15:24

问题


I'm using DB2 v9

I have a stored procedure with paramaters that can potentially be passed in as empty strings. Here somer pseudocode for what I'm trying to do:

WHERE myColumn.name =
     IF param1 = '' THEN
        **disregard this param, all column values are eligible**
     ELSE
        myColumn.name = param1;

Basically just ignore the param if it is an empty string. If not, apply it as a filter in the WHERE clause. Is this possible to do in DB2?


回答1:


SELECT ...
FROM ...
WHERE  param1 = '' 
   OR  myColumn.name = param1
   ;



回答2:


The answer provided by wildplasser is correct, but there are some additional considerations that may helpful to include.

First, it might be possible that the stored procedure input parameter contains a NULL instead of ''. Using the COALESCE or NULLIF functions will cover both a NULL and any amount of empty space:

SELECT ... FROM ... WHERE COALESCE( param1, '' ) = '' OR myColumn.name = param1 ;

When that type of search query is compiled into a stored procedure, it generally helps to enable REOPT ALWAYS on the statements inside the procedure. If you don't do this, the SQL statements inside your stored procedure will always use the same access plan, regardless of which input parameters are passed into the stored procedure at runtime. Allowing the optimizer to re-evaluate each statement in the procedure at runtime will provide a much better chance of exploiting the right index when the user searches on a particular column.

CALL SYSPROC.REBIND_ROUTINE_PACKAGE 
    ('P','YOURPROCSCHEMA.YOURPROCNAME','REOPT ALWAYS') ; 



回答3:


Another Keyword here would be "Dynamic SQL". Build your queries as a string and either EXECUTE IMMEDIATE them (for UPDATE, INSERT or DDL's) or use PREPARE/OPEN/FETCH (for SELECT's).



来源:https://stackoverflow.com/questions/10214340/db2-conditional-where-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!