Creating a Dynamic Where Clause

Consider a scenario where we need to fetch entries from a table checking with some of the selection screen parameters in which some are part of the key fields and some are not the key field however Index is available. 
General approach which normally followed is, keeping a check on the selection screen parameters and has the same hit to the table checking with different filter criteria.

This can be avoided through Dynamic Where clause;
  • When the requirement is to get data from same table but with different fields in the WHERE clause.
  • Other than increasing the program lines by IF….ENDIF, to hit the same table with       Different WHERE clause, we can make use of dynamic WHERE clause for a better        Alignment.

Below is a sample scenario:
   Fetch the entries from VBAP checking with selection screen parameter sales order and legacy order number with condition either one of parameter value required but not both.


DWC.png
    VBAP – VBELN is the key filed
                ZZLEGORDNUM is not Key but index is available

  DATA:
  Work Area for Dynamic WHERE Clause
   l_where_line 
TYPE edpline,

  Internal Table for Dynamic WHERE Clause
   l_where     
TYPE TABLE OF edpline

When the sales order is input for selection screen we build the where clause with sales order as shown below.
 
 IF  s_vbeln[] IS NOT INITIAL.
    CONCATENATE 'VBELN' 'IN' 'S_VBELN'
                 
 INTO l_where_line SEPARATED BY space.
    APPEND l_where_line TO l_where.
    CLEAR l_where_line.


When the legacy order is input for selection screen we build the where clause with sales order as shown below.
  ELSE.
    
CONCATENATE 'ZZLEGORDNO' 'IN' 'S_LEGORD'
                
INTO l_where_line SEPARATED BY space.
    
APPEND l_where_line TO l_where.
   
 CLEAR l_where_line.

 ENDIF.

While selecting data from the VBAP simply add the l_where in where condition of select statement.

SELECT vbeln posnr matnr
    
FROM vbap
    
INTO TABLE i_vbap
    
WHERE (l_where).
We can also use following FM to build where condition dynamically from select options.

  
CALL FUNCTION 'FREE_SELECTIONS_RANGE_2_WHERE'
    
EXPORTING 
      
field_ranges  = lt_range
    
IMPORTING 
      
where_clauses = lt_where.