Running ABAP queries with dynamic WHERE clause - UPDATED 2
2 minute read
Here comes a short and simple example for ABAP Programming. Suppose you want to make some more flexible function module for searching data in database table, that depending on parameters that are passed (can be optional), forms the WHERE clause of select statement. In ABAP this is pretty straight forward:
FUNCTION zsfli_sflight_getlist.
*"----------------------------------------------------------------------
*"*"Local Interface:
*" IMPORTING
*" VALUE(P_CARRID) TYPE ZSFLIGHT-CARRID OPTIONAL
*" VALUE(P_CONNID) TYPE ZSFLIGHT-CONNID OPTIONAL
*" VALUE(P_FLDATE) TYPE ZSFLIGHT-FLDATE OPTIONAL
*" TABLES
*" FLIGHT_DATA STRUCTURE ZSFLIGHT
*" RETURN STRUCTURE BAPIRET2
*"----------------------------------------------------------------------
DATA l_where(100) OCCURS 0 WITH HEADER LINE.
IF p_carrid IS NOT INITIAL.
APPEND 'carrid = p_carrid' TO l_where.
ENDIF.
IF p_connid IS NOT INITIAL.
IF l_where IS INITIAL.
APPEND ' and ' TO l_where.
ENDIF.
APPEND 'connid = p_connid' TO l_where.
ENDIF.
IF p_fldate IS NOT INITIAL.
IF l_where IS INITIAL.
APPEND ' and ' TO l_where.
ENDIF.
APPEND 'fldate = p_fldate' TO l_where.
ENDIF.
SELECT * FROM sflight INTO CORRESPONDING FIELDS OF TABLE flight_data
WHERE (l_where).
ENDFUNCTION.
In this way you can call function zsfli_sflight_getlist
only with parameter p_fldate
set, the select will filter and return all records for desired date.
~Enjoy
UPDATE2: I have added additional check for checking if there are already added WHERE
conditions, so that we can combine several conditions at once:
IF l_where IS NOT INITIAL.
APPEND ' and ' TO l_where.
ENDIF.
Posted:
Posted By:
Nick Penkov