DB2 Conditional WHERE clause

2019-07-19 19:55发布

问题:

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).



标签: sql db2