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

 X 

✒️ABAP El lenguaje SQL y la sentencia SELECT

ABAP El lenguaje SQL y la sentencia SELECT

ABAP El lenguaje SQL y la sentencia SELECT

SQL Language and the SELECT Statement


SQL (Structured Query Language)
is a query language used as an interface to communicate with databases, facilitating access and manipulation of stored information.

Statements in SQL fall into three groups:

  • Data Definition Language (DDL): Used for defining structures like schema, databases, database tables, constraints, etc.
  • CREATE: Creates a database, database tables, views, etc.
  • ALTER: Modifies the structure of the database, e.g., adding or deleting columns from a database table.
  • DROP: Deletes objects from the structure, e.g., an index or a sequence.
  • Data Manipulation Language (DML): Allows users to input data for subsequent querying or modification of database data.
  • SELECT: Used for data queries.
  • INSERT: Inserts values into a database table.
  • UPDATE: Modifies values of one or more records.
  • MODIFY: Also used for modifying values of one or more records.
  • DELETE: Deletes rows from a database table.
  • Data Control Language (DCL): Enables granting or revoking permissions on objects to users connecting to the database.
  • GRANT: Grants permissions.
  • REVOKE: Removes previously granted permissions.

The SELECT Statement

Used to retrieve information in SQL, allowing the retrieval of records from the database, from one or more combined tables. It also enables information filtering to obtain only records that meet certain conditions.

In ABAP, the SELECT statement has the following syntax:

SELECT result " Fields to be retrieved
FROM table " Database table from which data is fetched
INTO target " Destination where data will be stored
WHERE conditions. " Search conditions

There are different variants of SELECT, here are some of them:

  • SELECT * INTO TABLE: With the asterisk * symbol, we indicate that we want all records from the table. INTO TABLE is used when the query result is stored in an internal table. Important: Avoid using * when only a few fields from the source table are needed.

SELECT *
FROM zuser_table
INTO TABLE it_users.


  • SELECT * APPENDING TABLE: With APPENDING TABLE instead of INTO TABLE, we add database records to the internal table without deleting existing records. It is advisable to REFRESH the internal table where the data will be stored before selecting them. If a variable or structure is used, then CLEAR should be executed.

SELECT *
FROM zuser_table
APPENDING TABLE it_users.

  • SELECT field1: To select only one field from a database, use an auxiliary table with only the desired field, for example, DNI. Always check SY-SUBRC after a SELECT to determine how to proceed. If you want to retrieve two fields from the database table, write the field names after the SELECT statement, in the same order as they appear in the database table. If the format where the data will be stored does not match the retrieved data, an error occurs.

SELECT dni
FROM zuser_table
INTO TABLE it_users_aux.

  • SELECT SINGLE: If you want to retrieve the first occurrence of a table, execute SELECT SINGLE *. The result of this query will be stored in the WA_USERS structure, which is of the same type as the ZUSER_TABLE table.
CLEAR wa_users.

SELECT SINGLE *
FROM zuser_table
INTO wa_users
WHERE name_surname NE space.

If you want to retrieve only one field, store the result in a variable.

CLEAR v_dni.

SELECT SINGLE dni
FROM zuser_table
INTO v_dni
WHERE name_surname NE space.

  • SELECT INTO CORRESPONDING FIELDS OF TABLE: If you want to retrieve records from a database table that meet a condition but want to store them in an internal table with a different structure, use the INTO CORRESPONDING FIELDS OF TABLE clause.

SELECT name_surname user_status
FROM zuser_table
INTO CORRESPONDING FIELDS OF TABLE it_users2
WHERE name_surname NE space
AND user_status EQ 'A'.

  • SELECT ...WHERE IN: If you want to make a selection from a database table based on user input, do the following. The IN clause is used for select-options in the conditions of a select.

SELECT *
FROM zuser_table
INTO TABLE it_users
WHERE name_surname EQ p_name_surname
AND user_status IN s_user_status.

  • SELECT MAX: If you want to get the active user with the highest DNI, you have to use the MAX clause as follows.

CLEAR v_dni.

SELECT SINGLE max dni
INTO v_dni
FROM zuser_table
WHERE user_status EQ 'A'.

  • SELECT COUNT: If you want to count the number of active users, use the COUNT clause as follows.

CLEAR v_active_users.

SELECT COUNT (*)
INTO v_active_users
FROM zuser_table
WHERE user_status EQ 'A'.

  • SELECT FOR ALL ENTRIES IN: If you want to retrieve all records from a table that exist in an internal table loaded with data, use FOR ALL ENTRIES IN, allowing you to specify conditions at runtime.

SELECT *
INTO TABLE it_users
FROM zuser_table
FOR ALL ENTRIES IN it_providers
WHERE dni EQ it_providers-dni.

  • SELECT ...LIKE: If you want to retrieve all records that match a text pattern in any of their fields, use the LIKE clause.

SELECT *
FROM zuser_table
INTO TABLE it_users
WHERE name_surname LIKE 'A%'.

  • SELECT ...INNER JOIN: It is possible to perform a SELECT on more than one database table, known as JOIN. To analyze this point, we will work with two crucial standard SAP database tables, VBRK for Invoice: Header Data, and VBRP for Invoice: Item Data. Suppose we want to retrieve records from both database tables where the VBELN (Invoice Number) field matches. This will be the join condition between both tables, and for these records, we will select the following fields from the VBRK database table:

TYPES: BEGIN OF ty_invoices,
vbeln LIKE vbrk-vbeln, " vbrk - Invoice (VBELN)
fkart LIKE vbrk-fkart, " vbrk - Invoice class (FKART)
fktyp LIKE vbrk-fktyp, " vbrk - Invoice type (FKTYP)
vbtyp LIKE vbrk-vbtyp, " vbrk - Commercial document type (VBTYP)
waerk LIKE vbrk-waerk, " vbrk - Document currency (WAERK)
vkorg LIKE vbrk-vkorg, " vbrk - Sales organization (VKORG)
vtweg LIKE vbrk-vtweg, " vbrk - Distribution channel (VTWEG)
posnr LIKE vbrp-posnr, " vbrp - Invoice item (POSNR)
netwr LIKE vbrp-netwr, " vbrp - Net value of invoice item (NETWR)
END OF ty_invoices.

DATA: it_invoices TYPE STANDARD TABLE OF ty_invoices,
wa_invoices LIKE LINE OF it_invoices.

SELECT t1~vbeln t1~fkart t1~fktyp t1~vbtyp t1~waerk t1~vkorg t1~vtweg t2~posnr t2~netwr
INTO CORRESPONDING FIELDS OF TABLE it_invoices
FROM vbrk AS t1 INNER JOIN vbrp AS t2
ON t2~vbeln = t2~vbeln.

The INNER JOIN clause between two database tables A and B will yield the result of the intersection of sets A and B. In other words, the inner part, i.e., the records common to both database tables based on the connection condition between them.

In ABAP, the LEFT OUTER JOIN clause between two database tables A and B is also available, where the result will be the union between tables A and B plus the outer information part of database table A, from the left side of the union.

E.g

*&---------------------------------------------------------------------*
*& Report ZTEST_ABAP_JEGA_10
*&---------------------------------------------------------------------*
*& To complete this exercise, the message class Z_TEST must be created,
*& a zuser_table_jega must be created and the text corresponding
*& to the Z_BD parameter on the selection screen must be completed.
*&---------------------------------------------------------------------*
REPORT ztest_abap_jega_10.

* Declaration of Tables
DATA: it_users TYPE STANDARD TABLE OF zuser_table_jega,
wa_users LIKE LINE OF it_users.

* Declaration of Variables
DATA: v_birthdate TYPE z_bd.

*----------------------------------------------------------------------*
* Selection Screen
*----------------------------------------------------------------------*
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE TEXT-001.
SELECT-OPTIONS: s_bd FOR v_birthdate. "Birthdate
SELECTION-SCREEN END OF BLOCK b1.
*----------------------------------------------------------------------*

*----------------------------------------------------------------------*
AT SELECTION-SCREEN.
*----------------------------------------------------------------------*
* Validate that data is entered on the selection screen
IF s_bd-low IS INITIAL AND s_bd-high IS INITIAL.
MESSAGE e001(z_test) WITH 'Please complete the Birthdate field'.
ENDIF.

*----------------------------------------------------------------------*
START-OF-SELECTION.
*----------------------------------------------------------------------*
CLEAR it_users.
REFRESH it_users.

SELECT *
FROM zuser_table_jega
INTO TABLE it_users
WHERE birthdate IN s_bd.

IF sy-subrc EQ 0.

* Users Title
WRITE: /1(133) sy-uline.
WRITE:/1(1) sy-vline,
2(86) ' Users ',
133 sy-vline.

* Field Headers
WRITE: /1(133) sy-uline.
WRITE:/1(1) sy-vline,
2(8) 'DNI',
11 sy-vline,
12(30) 'Nombre Completo',
43 sy-vline,
44(20) 'Estado',
65 sy-vline,
66(30) 'Birthdate',
133 sy-vline.
WRITE: /1(133) sy-uline.

LOOP AT it_users INTO wa_users.

* Content of the Users Table
WRITE:/1(1) sy-vline,
2(8) wa_users-dni,
11 sy-vline,
12(30) wa_users-nombre_ape,
43 sy-vline,
44(20) wa_users-estado,
65 sy-vline,
97(20) wa_users-birthdate,
133 sy-vline.

ENDLOOP.

WRITE: /1(133) sy-uline.

ELSE.
MESSAGE s001(z_test) WITH 'No data found for the selected criteria'.
ENDIF.


 

 

 


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 "El lenguaje SQL y la sentencia SELECT" de la mano de nuestros alumnos.

SAP Master

SQL, sus siglas significan lenguaje de consulta estructurado. es un lenguaje de consulta, usado como interfaz para comunicarse con bases de datos y realizar operaciones de acceso y manipulacion de la informacion almacenada. Algunos sistemas de gestion de bases de datos comunes que utilizan SQL son ORACLE, SAP HANA, MY SQL; Microsoft SQL SERVER, microsoft acces, ingres etc. LA SENTENCIA SELECT se utiliza para realizar informacion en SQL, es decir permite obtener registros de la base de datos de una o varias tablas combinadas. Ademas permite hacer filtrados de la informacion para obtener unicamente los registros que cumplen ciertas condiciones. Una sentencia select recupera cero o mas filas de una o mas tablas de base de datos o vistas de base...

Acceder a esta publicación

Creado y Compartido por: Pedro Salazar / Disponibilidad Laboral: FullTime + Carta Presentación

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

SAP Expert


La sentencia "SELECT" en el contexto de SAP ABAP (Advanced Business Application Programming), que se utiliza para recuperar datos de una base de datos. La sentencia "SELECT" se utiliza para consultar registros en tablas de la base de datos y recuperar la información que necesitas para tu programa. La sentencia "SELECT" puede incluir más detalles, como cláusulas "WHERE" para filtrar los registros, "GROUP BY" para agrupar resultados y otras opciones que permiten personalizar la consulta según tus necesidades. QL (Structured Query Language) es un lenguaje de programación utilizado para gestionar y manipular bases de datos relacionales. Con SQL, puedes realizar...

Acceder a esta publicación

Creado y Compartido por: Darling Geraldino

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

SAP Expert

El lenguaje SQL y la sentencia SELECT LECCION 6º DE 10 1 - El lenguaje SQL. Lenguaje de consulta estructurado, interfaz para cominucacrse con la base de datos y realizar operaciones de acceso y manipulacion de la informacion almacenda. Las sentencias SQL la podemos clasificar en 3. Lenguaje de definicion de datos(DDL) : se usa para definir estructuras como el esquema, la base de datos, las tablas de db, las restricciones, etc. Se dispone de CREATE, ALTER, DROP Lenguaje de manipulacion de datos (DML): se usa para manipular los datos. SELECT, INSERT,UPDATE, MODIFY, DELETE. Lenguaje de control de datos(DCL): se usa para dar o quitar permisos sobre los objetos a los que los usuarios se conectan a la base de datos. GRANT,REVOKE....

Acceder a esta publicación

Creado y Compartido por: Pablo Adrian Oggero

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

SAP Senior

SQL es un lenguaje de consulta de bases de datos, que se utiliza para comunicarse con la base de datos y realizar operaciones, este lenguaje es el mas utilizado por las bases de datos relacionales y aunque es el mas utilizado cada base de datos tiene sus propias extensiones. las sentencias del lenguaje SQL pueden ser clasificadas en tres, que serian * lenguaje de definición de datos DDL - CREATE. - ALTER. - DROP. * lenguaje de manipulación de datos. DML - SELECT - INSERT - UPDATE - MODIFY - DELETE * lenguaje de control de datos DCL - GRANT - REVOKE LA SENTENCIA SELECT esta sentencia permite obtener registros de la base de datos, filtrados o no. para obtener todos los resultados de una tabla se pone * y INTO TABLE cuando los...

Acceder a esta publicación

Creado y Compartido por: Jose Sebastian Salamanca Garcia

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

SAP Junior

1. La sentencia SELECT Se utiliza para acceder a las bases de datos de SAP. podemos acceder a los registros almacenados en todas las tablas. Sintaxis: SELECT<resultado> FROM<tabla> INTO<target> WHERE<condiciones>. Ejemplo. Si quisieramos obtener los registros de la tabla ZTABLA_USUARIOS, usariamos el siguiente codigo: SELECT * FROM ztabla_usuarios INTO TABLE ti_usuarios. APPENDING TABLE: Se utiliza junto con la sentencia SELECT y produce que los regsitros de las tablas que se selecionan se añadan al final de la tabla interna sin pisar los registros preexistentes en la tabla interna. INTO TABLE: Se utiliza junto con la sentencia SELECT y produce que los rgistros de las tablas base de datos que se selecionan,...

Acceder a esta publicación

Creado y Compartido por: Jairo Alexander Arias Linares

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

SAP Junior

Lenguaje SQL y la sentencia Select 1. Lenguaje SQL Sus siglas significan Lenguaje de Consulta estrucurado Es un lenguaje de consulta usado como interfaz para comunicarse con bases de datos y realizar operaciones de acceso y manipulacion de la informacion almacenada. Es un lenguaje sencillo de consulta que permite la seleccion, insercion, actualizacion y borrado de datos. Tiene la capacidad de hacer calculos avanzados en algebra. Es utilizado en empresas que almacenana datos en una base de datos. El lenguaje SQL es estandar mantenido por ANSI, por lo que las bases de datos son las mismas en la mayoria de los sistemas Algunos de bases de datos mas comunes que utiliza SQL son: ORACLE, SAP, HANA, MySQL, Microsoft SQLm Microsoft...

Acceder a esta publicación

Creado y Compartido por: Lucas Mera / Disponibilidad Laboral: FullTime + Carta Presentación

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

SAP SemiSenior

Sentencia Select nos permite acceder a la base de datos SELECT <cmpos necesitamos> FROM <tabla BD> INTO TABLE<tabla (o workarea)> WHERE <campo> = <valor>. recomendable realizar CLEAR o REFRESH a la tabla antes de la siguiente sentencia SELECT <cmpos necesitamos> FROM <tabla BD> APPENDING TABLE <tabla o workarea> WHERE <campo> = <valor>. SELECT SINGLE<cmpos necesitamos> FROM <tabla BD> INTO TABLE<tabla (o workarea)> WHERE <campo> = <valor>. "para obtener 1er ocurrencia SELECT SINGLE<cmpos necesitamos> FROM <tabla BD> INTO <variable> WHERE <campo> = <valor>. "para obtener 1er ocurrencia en variable SELECT <cmpos1>...

Acceder a esta publicación

Creado y Compartido por: Tania Luisa Diaz Corona / Disponibilidad Laboral: FullTime + Carta Presentación

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

SAP Senior

EL LENGUAJE SQL: SQL como sus siglas la identifican, se definen como "Lenguaje de consulta estructurado" este lenguaje puede ser clasificado en tres grupos que son los siguientes: - Lenguaje de definición de datos DDL: gracias a este lenguaje podemos definir los diferentes objetos que tenemos en nuestra base de datos, se utiliza para definir estructuras como son el esquema, la base de datos, las tablas de bases de datos, las restricciones, etc. Para definir las estructuras disponemos de 3 sentencias: *** CREATE: se utiliza para crear una base de datos, tablas bases de datos, vistas, etc. *** ALTER: se utiliza para modificar la estructura de la base de datos, por ejemplo añadir o borrar columnas de una tabla base de datos....

Acceder a esta publicación

Creado y Compartido por: Jean Carlos Lopez / Disponibilidad Laboral: FullTime

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

SAP Senior

SQL SELECT - Es la principal sentencia para acceder bases de datos. SELECT * FROM z_tabla INTO TABLE ti_tabla WHERE condiciones *ti-tabla es del mismo tipo que z_tabla APPENDING TABLE - No planchará el contenido de una tabla interna sino que lo agreagará al final. *Se recomienda hacer CLEAR Y REFRESH a la tabla interna Si solo vamos a obtener un campo es recomendable crear una tabla auxiliar solo con ese campo: SELECT id FROM z_tabla INTO TABLE ti_id. ****SY-SUBRC****** Validar siempre que sea 0 despues de cada sentencia para confirmar éxito o error. -Obtener el primer registro SELECT SINGLE * FROM z_tabla INTO wa_table -Obtener un campo del primer registro, va a una variable SELECT SINGLE id FROM z_tabla INTO v_id -Guardar...

Acceder a esta publicación

Creado y Compartido por: Armando Mayo Marquez / Disponibilidad Laboral: FullTime + Carta Presentación

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

SAP Master

Con la sentencia SELECT podemos seleccionar los registros de las tablas bases de datos. Se recomienda utilizar las sentencias CLEAR y REFRESH antes de realizar una selección de una tabla interna. Con la cláusula SINGLE obtenemos el primer registro que cumpla la condición especificada dentro de la selección. La cláusula IN se utiliza con la sentencia SELECT cuando dentro de la condición se utilizan select-options. La cláusula COUNT cuenta la cantidad de registros que cumple con una condición específica.

Acceder a esta publicación

Creado y Compartido por: Mónica Robles

 


 

👌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!