Monday, 28 February 2022

Calling MS SQL Stored Procedure from ABAP

One of the few things sometime coming up in your ticket request. Calling stored procedure from ABAP to remote SQL server. 

How do we send the NULL value? It seems sending the ind_ref with -1 solve this.


TYPES: BEGIN OF ty_input,
         orderid(50),
         materialid(50),
         description(80),
         user1(50),
         user2(50),
       END OF ty_input,
       BEGIN OF ty_output,
         orderid(50),
       END OF ty_output.

DATA: ls_input          TYPE ty_input,
      ls_output         TYPE ty_output.

CONSTANTS: gc_null      TYPE int2 VALUE '-1'.

* Create db connection
DATA(lr_sql_connection) = cl_sql_connection=>get_connection( 'MSSQL' ).
DATA(lr_statement) = lr_sql_connection->create_statement( ).
DATA(lo_struct) = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( ls_input ) ).
DATA(lt_comp) = lo_struct->get_components( ).
CLEAR: ls_input.
ls_input-orderid    = 'ABC123'.
ls_input-materialid = 'MAT01'.
ls_input-description = 'Order for MAT01'.

* Input fields
LOOP AT lt_comp INTO DATA(ls_comp).
  ASSIGN COMPONENT ls_comp-name OF STRUCTURE ls_input TO FIELD-SYMBOL(<cell>).
  IF <cell> IS INITIAL.
    lr_statement->set_param( data_ref = REF #( <cell> )
                             ind_ref  = REF #( gc_null )    "Send NULL if field has no value
                             inout    = cl_sql_statement=>c_param_in ).
  ELSE.
    lr_statement->set_param( data_ref = REF #( <cell> )
                             inout    = cl_sql_statement=>c_param_in ).
  ENDIF.
ENDLOOP.
* Output fields
lr_statement->set_param( data_ref = REF #( ls_output-orderid )
                         inout    = cl_sql_statement=>c_param_out ).

TRY.
    lr_statement->execute_procedure( proc_name = 'ST_ADDORDER' ).
    WRITE: / 'OrderID: ', ls_output-orderid.
  CATCH cx_sql_exception INTO DATA(lx_00).
    DATA(lv_exception) = | An exception occurred with SQL_MESSAGE = { lx_00->sql_message }|.
    WRITE: / lv_exception.
ENDTRY.

* Close db connection
lr_sql_connection->close( ). 

TOUCHTAB report, regenerate all ABAPs related to changed/modified structure

I was working on S4HANA OnPremis and tried to do an enhancement to BP's additional info structure by appending fields, but decided that ...