How to insert Data records in to Database table in SAP ABAP

With the help of ‘INSERT’ keyword, we can insert one or more records in to an internal table.

Data records can be inserted in the following two different ways:

  1. Through structure.
  2. Through Internal table.
  • Through structure.

DATA ls_contact TYPE ztt_db_table2.

ls_contact – contact_id = 104.

ls_contact – contact_name = ‘Bala’.

ls_contact – contact_address = ‘Street 55’.

The data records can be inserted in following two different ways from a structure.

  1. INSERT ztt_db_table2 FROM ls_contact.
  2. INSERT INTO ztt_db_table2 VALUES ls_contact.

Both the above INSERT operations are very much similar. If the Data records are inserted successfully, then the system field sy-subrc is set to 0. If it is not inserted successfully, then the system field sy-subrc is set to 4.

  • Through Internal table.

More than one data record can be inserted into Database table through Internal tables. If the line of record is already present in an internal table, then it results in runtime error. But this can be avoided through the keywords ACCEPTING DUPLICATE KEYS. Through the above keyword, already existing lines of record will be ignored.

If the records are inserted successfully, then the system field sy-subrc is set to 0. If the data records are not inserted successfully, then the system field sy-subrc is set 4. The system field sy-dbcnt will print out the number of records inserted in to the Database table.

DATA lt_int_table TYPE TABLE OF ztt_db_table2.

DATA ls_contact TYPE ztt_db_table2.

ls_contact -contact_id = 105.

ls_contact -contact_name = ‘Suresh’.

ls_contact -contact_address = ‘Street 88’.

APPEND ls_contact TO lt_int_table.

CLEAR ls_contact.

ls_contact -contact_id = 106.

ls_contact -contact_name = ‘Sanjay’.

ls_contact -contact_address = ‘Street 98’.

APPEND ls_contact TO lt_int_table.

INSERT INTO ztt_db_table2 FROM TABLE lt_int_table.

The Duplicate records can be ignored by using the following INSERT statement.

INSERT INTO ztt_db_table2 FROM TABLE lt_int_table ACCEPTING DUPLICATE KEYS.