Form a dynamic Query in SAP ABAP

You can indeed achieve it by creating dynamic queries in SAP ABAP. Dynamic queries allow you to build SQL statements at runtime based on varying conditions. Just follow the below steps:

Steps to Create Dynamic Query

Step 1 ? Define the input parameters

DATA: table_name TYPE string VALUE 'MARA',
      column_name TYPE string VALUE 'MATNR',
      name_value TYPE string VALUE 'TEST_MATERIAL'.

Step 2 ? Create a table type to hold the output results

DATA: results TYPE REF TO data,
      table_type TYPE string.
FIELD-SYMBOLS: <results> TYPE STANDARD TABLE,
               <wa_result> TYPE any.

Step 3 ? Create a dynamic query to fill the table

" Build dynamic table type
CONCATENATE 'TABLE OF ' table_name INTO table_type.

" Create internal table dynamically
CREATE DATA results TYPE (table_type).
ASSIGN results->* TO <results>.

" Build and execute dynamic SELECT statement
SELECT * FROM (table_name)
  INTO TABLE <results>
  WHERE (column_name) = name_value.

" Process results
LOOP AT <results> INTO <wa_result>.
  " Your processing logic here
  WRITE: / 'Record found'.
ENDLOOP.

The above code demonstrates how to dynamically construct and execute a SELECT statement where the table name, column name, and search value are determined at runtime.

Key Points

When working with dynamic queries, remember to:

  • Use parentheses around dynamic elements in SQL statements
  • Create data references for dynamic table types
  • Assign field symbols to access the dynamic data
  • Handle potential runtime errors with proper exception handling

Conclusion

Dynamic queries in SAP ABAP provide flexibility to build SQL statements at runtime based on varying input parameters. This approach is particularly useful when creating generic programs that need to work with different tables and conditions.

Updated on: 2026-03-13T17:56:04+05:30

966 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements