ABAP Quick - Compare tables
Imagine you are currently implementing an ALV with editing functions and would like to compare what has changed after editing by the user? No problem, we'll show you a quick and easy solution.
Table of contents
The scenario is relatively simple: You offer the user an ALV to edit his data. Here he can change data, record new records or maybe even delete them. If the user then click on the save button, the data must now be stored on the database and adapted.
Some rely on the method of logging each action of the user into separate tables and then simply processing them. But again there is an easier way to realize this.
Preparation
For this we want to build together a small test scenario, which you can also use with your machine. To do this, you only need to adjust the listed company codes to match which ones in your system.
" Data selection
SELECT * FROM t001
WHERE bukrs IN ('A001','A002','A003','A004','A005')
INTO TABLE @DATA(lt_old).
" Create the new table
DATA(lt_new) = lt_old.
DELETE lt_new INDEX 1.
DATA(lr_t001) = REF #( lt_new[ 1 ] ).
lr_t001->butxt = 'Some changes'.
lr_t001 = REF #( lt_new[ bukrs = 'A004' ] ).
lr_t001->ktopl = 'ABC'.
We read five entries from table T001 (company codes) that are hard coded in the select statement. Then we take the data in a new table, the old serves us later as a comparison of what has changed. Then we adapt the new table accordingly:
- Delete the first entry in the table
- Assign the new first entry and change the company code text
- Read the entry A004 and change the chart of accounts
Compare
This allows the comparison to be carried out. In the internal table lt_old are the originally selected data, in the table lt_new are the changed data that the user has adjusted. For the comparison, we simply call the following function module:
DATA:
lt_del TYPE STANDARD TABLE OF t001,
lt_add TYPE STANDARD TABLE OF t001,
lt_mod TYPE STANDARD TABLE OF t001,
ld_flag TYPE abap_bool.
" Compare the two tables
CALL FUNCTION 'CTVB_COMPARE_TABLES'
EXPORTING
table_old = lt_old
table_new = lt_new
key_length = 14
IMPORTING
table_del = lt_del
table_add = lt_add
table_mod = lt_mod
no_changes = ld_flag.
The comparison was made by the function module and we get back 3 internal tables, which we can now easily process. Thus, we have a clear representation of what has been adjusted, what data is new and what data has been deleted. The internal tables all have the same data type, so they can be used directly for customization.
Hint: The key_length field must be calculated beforehand and represents the key of the table. In this case, the length is 14 and is calculated from the fields MANDT and BUKRS (3 4), which are the key. Since we are in a Unicode system, the key must be taken times 2, since each character needs 2 digits space.
Conclusion
The comparison of two tables is easy with the right tool for you and should be no problem for you with our little tip.