Query ABAP internal tables using SQL

2021/02/21

Recently I discovered one feature of ABAP which I wanted to exist a long time ago.

I had a task in my project to implement OData Service. Unfortunately, I could not use CDS-View to generate OData Service, because data extraction was ABAP implemented legacy-code. I had to implement SAP Gateway Service (transaction code SEGW), then use the ABAP logic to get requested data:

DATA(lref_srv) = NEW zcl_project_name_service_class( id = CONV #( lv_id )).
DATA(lt_entityset) = lref_srv->get_data().

The client of this Gateway Service was a SAPUI5 application with diverse filter logic. The filters are somewhat combinations of other filters. They were sometimes even mutually exclusive. It would be very painful to reimplement this filter logic in Gateway Service from scratch. Fortunately, there is a way to get filters in ABAP:

DATA(lv_sql) = io_tech_request_context->get_osql_where_clause_convert( ).

This method converts input filters from url string to SQL where clause. For example, it converts ?$filter=(id eq '10001' and mandant eq '100') to ID = '10001 AND MANDANT = '100'. It is very useful if your filter has many conditions.

Now I have an internal table with all data to the given ID. But I need somehow filter this table according to filter conditions. It turned out, that you can query the internal table using SQL where clauses.

SELECT * FROM @lt_entityset as _res WHERE (lv_sql) 
 INTO CORRESPONDING FIELDS OF TABLE @et_entityset

For some reason, you have to specify an alias to the table (_res). Also, the names of columns have to match to column names in the filter from the URL. Otherwise, you’ll get a SQL exception. If it is your case you can use other cool features of the new ABAP - MOVE-CORRESPONDING(MAPPING) to create an auxiliary table with the correct column structure.

>> Home