Native SQL, ADBC and AMDP

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Most of the time an ABAP program talks to the database with ABAP SQL, the statements SELECT, INSERT, UPDATE and DELETE that look the same on every database. Sometimes that is not enough: you need a feature that only one database offers, or you want a long calculation to run inside the database next to the data instead of in your program. ABAP has three tools for this. Native SQL passes text that only the database understands straight through. ADBC is the class library that sends such text from ABAP Objects code. AMDP lets you write a database procedure or function in the language of SAP HANA, called SQLScript, as a method of an ABAP class. After reading this page you can tell the three apart, read an old EXEC SQL block, write a small AMDP method that sums the items of expense claims, and know why you should reach for them last. The page is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Native SQL and ADBC belong to classic Standard ABAP only: the ABAP Cloud edition of the Keyword Documentation has no pages for EXEC SQL or ADBC. AMDP works in Standard ABAP and, with extra rules for read access and client safety, in ABAP Cloud; it runs only on a system whose database is SAP HANA.

Before you read

Key terms

  • Native SQL: SQL text that is passed unchanged to the database and follows the rules of that database, not those of ABAP.

  • ADBC (ABAP Database Connectivity): the ABAP Objects classes and interfaces that send Native SQL to the database and read the result.

  • AMDP (ABAP Managed Database Procedures): a way to write a database procedure or function in SQLScript as a method of an ABAP class, with ABAP managing its creation and transport.

  • SQLScript: the programming language of SAP HANA for procedures and functions that run inside the database.

  • Code pushdown: moving a calculation from the ABAP program to the database, so that only the result travels back.

  • Client safety: the guarantee that an AMDP method reads data of the current client only.

Choosing the layer: where the work runs

A calculation such as "total amount per claim" can run in three places. Written as a loop in ABAP, every item row travels from the database to the application server and the program adds them up. Written as one ABAP SQL statement with an aggregate function, the database adds them up and sends back one row per claim. Written as an AMDP method, the database also runs the whole procedure, which may contain several steps. The rule of the Keyword Documentation is to use ABAP SQL for general database access where possible. Move down a layer only when the layer above cannot express what you need.

flowchart TD A[Need data from the database] --> B{Can ABAP SQL or a CDS view express it?} B -- Yes --> C[Use ABAP SQL or CDS: portable, client handling and buffering work] B -- No --> D{Is the work a read on SAP HANA that needs SQLScript?} D -- Yes --> E[AMDP method: SQLScript runs inside HANA, allowed in ABAP Cloud as read-only] D -- No --> F[Native SQL through ADBC: Standard ABAP only, you handle the client]

The aggregate case is the one the next example shows. It sums the items of each claim with ABAP SQL alone, which is what you should write first. It requires an SAP system; not run here, because it reads a database table of the running example.

SELECT claim_id, SUM( amount ) AS total
  FROM zexp_item
  GROUP BY claim_id
  ORDER BY claim_id
  INTO TABLE @DATA(totals).

What Native SQL is and what it changes

The Keyword Documentation defines Native SQL as all platform-dependent statements and calls that are passed to the Native SQL interface of the database interface. By default it uses the standard connection, which leads to the ABAP database schema of the standard database of the application server. Native SQL reaches the database in two ways: as strings passed to objects of the ADBC classes, and as statements embedded between EXEC SQL and ENDEXEC.

Native SQL gives up several things that ABAP SQL does for you, and each is a way to make a mistake.

  • No implicit client handling. A client-dependent table holds the rows of every client. ABAP SQL adds the current client to every statement; Native SQL does not, so you name the client yourself and must use only the current client.

  • No table buffering. Native SQL reads and writes go straight to the database and bypass the buffer.

  • Column order. The columns of a table in the database may be in a different order than in the ABAP Dictionary. ABAP SQL respects the Dictionary order; with Native SQL you must respect the database order yourself.

  • Types. Not every ABAP type has a matching type in the database, so the ABAP types of the data you pass in and read out should match the database types, or conversions that depend on the platform happen and can raise exceptions.

  • Different behaviour per database. Handling of blanks in strings, rounding and overflow can differ from ABAP SQL and from one database to another, and the examples in the documentation are tested on SAP HANA.

EXEC SQL, the legacy form

EXEC SQL opens an area in the program that holds one or more Native SQL statements, and ENDEXEC closes it. What is written between them is not checked completely by the ABAP syntax check, because it follows the rules of the database, including the rules for upper and lower case of object names. A few SAP-specific elements may appear there as well, for example host variables, which are ABAP variables whose names start with a colon so that the value is passed to the statement. ENDEXEC sets sy-subrc to 0 when the statements ran and to 4 when they did not, and sy-dbcnt to the number of rows processed by the last statement.

The sketch below changes the category of claim items. The client column of the table is named in the statement and set to the current client, because Native SQL does not do it for you. It assumes that ZEXP_ITEM has a client column named MANDT. It requires an SAP system; not run here.

EXEC SQL.
  UPDATE zexp_item SET category = 'MEALS'
   WHERE mandt = :sy-mandt AND category = 'FOOD'
ENDEXEC.

The Keyword Documentation says that the static embedding between EXEC SQL and ENDEXEC is still supported but should no longer be used in new programs, and that new features of the Native SQL interface are developed only for ADBC. You need to read EXEC SQL because old programs are full of it, and you should replace it with ADBC when you change them.

ADBC: Native SQL from ABAP Objects

ADBC is an API for the Native SQL interface that is based on interfaces and classes in ABAP Objects. Its interfaces start with the prefix IF_SQL_ and its exception class is CX_SQL_EXCEPTION. Unlike EXEC SQL, ADBC treats the statement as an ordinary string, so it can be built at runtime, and a failure is an exception that you catch with TRY and CATCH.

The simplest form sends one statement. The Keyword Documentation shows the replacement of an EXEC SQL insert by a single call of the class CL_SQL_STATEMENT, created with NEW and run with execute_update. The following sketch adapts it to the update of the previous section. It requires an SAP system; not run here.

TRY.
    NEW cl_sql_statement( )->execute_update(
      |UPDATE zexp_item SET category = 'MEALS' | &&
      |WHERE mandt = '{ sy-mandt }' AND category = 'FOOD'| ).
  CATCH cx_sql_exception INTO DATA(sql_error).
    " report sql_error->get_text( ) and stop; nothing was changed
ENDTRY.

Putting a value into the text with { ... } is acceptable only for a value the program owns, such as sy-mandt. A value that comes from a user must never be glued into the statement, because it can change the meaning of the statement; this is an SQL injection. The documented ADBC interfaces take such values through the placeholder ?, to which an ABAP data object is bound before the statement runs. The next listing reads the total per claim for the current client that way. It follows the documented pattern: a connection from the builder CL_SQL_ADBC_CONNECTION_BUILDER, a statement built from its parts, one bound parameter for the client, a result set read row by row, and an explicit close. The row structure must match the types of the database columns, so adjust the type of total to your table. It requires an SAP system; not run here.

TYPES: BEGIN OF ty_row,
         claim_id TYPE c LENGTH 10,
         total    TYPE p LENGTH 16 DECIMALS 2, " must match the database type of the sum
       END OF ty_row.
DATA row TYPE ty_row.

TRY.
    FINAL(connection) = cl_sql_adbc_connection_builder=>default( )->get( ).
    DATA(builder) = connection->build_new_statement( ).
    builder->sequence(
      |select "CLAIM_ID", sum( "AMOUNT" ) as "TOTAL" from | )->table( |ZEXP_ITEM|
      )->sequence( |where "MANDT" = ? group by "CLAIM_ID" order by "CLAIM_ID"| ).
    DATA(query) = builder->create_regular( )->query( ).
    query->add_input_param_by_elementary( NEW symandt( sy-mandt ) ).
    DATA(result_set) = query->execute_and_get_result_set( ).
    result_set->set_output_params_by_struct( REF #( row ) ).
    WHILE result_set->next_and_get_rows_processed( ) > 0.
      WRITE / |{ row-claim_id } { row-total }|.
    ENDWHILE.
    result_set->close( ).
  CATCH cx_sql_exception INTO DATA(sql_error).
    WRITE / sql_error->get_text( ).
ENDTRY.

The documentation adds three rules that this listing follows. An open result set holds an open database cursor, so close it with close. Parameterise with ? instead of concatenating text. And ADBC, like all Native SQL, gives no implicit client handling, so the client is an explicit condition of the statement. ADBC also covers insert, update, delete, DDL statements, prepared statements and several result sets; the Keyword Documentation lists the interfaces for each.

The same sum written in plain ABAP

Before the AMDP example, here is the calculation it replaces, written as a loop in ABAP. It reads no database: the items are a table in memory, a stand-in for the rows a program would read from ZEXP_ITEM. Each item either adds its amount to the total of its claim, found with READ TABLE through a field symbol, or inserts a new total row. This listing runs in the local playground and prints C-1001 215.50 and C-1002 60.00.

REPORT zexp_sum_demo.

TYPES: BEGIN OF ty_item,
         claim_id TYPE c LENGTH 10,
         item_no  TYPE i,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item.
TYPES ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

TYPES: BEGIN OF ty_total,
         claim_id TYPE c LENGTH 10,
         total    TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_total.
TYPES ty_totals TYPE SORTED TABLE OF ty_total WITH UNIQUE KEY claim_id.

DATA(items) = VALUE ty_items(
  ( claim_id = 'C-1001' item_no = 1 amount = '120.50' )
  ( claim_id = 'C-1001' item_no = 2 amount = '35.00' )
  ( claim_id = 'C-1002' item_no = 1 amount = '60.00' )
  ( claim_id = 'C-1001' item_no = 3 amount = '60.00' ) ).

DATA totals TYPE ty_totals.

LOOP AT items INTO DATA(item).
  READ TABLE totals ASSIGNING FIELD-SYMBOL(<total>) WITH TABLE KEY claim_id = item-claim_id.
  IF sy-subrc = 0.
    <total>-total = <total>-total + item-amount.
  ELSE.
    INSERT VALUE #( claim_id = item-claim_id total = item-amount ) INTO TABLE totals.
  ENDIF.
ENDLOOP.

LOOP AT totals INTO DATA(total).
  WRITE / |{ total-claim_id } { total-total }|.
ENDLOOP.

With real data this loop moves every item row to the application server. The AMDP method below does the same adding inside the database.

AMDP: database procedures written in an ABAP class

ABAP Managed Database Procedures are a framework for managing and calling database procedures and database functions in AS ABAP. You write the procedure in the language of the database, today SQLScript for SAP HANA, as a method of a class. ABAP then creates the procedure in the database for you, keeps it with the class when the class is transported, and calls it like any other method. You do not need a separate database user. The Keyword Documentation notes that currently AMDP supports only SAP HANA, although it is designed so that other databases could be added.

The AMDP class

An AMDP class is a global class that implements the tag interface IF_AMDP_MARKER_HDB. The suffix _HDB stands for the SAP HANA database. A tag interface has no methods; it only marks the class. An AMDP class may contain regular methods and AMDP methods side by side. There are two kinds of AMDP method: a method without a return value defines a database procedure, and a method with a return value defines a database function.

An AMDP procedure that sums claims

The declaration of a procedure looks like that of an ordinary method, with two rules. Its parameters are passed by value (VALUE), and it has no RETURNING parameter. In the implementation the addition BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT says that the body is SQLScript, and USING lists every database object the body reads, so that the syntax check and the framework know them. The body is not ABAP: parameters are written with a colon where SQLScript needs it, an output parameter is filled with an assignment, and the statement ends with a semicolon.

The declaration below also says AMDP OPTIONS READ-ONLY CDS SESSION CLIENT DEPENDENT. In ABAP Cloud the first part, which restricts the method to reading, is required, and so is one of the two client options; the second part used here makes the method client safe, as the next section explains. This class requires an SAP system on SAP HANA; not run here.

CLASS zcl_exp_claim_totals DEFINITION PUBLIC FINAL CREATE PUBLIC.
  PUBLIC SECTION.
    INTERFACES if_amdp_marker_hdb.

    TYPES: BEGIN OF ty_total,
             claim_id TYPE zexp_item-claim_id,
             total    TYPE zexp_item-amount,
           END OF ty_total.
    TYPES ty_totals TYPE STANDARD TABLE OF ty_total WITH EMPTY KEY.

    METHODS get_totals
      AMDP OPTIONS READ-ONLY CDS SESSION CLIENT DEPENDENT
      EXPORTING VALUE(totals) TYPE ty_totals.
ENDCLASS.

CLASS zcl_exp_claim_totals IMPLEMENTATION.
  METHOD get_totals BY DATABASE PROCEDURE FOR HDB
                    LANGUAGE SQLSCRIPT
                    USING zexp_item.
    totals = SELECT claim_id, SUM( amount ) AS total
               FROM zexp_item
              GROUP BY claim_id
              ORDER BY claim_id;
  ENDMETHOD.
ENDCLASS.

Calling it is the same as calling any method. The framework creates the database procedure the first time the method is used (or updates an existing one), the call runs in the database, and the table comes back through the output parameter. The example calls the method with the expression NEW. If the standard database is not SAP HANA, the call ends in a runtime error. It requires an SAP system on SAP HANA; not run here.

DATA totals TYPE zcl_exp_claim_totals=>ty_totals.
NEW zcl_exp_claim_totals( )->get_totals( IMPORTING totals = totals ).

The sequence below shows what happens from the first call to the result.

sequenceDiagram participant P as ABAP program participant F as AMDP framework participant H as SAP HANA P->>F: get_totals( ) F->>H: create or update procedure ZCL_EXP_CLAIM_TOTALS=>GET_TOTALS (first use only) F->>H: run the procedure with the current client H->>H: SQLScript sums ZEXP_ITEM per claim H-->>F: result table F-->>P: totals

The Keyword Documentation is candid about the example it uses for a similar read of a table: the same function can be reached with the same efficiency in ABAP SQL, and AMDP is not needed in simple cases. Our sum is also simple enough for the single ABAP SQL statement shown earlier. An AMDP method pays off when the work has several steps that are easier to write in SQLScript, such as intermediate tables, or when the same logic is also needed inside a CDS table function.

Restrictions and client safety

An AMDP method is not an ordinary method, and the Keyword Documentation lists what it may not do.

  • Interface. Parameters are passed by value. Only elementary types and table types whose rows have only elementary components are allowed. Only input parameters can be optional, and an optional elementary input parameter needs a replacement value declared with DEFAULT.

  • No changes to the database structure or transactions. No DDL statements, no COMMIT and no ROLLBACK in the body. The ABAP program controls the logical unit of work (LUW), so the data stays consistent across procedures.

  • No writes to buffered tables. SQLScript access ignores the buffer synchronisation, so writing to a table with table buffering switched on is not allowed.

  • No constructors. A constructor cannot be an AMDP method.

  • Table buffering is bypassed. The same is true of Native SQL generally.

In the language version ABAP for Cloud Development the following apply as well.

  • The method must be restricted to reads with AMDP OPTIONS READ-ONLY in the declaration or OPTIONS READ-ONLY in the implementation (at least once).

  • The implementation must be SQLScript, and every object it uses must be released for ABAP Cloud.

  • The method must be client safe.

  • CDS entities in the USING list are named by their CDS name.

Client safety needs a short explanation. ABAP SQL adds the current client to every statement. Native SQL, and therefore AMDP, does not: the AMDP framework adds no client condition to your SQLScript. So the method is declared with one of two options, and the framework then checks that the objects in the USING list cannot return rows of another client. CDS SESSION CLIENT DEPENDENT declares the method client dependent. The framework sets the HANA session variable CDS_CLIENT to the current client, and client-dependent sources in the USING list are filtered by it; for a client-dependent database table the framework reads an implicitly created view with that filter instead of the table. CLIENT INDEPENDENT declares a method that uses only client-independent objects. Our example uses the first option, which is why zexp_item can appear in USING and the SQLScript has no client condition of its own. The SQLScript must not call procedures that AMDP does not manage and must not use built-in functions with an explicit client parameter, such as CONVERT_CURRENCY.

Functions and CDS table functions

A method with a return value is an AMDP function, implemented with BY DATABASE FUNCTION. A scalar function returns one elementary value and can be called in ABAP like a functional method. A table function returns a table. One that serves only other AMDP methods cannot be called from ABAP, because its result cannot be restricted with a WHERE condition.

The useful variant for ABAP is the AMDP function that implements a CDS table function. A CDS table function is a CDS entity, declared in a data definition with DEFINE TABLE FUNCTION, whose content is computed by an AMDP function. You read it like any other CDS entity: as the source of an ABAP SQL SELECT or of a CDS view entity. Its parameters and columns are given in the CDS definition, and the AMDP method has no parameter interface of its own. It is declared with CLASS-METHODS ... FOR TABLE FUNCTION in the public section of the class, and the CDS definition names the method after IMPLEMENTED BY METHOD. In ABAP Cloud a client-dependent table function carries the annotations @ClientHandling.type: #CLIENT_DEPENDENT and @ClientHandling.algorithm: #SESSION_VARIABLE, and a client column. The sketch below turns the sum into a table function. It requires an SAP system on SAP HANA; not run here.

@AccessControl.authorizationCheck: #NOT_ALLOWED
@ClientHandling.type: #CLIENT_DEPENDENT
@ClientHandling.algorithm: #SESSION_VARIABLE
define table function ZEXP_CLAIM_TOTALS_TF
returns
{
  client   : abap.clnt;
  claim_id : abap.char(10);
  total    : abap.curr(15,2);
}
implemented by method zcl_exp_claim_totals_tf=>get_totals;
CLASS zcl_exp_claim_totals_tf DEFINITION PUBLIC FINAL CREATE PUBLIC.
  PUBLIC SECTION.
    INTERFACES if_amdp_marker_hdb.
    CLASS-METHODS get_totals FOR TABLE FUNCTION zexp_claim_totals_tf.
ENDCLASS.

CLASS zcl_exp_claim_totals_tf IMPLEMENTATION.
  METHOD get_totals BY DATABASE FUNCTION FOR HDB
                    LANGUAGE SQLSCRIPT
                    OPTIONS READ-ONLY
                    USING zexp_item.
    RETURN SELECT mandt AS client, claim_id, SUM( amount ) AS total
             FROM zexp_item
            GROUP BY mandt, claim_id;
  ENDMETHOD.
ENDCLASS.

Once both objects are active, SELECT * FROM zexp_claim_totals_tf INTO TABLE @DATA(t). reads the sums. The Keyword Documentation advises checking, in a program that must also run on other databases, whether the system supports AMDP and CDS table functions with cl_abap_dbfeatures=>use_features before relying on them, and it marks such a SELECT with the pseudo comment for the database feature mode.

Security: SQL injection

SQLScript has dynamic statements such as EXEC and EXECUTE IMMEDIATE, and the Keyword Documentation strongly discourages them. The reason is that the content of an AMDP method is managed by ABAP but its safety is not ABAP’s responsibility, and ABAP test tools do not check the SQLScript. The documentation’s own example builds an UPDATE statement by joining a string with an input parameter. A caller could then pass 2, seatsmax = seatsmax + 10 and change a second column. Check or escape every value that comes from outside before it reaches such a method, for example with the class CL_ABAP_DYN_PRG, or better, do not build statements from parameters at all. The same advice applies to ADBC, as the previous section showed.

Where older material is out of date

Books and articles from the first years of SAP HANA, such as the 2014 first edition of the SAP Press book on ABAP development for SAP HANA and the 2002 book on ABAP Objects listed in the bibliography, predate several things this page describes. Keep these points in mind when you read them.

  • EXEC SQL was once the normal way to reach Native SQL. The current documentation says it should no longer be used in new programs and that new Native SQL features appear only in ADBC.

  • Text written before ABAP for Cloud Development knows no READ-ONLY rule and no client safety rule for AMDP, so its examples may fail the syntax check in an ABAP Cloud project.

  • Database procedure proxies with CALL DATABASE PROCEDURE were the way to call an existing procedure. An AMDP method replaces them, either by implementing the procedure in the method or by calling an existing one. The documentation still recommends proxies only for secondary database connections.

  • The advice to push work down by writing native SQL or procedures first is outdated. The current order is ABAP SQL first, then CDS, then AMDP, and Native SQL last.

Summary

  • Native SQL is database-specific SQL passed through unchanged. It gives no implicit client handling, bypasses table buffering and can behave differently per database, so use ABAP SQL whenever it can express the task.

  • EXEC SQL and ENDEXEC are the old static form and are not for new programs. ADBC is the replacement: send the statement through the IF_SQL_ interfaces or CL_SQL_STATEMENT, bind values with ?, close result sets and catch CX_SQL_EXCEPTION. Both belong to Standard ABAP and are absent from ABAP Cloud.

  • AMDP puts SQLScript for SAP HANA into a method of a class that implements IF_AMDP_MARKER_HDB. A procedure uses BY DATABASE PROCEDURE and has no RETURNING; a function uses BY DATABASE FUNCTION; a CDS table function is implemented by an AMDP function.

  • In ABAP Cloud an AMDP method must be read-only and client safe, written in SQLScript, and may use only released objects.

  • AMDP and Native SQL are the last layer of code pushdown: try ABAP SQL, then CDS, then AMDP.