Abap predefined function line_index

As part of the ABAP predefined functions series, today I wanted to talk about the predefined function  LINE_INDEX.

As the name suggests, the function returns the row index of an internal table found using table expressions.

Syntax:
  result = line_index( table_expression).

Features:

- If the row in question is not found, no exception is raised. The value 0 is returned instead.

- Supports table expression chaining as long as the result of the expression is also table-like in 
   the case of nested tables.

- Effectively, a functional replacement of READ TABLE statement followed by sy-tabix check.

Notes:

 - If a hashed table is specified then the result would be -1.
 - If a hash key is specified then the result would be -1.
 
Example:

"Procedural way
READ TABLE data TRANSPORTING NO FIELDS WITH KEY name = 'X'.
IF sy-subrc = 0.
DATA(index) = sy-tabix.
ENDIF.
"Using Line_Index.
DATA(index) = line_index( data[ name = 'X' ].

you might think that it's not that impressive as it's not that hard or frequent to know an index of the row in internal tables till you have to know the index of a deeply nested table. below is an example illustrating the same.

report sy-repid.
TYPES: tab1 TYPE TABLE OF i WITH EMPTY KEY,
tab2 TYPE TABLE OF tab1 WITH EMPTY KEY,
tab3 TYPE TABLE OF tab2 WITH EMPTY KEY.
DATA(itab) = VALUE tab3(
( VALUE tab2(
( VALUE tab1(
( 1 )
( 2 ) ) )
( VALUE tab1(
( 3 )
( 4 ) ) ) ) )
( VALUE tab2(
( VALUE tab1(
( 5 )
( 6 ) ) )
( VALUE tab1(
( 7 )
( 8 ) ) ) ) ) ).
" find index of value 5 in 2nd nested internal table(tab2) in tab3.
"procedural
READ TABLE tab3 INTO DATA( tab3_line ) INDEX 2.
IF sy-subrc = 0.
READ TABLE tab2 TRANSPORTING NO FIELDS WITH KEY table_line = 5.
IF sy-subrc = 0.
DATA(index) = sy-tabix.
ENDIF.
ENDIF.
"Using Line_index with table expressions chaining
DATA(index) = line_index( tab3[2][ KEY primary_key table_line = 5 ] ).

As always, I hope this information helps you in your day-to-day work.

Popular posts from this blog

ABAP convert internal table to excel (.xlsx) format and Send email or download

ABAP read excel(.XLSX) file to internal table in ABAP using CL_FDT_XL_SPREADSHEET

Use CL_BCS library to send email with ABAP