Table lookup without having to deal with CX_SY_ITAB_LINE_NOT_FOUND
2020-06-15

Before the modernization of ABAP in 7.40, a table lookup required an auxiliary variable and at least 4 lines of code.
Take this pre-populated internal table:
DATA(itbl) = VALUE t_t001( ( bukrs = 'COCA' butxt = 'Coca-cola' )
( bukrs = 'PEPS' butxt = 'Pepsi' ) ).
This is what you had to do before 7.40:
DATA wa LIKE LINE OF itbl.
DATA butxt TYPE butxt.
READ TABLE itbl INTO wa WITH KEY bukrs = 'SPRI'.
IF SY-SUBRC = 0.
butxt = wa-butxt.
ENDIF.
7.40 made it more elegante. No more auxiliary variable and one line of code. Except that we have to deal with the CX_SY_ITAB_LINE_NOT_FOUND exception even in the cases (like this one) in which we don’t care about it:
TRY.
DATA(butxt) = itbl[ bukrs = 'SPRI' ]-butxt.
CATCH CX_SY_ITAB_LINE_NOT_FOUND.
CLEAR butxt.
ENDTRY.
But now I found that we can use VALUE together with OPTIONAL to help us make it truly simple:
DATA(butxt) = VALUE #( itbl[ bukrs = 'SPRI' ]-butxt OPTIONAL ).
It’s easier to read and much easier to understand. This is beautiful code.
Greetings from Abapinho.
8 de July de 2020 às 03:45 PM
Obrigado pela partilha Nuno!
Só uma questão, precisas de indicar o campo que queres ler, certo?
DATA(butxt) = VALUE #( itbl[ bukrs = ‘SPRI’ ]-butxt OPTIONAL ).
Para evitar o TRY/CATCH fazia sempre uma verificação na tabela a ver se a linha existia.
IF line_exists( itbl[ bukrs = ‘SPRI’ ] ).
DATA(lv_butxt) = itbl[ bukrs = ‘SPRI’ ]-butxt.
ENDIF.
Evita o dump mas pode comprometer a performance.
Desta maneira fica ainda mais prático.
Valeu!
10 de July de 2020 às 10:31 AM
Olá João, tens toda a razão. Não só faltava o -BUTXT em dois sítios como ainda tinha mais uns erros por distracção que também corrigi. Obrigado pelo aviso!