How to use MODIFY to modify or insert records in Database table in SAP ABAP

Using the MODIFY statement, we can modify the existing records in a Database table. If the records does not exist in a Database table, then it can insert records in to Database table. This can be achieved in the following two ways.

  1. Through Structure.
  2. Through Internal table.
  • Structure

It is used to modify a single line of record in a Database table. If the line does not exist in the Database table, then a new line will be inserted to the Database table. The contents of the structure must always follow the primary key values. If the component values of the structure is exactly similar to line of record in the Database table, then there will be no changes after the execution of this query. The structure is specified after the ‘FROM’ keyword. It is always recommended to define the structure of type (DB table) like below

Syntax: MODIFY DB_TABLE FROM structure

              DATA ls_contact TYPE ztt_db_table2.

              ls_contact – contact_id = 104.

              ls_contact – contact_name = ‘Sanjay’.

              ls_contact – contact_id = ‘Street 88’.

              MODIFY ztt_db_Table2 FROM ls_contact.

If the contact_id = 104 does not exist, then a new line of record will be inserted into the Database table ztt_db_table2.

If anyone line of record is changed or inserted, then the system field sy-subrc will be set to 0. Otherwise, it will be set to 4.

If some of the components of the structure are not mentioned, then initial values will be set to those fields in the Database table. For example, contact_age is not mentioned in the structure, therefore it will hold initial values in the Database table.

  • Through Internal table:

More than one line of record can be modified or inserted using this option. It is done through the following syntax.

Syntax: MODIFY DB_table FROM lt_int_tab.

DATA ls_contact TYPE ztt_db_table2.

DATA lt_contact TYPE TABLE OF ztt_db_table2.

ls_contact-contact_id = 101.

ls_contact-contact_name = ‘Mahesh’.

ls_contact-contact_address = ‘Street 10’.

APPEND ls_contact TO lt_contact.

ls_contact-contact_id = 110.

ls_contact-contact_name = ‘Andreas’.

ls_contact-contact_address = ‘Street 55’.

APPEND ls_contact TO lt_contact.

MODIFY ztt_db_table2 FROM TABLE lt_contact.

The line of record with contact_id = 101 will be modified in the Database table, as the line already exists. The line of record with contact_id = 110 will be inserted in the Database table, as the line of record does not exists.

If anyone of the operation, that is either modifying or inserting is successful, then the system field sy-subrc is set to 0. The system field sy-dbcnt will print out the lines of record which are changed.