🚀PROMO #PLANCARRERA2024 - 🔥Bonificaciones, Precios Congelados y Cuotas

 X 

✒️ABAP Las tablas internas

ABAP Las tablas internas

ABAP Las tablas internas

Internal Tables

Internal tables are data objects that allow storing large amounts of records with the same structure in memory, from 0 to n records. The maximum limit is related to the limits specified in the SAP installation. They exist only at runtime. In other languages, this concept of internal table is known as an array, vector, list, or collection. Typical uses:

  • Temporarily storing data from database tables for future processing.
  • Structuring and formatting data to be displayed as program output.
  • Formatting data for use by other services.

Internal Tables Declaration

To work with an internal table, we need a structure or work area or header of the internal table, which has the same format as the internal table and allows us to:

  • Read the content of a record
  • Traverse each record.
  • Add a record
  • Modify the content of a record.
  • This structure can only store 1 record of data.

Ways to declare an internal table:

  • 1. The most efficient way is to use TYPES, where we first declare a data type (ty_suppliers) and then declare the internal table (ti_suppliers) of that data type using the statement TYPE STANDARD TABLE OF. Finally, we declare the structure or work area (wa_suppliers) that allows us to work with the internal table using the statement LIKE LINE OF.

TYPES: BEGIN OF ty_suppliers,
dni(8) TYPE c,
name(30) TYPE c,
END OF ty_suppliers.

DATA: ti_suppliers TYPE STANDARD TABLE OF ty_suppliers,
wa_suppliers LIKE LINE OF ti_suppliers.

  • 2. A second way to declare the internal table (ti_suppliers) is by using the OCCURS 0 statement, and to declare the structure or work area (wa_suppliers), we use the LIKE LINE OF statement.

DATA: BEGIN OF ti_suppliers OCCURS 0,
dni(8) TYPE c,
name(30) TYPE c,
END OF ti_suppliers.

DATA: wa_suppliers LIKE LINE OF ti_suppliers.

  • 3. A third way to declare an internal table is to first declare the structure (wa_suppliers) and then declare the internal table (ti_suppliers) of the same data type as the previously declared structure.

DATA: BEGIN OF wa_suppliers,
dni(8) TYPE c,
name(30) TYPE c,
END OF wa_suppliers.

DATA: ti_suppliers LIKE STANDARD TABLE OF wa_suppliers.

  • 4. A fourth way to declare the internal table (TI_STRUCTURE) is to declare it of the same type as an existing database table in the ABAP data dictionary.

"LFA1 is a master table of suppliers
DATA: lt_supplier_data TYPE TABLE OF lfa1,
ls_supplier_data LIKE LINE OF lt_supplier_data.

SELECT * FROM lfa1 INTO TABLE lt_supplier_data.

LOOP AT lt_supplier_data INTO ls_supplier_data.
" Your processing logic here, for example:
WRITE:/ ls_supplier_data-lifnr, ls_supplier_data-name1, ls_supplier_data-city.
ENDLOOP.

  • 5. Declaring the structure or work area or header of an internal table using the same internal table as the header.

DATA: ti_suppliers LIKE TABLE OF lfa1 WITH HEADER LINE.

Adding Content to Internal Tables

  • Perform a select and store the result in the internal table.
  • Use INSERT to insert records into the internal table.
  • Add records with APPEND TO.

Types of Internal Tables

  • AnyTables: Please note that the ANY TABLE type should be used cautiously, as it sacrifices the benefits of strong typing. It seems there is a limitation in the ABAP runtime, and the ANY TABLE type might not be supported in certain scenarios.

DATA: lt_any TYPE ANY TABLE,
ls_any TYPE string.

APPEND 'Item 1' TO lt_any.
APPEND 'Item 2' TO lt_any.

LOOP AT lt_any INTO ls_any.
WRITE:/ ls_any.
ENDLOOP.

  • IndexTable

TYPES: BEGIN OF ty_index,
table_key TYPE string,
value TYPE string,
END OF ty_index.

DATA: lt_index TYPE TABLE OF ty_index WITH NON-UNIQUE KEY table_key,
ls_index TYPE ty_index.

APPEND VALUE #( table_key = 'Key1' value = 'Item 1' ) TO lt_index.
APPEND VALUE #( table_key = 'Key2' value = 'Item 2' ) TO lt_index.

READ TABLE lt_index INTO ls_index WITH KEY table_key = 'Key1'.
IF sy-subrc EQ 0.
WRITE:/ 'Item found:', ls_index-value.
ELSE.
WRITE:/ 'Item not found.'.
ENDIF.

  • Standard Table (Most used)

DATA: lt_standard TYPE TABLE OF string,
ls_standard TYPE string.

APPEND 'Item 1' TO lt_standard.
APPEND 'Item 2' TO lt_standard.

LOOP AT lt_standard INTO ls_standard.
WRITE:/ ls_standard.
ENDLOOP.

  • Sorted Table

TYPES: BEGIN OF ty_sorted,
table_key TYPE string,
value TYPE string,
END OF ty_sorted.

DATA: lt_sorted TYPE TABLE OF ty_sorted WITH NON-UNIQUE SORTED KEY table_key COMPONENTS value.

APPEND VALUE #( table_key = 'Key2' value = 'Item 2' ) TO lt_sorted.
APPEND VALUE #( table_key = 'Key1' value = 'Item 1' ) TO lt_sorted.

LOOP AT lt_sorted INTO DATA(ls_sorted).
WRITE:/ ls_sorted-value.
ENDLOOP.

  • Hashed Table

TYPES: BEGIN OF ty_hashed,
table_key TYPE string,
value TYPE string,
END OF ty_hashed.

DATA: lt_hashed TYPE HASHED TABLE OF ty_hashed WITH UNIQUE KEY table_key,
ls_hashed TYPE ty_hashed.

INSERT VALUE #( table_key = 'Key1' value = 'Item 1' ) INTO TABLE lt_hashed.
INSERT VALUE #( table_key = 'Key2' value = 'Item 2' ) INTO TABLE lt_hashed.

READ TABLE lt_hashed INTO ls_hashed WITH KEY table_key = 'Key1'.

IF sy-subrc EQ 0.
WRITE:/ 'Item found:', ls_hashed-value.
ELSE.
WRITE:/ 'Item not found.'.
ENDIF.

Internal Tables Sorting

Use the SORT statement to sort by any field that is part of the internal table, in ascending (ASCENDING) or descending (DESCENDING) order.

SORT ti_suppliers BY dni DESCENDING.

Internal Tables Iteration

To traverse an internal table and process its content record by record, use the LOOP-ENDLOOP statement. You can restrict the records you want to traverse based on a condition specified using the WHERE statement. If no record meets the specified condition in the WHERE clause, SY-SUBRC will be different from zero. More than one condition can be specified with AND or OR concatenation.

  • With LOOP - ENDLOOP:

LOOP AT it_suppliers INTO wa_suppliers.
WRITE:/ wa_suppliers-dni,
wa_suppliers-name,
wa_suppliers-surname.
ENDLOOP.

  • You can restrict records with the WHERE clause:

LOOP AT ti_suppliers INTO wa_suppliers WHERE NOT name IS INITIAL.
WRITE:/ wa_suppliers-dni,
wa_suppliers-name,
wa_suppliers-surname.
ENDLOOP.

Reading values from an Internal Table

  • To read an internal table without traversing it record by record, use the READ TABLE statement. The work area is needed.

READ TABLE it_suppliers INTO wa_supplier WITH KEY name = 'Jega'.

IF sy-subrc EQ 0.
WRITE: / 'Supplier found - Name:', wa_supplier-name, 'DNI:', wa_supplier-dni.
ELSE.
WRITE: / 'Supplier not found.'.
ENDIF.


  • To optimize this search, use binary search, which finds the position of a value in a sorted internal table. First, sort the table with SORT and then perform the read with BINARY SEARCH.

SORT ti_suppliers ASCENDING BY name.
READ TABLE ti_suppliers INTO wa_suppliers WITH KEY name='Jega' BINARY SEARCH.

IF sy-subrc EQ 0.
WRITE: / 'Supplier found - Name:', wa_supplier-name, 'DNI:', wa_supplier-dni.
ELSE.
WRITE: / 'Supplier not found.'.
ENDIF.

  • If you want to find a specific position, use INDEX.

READ TABLE ti_suppliers INTO wa_suppliers INDEX 5.

IF sy-subrc EQ 0.
WRITE: / 'Supplier found - Name:', wa_supplier-name, 'DNI:', wa_supplier-dni.
ELSE.
WRITE: / 'Supplier not found.'.
ENDIF.

Others statements over Internal Tables.

  • To modify the content, use MODIFY. The work area is required.
wa_proveedores-dni = '24987500'.
MODIFY ti_suppliers FROM wa_suppliers INDEX 1.

IF sy-subrc EQ 0.
WRITE: / 'OK'.
ELSE.
WRITE: / 'Error'.
ENDIF.

  • To add a record, use INSERT. The work area is needed.

wa_proveedores-nombre = 'Marcelo'.
wa_proveedores-apellido = 'Rivarola'.
wa_proveedores-dni = '20857492'.

INSERT wa_proveedores INTO ti_proveedores INDEX 2.

IF sy-subrc EQ 0.
WRITE: / 'OK'.
ELSE.
WRITE: / 'Error'.
ENDIF.

  • For deletion, use DELETE.

DELETE it_suppliers WHERE dni='28280933'.

IF sy-subrc EQ 0.
WRITE: / 'OK'.
ELSE.
WRITE: / 'Error'.
ENDIF.

  • To delete all content of an internal table, use REFRESH.

REFRESH it_suppliers.

  • To determine the number of records in an internal table, use DESCRIBE TABLE. Declare the variable V_LINES of type i.

DATA: v_lines TYPE i.

DESCRIBE TABLE it_suppliers LINES v_lines.

IF v_lines > 0.
ENDIF.

  • To initialize the work area or header, use CLEAR wa_suppliers.

CLEAR wa_suppliers.

  • To free up the space occupied by an internal table in memory, use FREE ti_suppliers.

FREE ti_suppliers.

E.g

* Internal table for passengers
DATA: BEGIN OF it_passengers OCCURS 0,
passport(10) TYPE c,
full_name(30) TYPE c,
birthdate TYPE dats,
END OF it_passengers.

* Structure for passengers
DATA: wa_passenger LIKE LINE OF it_passengers.

*----------------------------------------------------------------------*
START-OF-SELECTION.
*----------------------------------------------------------------------*

CLEAR wa_passenger.
wa_passenger-passport = 'ABC123456'.
wa_passenger-full_name = 'John Smith'.
wa_passenger-birthdate = '19851215'.
APPEND wa_passenger TO it_passengers.

CLEAR wa_passenger.
wa_passenger-passport = 'XYZ987654'.
wa_passenger-full_name = 'Alice Johnson'.
wa_passenger-birthdate = '19780423'.
APPEND wa_passenger TO it_passengers.

CLEAR wa_passenger.
wa_passenger-passport = 'DEF345678'.
wa_passenger-full_name = 'Michael Brown'.
wa_passenger-birthdate = '19901102'.
APPEND wa_passenger TO it_passengers.

WRITE:/1(20) 'Passport',
21(30) 'Full Name',
51(20) 'Birthdate'.

LOOP AT it_passengers INTO wa_passenger.

WRITE:/1(20) wa_passenger-passport,
21(30) wa_passenger-full_name,
51(20) wa_passenger-birthdate.

ENDLOOP.

 

 

 

2 Agradecimientos:

Han agradecido este aporte: Alvaro Ardila Sandoval, Octavio Pasciucco


Sobre el autor

Publicación académica de Jaime Eduardo Gomez Arango, en su ámbito de estudios para la Carrera Consultor ABAP.

SAP Master

Jaime Eduardo Gomez Arango

Profesión: Ingeniero de Sistemas y Computación - España - Legajo: SW34C

✒️Autor de: 99 Publicaciones Académicas

🎓Cursando Actualmente: Consultor ABAP Nivel Avanzado

🎓Egresado del módulo:

Disponibilidad Laboral: FullTime

Presentación:

Ingeniero de sistemas y computación con 8 años de experiencia el desarrollo frontend & backend (react/node) y en cloud (aws), actualmente desarrollando habilidades en sap btp, ui5, abap y fiori.

Certificación Académica de Jaime Gomez

✒️+Comunidad Académica CVOSOFT

Continúe aprendiendo sobre el tema "Las tablas internas" de la mano de nuestros alumnos.

SAP Senior

El uso de tablas internas facilita y ayuda a que en sap no se generen tablas Z innecesarias.

Acceder a esta publicación

Creado y Compartido por: Faharid Manjarrez

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Master

Para el manejo de tablas internas, es importante saber cuando deben llevar un area de trabajo de tal forma de agilizar y poder explotar la versatilidad del lenguaje de programacion ABAP, porque permita diferenciar el trabajo simple, del trabajo con tablas del sistema.

Acceder a esta publicación

Creado y Compartido por: Luis Enrique Quintero Florido

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Master

Tabla internas alamcenar temporalmente coleccion de daros sin estar que accediendo a la base de datos para ello utilizamos tablas internas uso tipico almacenar temporalmente los datos de las bases de datos para un procesamiento futuro. estructurar y formatear datos que se mostraran como salida del programa formatear datos para ser utilizados por otros servicios como declarar tablas internas DATA: BEGIN OF <TABLA> OCCURS <N> <DEF CAMPO> END OF <TABLA> OCCURS: especifica la cantidad de registros en memoria AREA DE TRABAJO Cabecera de una tabla interna que tiene el contenido de una tabla interna que se esta procesando APPEND TO : se añade un registro a la tabla interna en la ultima posicion con los valores que...

Acceder a esta publicación

Creado y Compartido por: Andres Felipe Escobar Lopez

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Master

Tablas internas Para acabar (por el momento) tenemos las tablas internas. Sirven básicamente para almacenar la información que extraemos de las tablas de la base de datos. Una tabla interna es también una matriz de datos, pero bidimensional. Al contrario que las estructuras que sólo pueden contener un valor para cada campo, las tablas internas contendrán muchos registros. Cada registro llevará un valor diferente en el mismo campo a la manera que tiene una tabla transparente de diccionario. Podemos declarar tablas internas de diferentes maneras: Ejemplo de declaración de tablas internas: ************************************************************************ *Tablas internas ************************************************************************...

Acceder a esta publicación

Creado y Compartido por: Cesar Ismael Rodriguez Zorrilla

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP SemiSenior

tablas internas. es un objeto de datos. append to

Acceder a esta publicación

Creado y Compartido por: Christian Camilo Alzate Duque

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Master

TABLAS INTERNAS Objeto de datos que permite guardar en memoria grandes cantidades de registros de datos con la misma estructura. cuyo límite se especifica en la instalacoón del sistema. Usos: Almacenamiento temporal de datos de bases de datos para futuro procesamiento. Estructurar y formatear datos que se mostrarán como salida del programa. Formatear datos para ser utilizados por otrs servicios. DECLARACIÓN DE TABLAS INTERNAS DATA: BEGIN OF <tabla> OCCURS <n>, <Def.Campo>, ... END OF <tabla> Tabla interna es la misma tabla interna estándar DATA: ti_vuelos like standard table of SFLIGHT with header line 3. LLENADO DE TABLA INTERNA Para llenar de datos las tablas internas...

Acceder a esta publicación

Creado y Compartido por: Jorge Alirio Carrillo García

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

- Tablas Internas Las tablas internas son un objeto de datos que nos permite guardar grandes cantidades de registros con la misma estructura, para evitar el acceso a las bases de datos constantemente. La cantidad de registros máxima está limitada a las especificaciones en la instalación del sistema. - Usos de las tablas internas: Almacenar temporalmente los datos de las BD para su procesamiento. Estructurar y formatear datos que se mostrarán como salida del programa. Formatear datos para utilizarlos en otros servicios. - Declaración de una tabla interna: DATA: BEGIN OF <tabla> OCCURS <n>, <Def. Campo>, .... ...

Acceder a esta publicación

Creado y Compartido por: Sandra Erika Bernabe Abreu

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

Las tablas internas sirven para realizar operaciones con la data de las tablas estándares sin tener que acceder a estas tablas cada vez que se necesite un dato. El agregado OCCURS en la declaración de una tabla interna limitan la cantidad de registros de la misma. El agregado WITH HEADER LINE define una cabecera a la tabla interna. Se puede declarar una tabla interna de la siguiente manera: <nombre_tabla_1> LIKE STANDARD TABLE OF <work_area>, siendo <work_area> una estructura. CLEAR inicializa una cabecera o work area de una tabla interna. APPEND añade un registro al final de la tabla interna. LOOP - ENDLOOP recorre el contenido de una tabla interna. READ TABLE lee un registro de una tabla interna dada...

Acceder a esta publicación

Creado y Compartido por: George Yunkichi Okuma Zavala

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

Tablas Internas Las tablas internas son un objeto de datos que nos permite guardar grandes cantidades de registros con la misma estructura, para evitar el acceso a las bases de datos constantemente. La cantidad de registros máxima está limitada a las especificaciones en la instalación del sistema. - Usos de las tablas internas: Almacenar temporalmente los datos de las BD para su procesamiento. Estructurar y formatear datos que se mostrarán como salida del programa. Formatear datos para utilizarlos en otros servicios. - Declaración de una tabla interna: DATA: BEGIN OF <tabla> OCCURS <n>, <Def. Campo>, .... ...

Acceder a esta publicación

Creado y Compartido por: Juan Rodrigo Meza Avina

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

TABLA INTERNA Es un objeto de datos que permite guardar en memoria grandes cantidades de registros de datos con la misma estructura. AREA DE TRABAJO: Cabecera de una tabla interna que tiene el contenido del registro de la tabla interna que se esta procesando. OCURRS: Clausula ABAP que se utiliza para especificar la cantidad de registro en memoria de una tabla interna. Por lo general en el parametro OCURRS se especifica la cantidad 0 lo que permite trabajar con tablas de gran cantidad de registros. AREA DE TRABAJO (WA): Cabecera de una tabla interna que tiene el contenido del registro de la tabla interna que se esta procesando. SELECT: Sentencia ABAP que se utiliza para acceder a las bases de datos de SAP. SORT: Sentencia ABAP que se utiliza...

Acceder a esta publicación

Creado y Compartido por: David Camacho Espinoza

 


 

👌Genial!, estos fueron los últimos artículos sobre más de 79.000 publicaciones académicas abiertas, libres y gratuitas compartidas con la comunidad, para acceder a ellas le dejamos el enlace a CVOPEN ACADEMY.

Buscador de Publicaciones:

 


 

No sea Juan... Solo podrá llegar alto si realiza su formación con los mejores!