The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted.
Following is the syntax to use the DELETE statement to delete a record or line from an internal table −
DELETE TABLE <internal_table> FROM <work_area_itab>.
In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components.
You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax −
DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>………… <Kn> = <Fn>.
In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>.
Note − If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format.
REPORT ZDELETE_DEMO. DATA: BEGIN OF Line1, ColP TYPE I, ColQ TYPE I, END OF Line1. DATA mytable LIKE HASHED TABLE OF Line1 WITH UNIQUE KEY ColP. DO 8 TIMES. Line1-ColP = SY-INDEX. Line1-ColQ = SY-INDEX + 4. INSERT Line1 INTO TABLE mytable. ENDDO. Line1-ColP = 1. DELETE TABLE mytable: FROM Line1, WITH TABLE KEY ColP = 3. LOOP AT mytable INTO Line1. WRITE: / Line1-ColP, Line1-ColQ. ENDLOOP.
The above code produces the following output −
2 6 4 8 5 9 6 10 7 11 8 12
In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time.
The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12.