Database Update Opensql

18
LINK: https://training.sap.com/mx/es Database Updates with ABAP Open SQL ABAP has the following commands for making database changes: Native SQL Accessing the database with Native SQL enables you to use database- specific commands. Use of these commands requires detailed knowledge of their syntax. Programs that use Native SQL commands need additional programming after they are transported to different system environments (different database systems) because the syntax of the commands needs to be adjusted on a database-specific basis. Implement database access using Native SQL only if a Native SQL function that is not available in Open SQL must be used. Open SQL Open SQL commands are not database specific. They are automatically converted into the respective SQL statements by the database interface and passed to the database. An ABAP program that operates with Open SQL is, therefore, not database specific and you can use it in any SAP system without adjustments. Open SQL also enables you to buffer the content of database tables locally on the application server for quick read access. Local buffering of the content reduces the database load. The data is automatically read from the buffer after the table settings are done.

description

Actualizacion de base de datos con OpenSQL

Transcript of Database Update Opensql

Page 1: Database Update Opensql

LINK:

https://training.sap.com/mx/es

Database Updates with ABAP Open SQL

ABAP has the following commands for making database changes:

Native SQL

Accessing the database with Native SQL enables you to use database-

specific commands. Use of these commands requires detailed knowledge

of their syntax. Programs that use Native SQL commands need additional

programming after they are transported to different system environments

(different database systems) because the syntax of the commands needs

to be adjusted on a database-specific basis. Implement database access

using Native SQL only if a Native SQL function that is not available in

Open SQL must be used.

Open SQL

Open SQL commands are not database specific. They are automatically

converted into the respective SQL statements by the database interface

and passed to the database. An ABAP program that operates with Open

SQL is, therefore, not database specific and you can use it in any SAP

system without adjustments.

Open SQL also enables you to buffer the content of database tables locally

on the application server for quick read access. Local buffering of the

content reduces the database load. The data is automatically read from the

buffer after the table settings are done.

Page 2: Database Update Opensql

Open SQL commands perform operations only for Data Manipulation

Language (DML), not for Data Definition Language (DDL), because

DDL commands are integrated in the ABAP Dictionary.

For more information about Native and Open SQL, refer to the ABAP Editor

keyword documentation for the term SQL.

ABAP tiene los siguientes comandos para hacer los cambios de

base de datos:

• SQL Native

Acceso a la base de datos con SQL Native le permite utilizar

comandos específicos de bases de datos. El uso de estos

comandos requiere un conocimiento detallado de su sintaxis.

Los programas que utilizan comandos SQL nativos necesitan

programación adicional después de que se transportan a

diferentes entornos de sistema (los diferentes sistemas de

bases de datos), ya que la sintaxis de los comandos necesita

ser ajustado de manera específica de la base de datos.

Implementar el acceso de base de datos mediante SQL nativo

sólo si una función nativa de SQL que no está disponible en

Open SQL debe ser utilizado.

• Abra SQL

Comandos SQL abiertos no son específicos de la base de datos.

Ellos se convierten automáticamente en las sentencias SQL

respectivos por la interfaz de base de datos y pasan a la

base de datos. Un programa ABAP que funciona con Open SQL es,

por tanto, no la base de datos específica y se puede utilizar

en cualquier sistema SAP sin ajustes.

Abra SQL también permite amortiguar el contenido de las tablas

de bases de datos de forma local en el servidor de

aplicaciones para acceso de lectura rápida. Buffering Local

del contenido reduce la carga de base de datos. Los datos se

leen automáticamente de la memoria intermedia después se

hacen los arreglos de mesa.

Comandos SQL Abiertas realizan operaciones de manipulación de

datos sólo para Language (DML), no para Data Definition

Language (DDL), porque los comandos DDL se integran en el

Diccionario ABAP.

Para obtener más información acerca de nativo y Open SQL,

consulte la documentación de palabras clave ABAP Editor para

el término de SQL.

Page 3: Database Update Opensql

You can limit the target quantity to be read from the database using all

the Open SQL commands.

SQL commands are available for single record access and multiple

records access (or set access). A single set access usually performs

better than multiple single record accesses (except for the MODIFY

command) when applied to a certain number of records of data.

A syntax variant is available for the change operation that you can use

to change individual fields in a record. If you have masked field

selections (WHERE <field> LIKE '<search_mask>'), ‘_’ masks an

individual character and ‘%’ masks a character string of any length in

record with the SQL standard.

All the Open SQL commands display a message about the success or

failure of the database operation performed. The message is in the form

of a return code in the system field sy-subrc. If sy-subrc equals 0, it

means that the SQL operation has been successfully completed. All

other values of the field mean that errors have occurred. For further

details, refer to the keyword documentation for the command in

question.

Page 4: Database Update Opensql

In addition, the sy-dbcnt system field displays the number of records

for which the desired database operation was actually carried out.

Note: Open SQL commands do not perform any automatic

authorization checks. You need to execute these explicitly in your

program (statement AUTHORITY-CHECK).

Usted puede limitar la cantidad prevista para ser leído desde

la base de datos con todos los comandos SQL abiertas.

Comandos SQL están disponibles para el acceso y registro único

de acceso múltiple registros (o conjunto de acceso). Un único

set access generalmente funciona mejor que múltiples accesos

de registro individuales (excepto para el comando MODIFY)

cuando se aplica a un cierto número de registros de datos.

Una variante de sintaxis está disponible para la operación

de cambio que usted puede utilizar para cambiar los campos

individuales en un registro. Si ha enmascarado selecciones

de campo (donde <field> COMO '<search_mask>'), '_' máscaras

de un carácter individual y '%' oculta una cadena de

caracteres de cualquier longitud en el expediente con el

estándar SQL.

Todos los comandos SQL abiertas muestran un mensaje sobre el

éxito o fracaso de la operación de la base de datos realizada.

El mensaje está en la forma de un código de retorno en el

campo del sistema sy-SUBRC. Si sy-SUBRC es igual a 0,

significa que la operación de SQL se ha completado con éxito.

Todos los demás valores del campo significan que se han

producido errores. Para más detalles, consulte la

documentación de la palabra clave para el comando en cuestión.

Además, el campo del sistema sy-dbcnt muestra el número de

registros para los que la operación de la base de datos

deseada se lleva a cabo efectivamente.

Nota: Los comandos Abrir SQL no realizan ninguna comprobación

de autorización automática. Es necesario para ejecutar estos

explícitamente en su programa (declaración AUTORIDAD-CHECK).

Page 5: Database Update Opensql

If you do not specify the addition CLIENT SPECIFIED in an Open SQL

command, no client specification is allowed in the associated WHERE clause.

If the database table contains client-dependent data, the records of the current

execution client are accessed. The database interface automatically adds the

corresponding WHERE clause.

If you process data from other clients, specify the addition CLIENT

SPECIFIED in the Open SQL command and the associated client(s) in the

appropriate WHERE clause.

Caution: If an Open SQL command contains the addition CLIENT SPECIFIED

without a client specification, the system accesses the datasets of all clients.

Si no se especifica el CLIENTE Además especificado en un

comando Open SQL , no se permite la especificación del cliente

en el asociado cláusula WHERE. Si la tabla de base de datos

contiene los datos del cliente dependiente , se accede a los

registros del cliente de ejecución actual . La interfaz de

base de datos agrega automáticamente la correspondiente

cláusula WHERE.

Si procesa los datos de otros clientes , especifique el

CLIENTE Además especificado en el comando Open SQL y el

cliente ( s ) asociada en la cláusula WHERE apropiada .

Page 6: Database Update Opensql

Precaución: Si un comando Abrir SQL contiene el CLIENTE Además

especificado sin una especificación de cliente, el sistema

accede a los datos de todos los clientes .

Use the statements INSERT, UPDATE, MODIFY, and DELETE to change the

content of database tables.

To insert a new record in a database table, enter the command INSERT INTO

<dbtab> VALUES <wa>. Before running this command, you must place the

record to be inserted in the structure <wa>. This structure must be of the same

type as the records in the database table concerned.

The client field that may exist in the structure <wa> is used only if the CLIENT

SPECIFIED addition is specified. If there is no CLIENT SPECIFIED addition,

the client value of the current logged on client is taken as the default client.

Records can also be inserted using database views. However, the database view

must already be created in the ABAP Dictionary with the maintenance status

“read and change” and must only contain fields from a table.

Utilice las instrucciones INSERT , UPDATE , modificar y

eliminar a cambiar el contenido de las tablas de bases de

datos .

Page 7: Database Update Opensql

Para insertar un nuevo registro en una tabla de base de datos

, escriba el comando INSERT INTO < dbtab > VALORES < wa > .

Antes de ejecutar este comando , debe colocar el registro a

insertarse en la estructura < wa > . Esta estructura debe ser

del mismo tipo que los registros de la tabla de base de datos

en cuestión.

El campo de cliente que pueda existir en la estructura < wa

> sólo se utiliza si se especifica la adición cliente

especificado . Si no hay cliente especificado Además, el valor

para el cliente de la corriente que se conectó el cliente se

toma como el cliente predeterminado .

Los registros también se pueden insertar utilizando vistas

de base de datos . Sin embargo , la vista de la base de datos

ya debe estar creado en el Diccionario ABAP con el estado de

mantenimiento "leer y cambiar " y sólo debe contener los

campos de una tabla .

You can use the command INSERT <dbtab> FROM TABLE <itab> to create

several records in a database table, as shown in the figure. In this command, the

internal table <itab> must have the same record structure as the corresponding

database table.

Page 8: Database Update Opensql

The client field that may exist in the internal table <itab> is used only if the

CLIENT SPECIFIED addition is specified. If there is no CLIENT SPECIFIED

addition, the client value of the current logged on client is taken as the default

client.

If it is possible to create all the records, sy-subrc is set to zero. However, if even

one data record cannot be created, the system triggers a runtime error and the

entire insertion operation is discarded (database rollback).

If you want to insert all records, use the command addition ACCEPTING

DUPLICATE KEYS. This addition has the effect that in case of an error, the

runtime error and also the database rollback are suppressed. The value of sy-

subrc is set to 4, and all the records without errors are inserted.

The sy-dbcnt system field contains the number of records that were successfully

inserted in the database.

Usted puede utilizar el comando INSERT <dbtab> DE MESA <itab>

para crear varios registros en una tabla de base de datos,

como se muestra en la figura. En este comando, la tabla

interna <itab> debe tener la misma estructura de registro

como la tabla de base de datos correspondiente.

El campo de cliente que pueda existir en la tabla interna

<itab> sólo se utiliza si se especifica la adición cliente

especificado. Si no hay cliente especificado Además, el valor

para el cliente de la corriente que se conectó el cliente se

toma como el cliente predeterminado.

Si es posible crear todos los registros, sy-SUBRC se pone a

cero. Sin embargo, si incluso un registro de datos no puede

ser creado, el sistema desencadena un error de ejecución y

toda la operación de inserción se descarta (rollback base de

datos).

Si desea insertar todos los registros, utilice la adición de

comandos ACEPTAR claves duplicadas. Esto además tiene el

efecto de que en caso de un error, se suprimen el error de

ejecución así como la reversión de la base de datos. El valor

de sy-SUBRC se establece en 4, y se insertan todos los

registros sin errores.

Page 9: Database Update Opensql

El campo sistema sy-dbcnt contiene el número de registros que

se insertaron con éxito en la base de datos.

Page 10: Database Update Opensql

You can use two variants of the UPDATE command to update a specific record

in a database table, as shown in the figure.

In the case of variant 1, the database record that is specified by the key in <wa>

is overwritten by the content of <wa>. However, the key field mandt that may

exist in <wa> is used only if the CLIENT SPECIFIED addition is specified.

Otherwise, the client value of the current logged on client is taken as the default

client. Logically, <wa> must have the same structure as the structure of the

database record to be changed.

In the case of variant 2, the system changes the record specified in the WHERE

clause. However, only the fields specified in the SET addition are overwritten

by the specified values in the database. In this variant, you must define the

record to be changed in the WHERE clause by specifying all the key field

evaluations.

You can specify simple calculation operations as evaluation for numeric

database fields in the SET addition “f = g, f = f + g, f = f - g”.

You can also change the records by using database views. However, the view

must already be created in the ABAP Dictionary with the maintenance status

“read and change” and must only contain fields from a table.

Se pueden utilizar dos variantes del comando UPDATE para

actualizar un registro específico en una tabla de base de

datos, como se muestra en la figura.

En el caso de la variante 1, el registro de base de datos que

está especificado por la llave en <wa> se sobrescribe por el

contenido de <wa>. Sin embargo, el Mandt campo clave que pueda

existir en <wa> sólo se utiliza si se especifica la adición

cliente especificado. De lo contrario, el valor para el

cliente de la corriente que se conectó el cliente se toma

como el cliente predeterminado. Lógicamente, <wa> debe tener

la misma estructura que la estructura de la base de datos de

registro que ser cambiado.

En el caso de la variante 2, el sistema cambia el registro

especificado en la cláusula WHERE. Sin embargo, sólo los

campos especificados en la adición SET se sobrescriben con

los valores especificados en la base de datos. En esta

variante, debe definir el récord de ser cambiado en la

Page 11: Database Update Opensql

cláusula WHERE especificando todas las evaluaciones de campo

clave.

Puede especificar las operaciones de cálculo sencillas como

la evaluación para los campos numéricos de base de datos en

la adición SET "f = g, f = f + g, f = f - g".

También puede cambiar los registros de base de datos mediante

el uso de puntos de vista. Sin embargo, la vista ya debe estar

creado en el Diccionario ABAP con el estado de mantenimiento

"leer y cambiar" y sólo debe contener los campos de una tabla.

The MODIFY command is SAP specific and it covers the following commands:

UPDATE

If the data record specified in the MODIFY statement exists in a table, the

system updates the record.

INSERT

If the data record specified in the MODIFY statement does not exist in

the table, the system inserts the record.

Using the syntax variants of the MODIFY command, such as the syntax of

UPDATE and INSERT, you can process one or more records.

You can also carry out the update/insert operation on database views. However,

the view must exist in the ABAP Dictionary with the maintenance status “read

and change” and must only contain fields from a table.

The sy-dbcnt field contains the numberf processed records.

Page 12: Database Update Opensql

El comando MODIFY es SAP específica y cubre los siguientes

comandos:

UPDATE

Si existe el registro de datos especificado en la

sentencia CAMBIAR en una tabla , el sistema actualiza el

registro .

INSERT

Si no existe el registro de datos especificado en la

sentencia CAMBIAR en la tabla, el sistema inserta el disco.

El uso de las variantes de sintaxis del comando MODIFY , como

la sintaxis de UPDATE y INSERT , puede procesar uno o más

registros .

También puede llevar a cabo la actualización de la operación

/ inserto en las vistas de base de datos . Sin embargo , la

vista debe existir en el Diccionario ABAP con el estado de

mantenimiento "leer y cambiar " y sólo debe contener los

campos de una tabla .

El campo -sy dbcnt contiene el número de registros procesados

Page 13: Database Update Opensql

The syntax for the DELETE command is as specified in the figure above. The

last syntax of the DELETE command enables you to delete a record in a

database table. In this syntax, define the record to be changed in the WHERE

clause by exactly specifying all the key field evaluations or any other field

combination that uniquely identifies a record of existing data.

A record can also be deleted from database views. However, the database view

must already be created in the ABAP Dictionary with the maintenance status

“read and change” and must only contain fields from a table.

In the syntax DELETE <dbtab> [CLIENT SPECIFIED] FROM <wa>,

the structure <wa> must have the same structure as the records in the respective

database table. Also, before calling the command, the structure must be filled

with the key fields of the record that need to be deleted. However, if <dbtab>

is client-specific and if the CLIENT SPECIFIED addition is specified, the client

field is taken into consideration (otherwise client value of the current logged on

client is taken as the default client).

La sintaxis para el comando DELETE es como se especifica en

la figura anterior. La última sintaxis del comando DELETE

permite eliminar un registro de una tabla de base de datos.

En esta sintaxis, definir el registro para ser cambiado en

la cláusula WHERE especificando exactamente todas las

evaluaciones de campo clave o cualquier otra combinación de

campos que identifica un registro de los datos existentes.

Page 14: Database Update Opensql

Un registro también se puede eliminar de vistas de base de

datos. Sin embargo, la vista de la base de datos ya debe estar

creado en el Diccionario ABAP con el estado de mantenimiento

"leer y cambiar" y sólo debe contener los campos de una tabla.

En la sintaxis BORRAR <dbtab> [cliente especificado] FROM

<wa>, la estructura <wa> debe tener la misma estructura que

los registros de la tabla de base de datos correspondiente.

También, antes de llamar el comando, la estructura debe ser

llenado con los campos clave del registro que deben ser

eliminados. Sin embargo, si <dbtab> es específica del cliente

y si se especifica el CLIENTE Además se especifica, el campo

de cliente se tiene en cuenta (en caso contrario el valor del

cliente de la corriente que se conectó el cliente se toma

como el cliente predeterminado).

The syntax variant of the DELETE command that enables you to delete several

records in a database table is as show in the figure above. Here, you can specify

the records that are to be deleted in the WHERE clause.

If you delete several records from a database table, you can specify them first

in an internal table that has the same structure as that of the respective database

table, and then use the above syntax of the DELETE command. You need to

specify the key part of the records to be deleted in the internal table. If the key

Page 15: Database Update Opensql

field mandt exists, then it is used only if the CLIENT SPECIFIED addition is

specified. Otherwise, the client value of the current logged on client is taken as

the default client.

The number of records deleted from the database is shown in the system field

sy-dbcnt.

La variante de la sintaxis del comando DELETE que le permite

eliminar varios registros en una tabla de base de datos es

como se muestra en la figura anterior. Aquí , puede

especificar los registros que se van a eliminar en la cláusula

WHERE.

Si elimina varios registros de una tabla de base de datos ,

puede especificar que por primera vez en una tabla interna

que tiene la misma estructura que la de la tabla de base de

datos correspondiente , y luego usar la sintaxis anterior del

comando DELETE . Es necesario especificar la parte clave de

los registros que desea eliminar en la tabla interna . Si

existe el Mandt campo clave , entonces sólo se utiliza si se

especifica la adición cliente especificado . De lo contrario

, el valor para el cliente de la corriente que se conectó el

cliente se toma como el cliente predeterminado .

El número de registros borrados de la base de datos se muestra

en el campo del sistema sy- dbcnt .

Page 16: Database Update Opensql

If an Open SQL statement that implements a change to the database receives a

return code different than zero, then ensure that the database is reset to the same

status as the status before you attempted to implement the change. To reset the

database, perform a database rollback, which reverses all changes to the current

database LUW (Logical Unit of Work).

There are two ways to cause a database rollback, they are as follows:

Send a termination dialog message with message type A or X

Use the ROLLBACK WORK ABAP statement

The transmission of an A or X Message causes a database rollback and

terminates the program. All other message types (E, W, and I) involve a dialog

but do not trigger a database rollback.

The ABAP statement ROLLBACK WORK causes a database rollback without

terminating the program. In this case, the context is not reset in the current

program.

Si una instrucción Open SQL que implementa un cambio en la

base de datos recibe un código de retorno distinto de cero,

a continuación, asegurar que la base de datos se restablece

en el mismo estado que el estado antes de intentar implementar

el cambio . Para restablecer la base de datos , lleve a cabo

una operación de deshacer la base de datos , lo que revierte

todos los cambios a la base de datos actual LUW ( Unidad

lógica de trabajo ) .

Page 17: Database Update Opensql

Hay dos formas de provocar una reversión base de datos, que

son los siguientes :

Enviar un mensaje de diálogo con terminación tipo de

mensaje A o X

Utilice la sentencia ABAP TRABAJO ROLLBACK

La transmisión de una A o X Mensaje provoca una reversión de

la base de datos y termina el programa. Todos los demás tipos

de mensajes (E , W , y I) implican un diálogo , pero no

activan una reversión de base de datos .

El TRABAJO instrucción ROLLBACK ABAP provoca un retroceso de

base de datos sin necesidad de terminar el programa. En este

caso, el contexto no se restablece en el programa actual .

Page 18: Database Update Opensql