Sie sind auf Seite 1von 80

ABAP workshop

Database Access and Updates

Open SQL & Native SQL


ABAP lets you access the database in two ways
Open SQL Native SQL

Open SQL allows you to access database tables declared in the ABAP Dictionary regardless of the database platform that you R/3 System is using Native SQL allows you to use database-specific SQL statements in an ABAP program. This means that you can use database tables that are not administered by the ABAP Dictionary, and therefore integrate data that is not part of the R/3 System
2

Database Access

As a rule, an ABAP program containing database-specific SQL statements will not run under different database systems. If your program will be used on more than one database platform or think you may probably change the database in the future and wish to leave it portable, use only Open SQL statements.

Open SQL
Open SQL consists of a set of ABAP statements that perform operations on the central database The results of the operations and any error messages are independent of the database system in use 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 having to adjust it Open SQL thus provides a uniform syntax and semantics for all of the database systems supported by SAP Note that Open SQL commands do not perform any automatic authorization checks. You need to execute these explicitly in your program using Authorization Checks

Open SQL
Open SQL statements can only work with database tables that have been created in the ABAP Dictionary Open SQL supports Buffering SAP tables locally on the application server for quicker read access. This also means that the database load is reduced. The data is read from the buffer automatically after the respective table settings have been made The buffered tables are accessed exclusively via database interface mechanisms The Open SQL set of commands only comprises operations for Data Manipulation Language (DML), not for Data Definition Language (DDL) since these are integrated in the ABAP Dictionary
5

Open SQL Keywords


Open SQL contains the following keywords: Keyword Function SELECT Reads data from database tables INSERT Adds lines to database tables UPDATE Changes the contents of lines of database tables MODIFY Inserts rows into database tables or updates existing lines if they exists with same key DELETE Deletes lines from database tables OPEN CURSOR Opens database cursor to read one line at a time from database FETCH Reads lines of database tables using the cursor CLOSE CURSOR Opens database cursor to read one line at a time from database
6

Open SQL Return Codes


Return Codes All Open SQL statements update the following to system variables: SY-SUBRC: After every Open SQL statement, this system field contains the value 0 if the operation was successful, a value other than 0 if not SY-DBCNT: After an open SQL statement, this system field contains the number of database lines processed

For updates, if at least one line is changed, the system sets SY-SUBRC to 0, otherwise to 4. SY-DBCNT contains the number of lines updated.
7

Client Handling
The first column in the structure of every database table containing application data is the client field (MANDT, from the German word for client) MANDT is also the first field of the table key Only universal (common) system tables are client-independent, and do not contain a client name (MANDT does not exist)
8

Client Handling (continued)


SAP can manage the application data for several separate areas of a business (branches, subsidiaries, etc) Each of these commercially separate areas in the SAP System is called a client, and is represented by a number When an user logs onto an SAP System, they specify a client (example: 100)
9

Client Handling (continued)


By default, Open SQL statements use automatic client handling Statements that access client-dependent application tables only use the data from the current client and do not need the client condition in the where clause You cannot specify a condition for the client field in the WHERE clause of an Open SQL statement [unless using CLIENT SPECIFIED see next slide] If you do so, the system will either return an error during the syntax check or a runtime error will occur
10

Client Handling (continued)


You cannot overwrite the MANDT field of a database using Open SQL statements. If you specify a different client in a work area, the ABAP runtime environment automatically overwrites it with the current one before processing the Open SQL statement further Should you need to specify the client specifically in an Open SQL statement, use the addition ... CLIENT SPECIFIED .... directly after the name of the database table This addition disables the automatic client handling and you can use the field MANDT both in the WHERE clause and in a table work area An Open SQL command accesses ALL clients if it contains the addition CLIENT SPECIFIED without a client specification

SELECT * FROM SPFLI CLIENT SPECIFIED into TABLE gt_flights where client = sy-mandt [or client = 100]

11

Native SQL
To use a Native SQL statement, you must precede it with the EXEC SQL statement, and follow it with the ENDEXEC statement as follows: EXEC SQL [PERFORMING <form>]. <Native SQL statement> ENDEXEC.

12

Native SQL
There is no period after Native SQL statements. Furthermore, using inverted commas (") or an asterisk (*) at the beginning of a line in a native SQL statement does not introduce a comment as it would in normal ABAP syntax. You need to know whether table and field names are case-sensitive in your chosen database In Native SQL statements, the data is transported between the database table and the ABAP program using host variables. These are declared in the ABAP program, and preceded in the Native SQL statement by a colon (:). You can use elementary structures as host variables. Exceptionally, structures in an INTO clause are treated as though all of their fields were listed individually If the selection in a Native SQL SELECT statement is a table, you can pass it to ABAP line by line using the PERFORMING addition. The program calls a subroutine <form> for each line read. You can process the data further within the subroutine

13

Native SQL (example)


*&---------------------------------------------------------------------* *& Report Z_NATIVESQLEXAMPLE1 *& For illustration only AVOID using this in your *& ABAP programming unless accessing an external *& table *&---------------------------------------------------------------------* REPORT Z_NATIVESQLEXAMPLE1. DATA: BEGIN OF wa, connid TYPE spfli-connid, cityfrom TYPE spfli-cityfrom, cityto TYPE spfli-cityto, END OF wa. DATA c1 TYPE spfli-carrid VALUE 'LH'. EXEC SQL PERFORMING loop_output. SELECT connid, cityfrom, cityto INTO :wa FROM spfli WHERE carrid = :c1 ENDEXEC. FORM loop_output. WRITE: / wa-connid, wa-cityfrom, wa-cityto. ENDFORM. 14

Native SQL why try to avoid it


Native SQL statements bypass the SAP database interface There is no table logging, and no synchronization with the database buffer on the application server For this reason, you should, wherever possible, use Open SQL to change database tables declared in the ABAP Dictionary In particular, tables declared in the ABAP Dictionary that contain long columns with the types LCHR or LRAW should only be addressed using Open SQL, since the columns contain extra, database-specific length information for the column Native SQL does not take this information into account, and may therefore produce incorrect results Furthermore, Native SQL does not support automatic client handling. Instead, you must treat client fields like any other You should implement database accesses using Native SQL only if a particular Native SQL function that is not available in Open SQL must be used
15

Internal Table in ABAP


Internal tables provide a means of taking data from a fixed structure and storing it in working memory in ABAP The data is stored line by line in memory, and each line has the same structure. In ABAP, internal tables fulfill the function of arrays Since they are dynamic data objects, the programmer is saved the task of dynamic memory management in his or her programs Internal tables should be used whenever there is a need to process a dataset with a fixed structure within a program
16

Internal Table in ABAP (continued)


A particularly important use for internal tables is for storing and formatting data from a database table within a program. They are also a good way of including very complicated data structures in an ABAP program. Another very important use is to temporary copy users updates done on any DYNPRO screen to it (an internal table,) before finally updating the actual database tables [although they are not saved to the database, they are good tools for holding, processing, manipulating, filtering, and finally updating the data to the database tables, hence we are discussing internal tables here] Like all elements in the ABAP type concept, internal tables can exist both as data types and as data objects A data type is the abstract description of an internal table, either in a program or centrally in the ABAP Dictionary, that you use to create a concrete data object. The data type is also an attribute of an existing data object
17

Internal Table in ABAP (continued)


* Table declaration (old method) DATA: BEGIN OF tab_ekpo OCCURS 0, ebeln TYPE ekpo-ebeln, ebelp TYPE ekpo-ebelp, END OF tab_ekpo. "itab with header line

*Table declaration (new method) "USE THIS WAY!!! TYPES: BEGIN OF t_ekpo, ebeln TYPE ekpo-ebeln, ebelp TYPE ekpo-ebelp, END OF t_ekpo. DATA: it_ekpo TYPE STANDARD TABLE OF t_ekpo INITIAL SIZE 0, wa_ekpo TYPE t_ekpo. "itab "work area
18

Internal Table in ABAP (continued)


* Build internal table and work area from existing internal table DATA: it_datatab LIKE tab_ekpo OCCURS 0, "old method wa_datatab LIKE LINE OF tab_ekpo. * Build internal table and work area from existing internal table, * adding additional fields TYPES: BEGIN OF t_repdata. INCLUDE STRUCTURE tab_ekpo. "could include EKKO table itself!! TYPES: bukrs TYPE ekpo-werks, bstyp TYPE ekpo-bukrs. TYPES: END OF t_repdata. DATA: it_repdata TYPE STANDARD TABLE OF t_repdata INITIAL SIZE 0, "itab wa_repdata TYPE t_repdata. "work area
19

Internal Table Examples


REPORT Z_COPY_INTERNAL_TBLA. DATA itab_stravelag LIKE STANDARD TABLE OF stravelag WITH NON-UNIQUE KEY agencynum. DATA wa_stravelag TYPE stravelag. START-OF-SELECTION. SELECT * FROM stravelag INTO TABLE itab_stravelag where agencynum in ('00000055', '00000061', '00000087', '00000093'). LOOP AT itab_stravelag INTO wa_stravelag. WRITE: / 'wa_stravelag-MANDT = ', wa_stravelag-MANDT. WRITE: / 'wa_stravelag-AGENCYNUM = ', wa_stravelag-AGENCYNUM. WRITE: / 'wa_stravelag-NAME = ', wa_stravelag-NAME. WRITE: / 'wa_stravelag-STREET = ', wa_stravelag-STREET. ENDLOOP.
20

Internal Table Examples


REPORT Z_COPY_INTERNAL_TBLB. TYPES: BEGIN OF stravel_type. INCLUDE STRUCTURE stravelag. TYPES: mark_changed(1) type c, END OF stravel_type. DATA: itab_travel TYPE STANDARD TABLE OF stravel_type WITH NON-UNIQUE KEY agencynum, wa_travel TYPE stravel_type. START-OF-SELECTION. SELECT * FROM stravelag INTO CORRESPONDING FIELDS OF TABLE itab_travel where agencynum in ('00000055', '00000061', '00000087', '00000093'). LOOP AT itab_travel INTO wa_travel. WRITE: / 'wa_travel-MANDT = ', wa_travel-MANDT. WRITE: / 'wa_travel-AGENCYNUM = ', wa_travel-AGENCYNUM. WRITE: / 'wa_travel-NAME = ', wa_travel-NAME. WRITE: / 'wa_travel-mark_changed = ', wa_travel-mark_changed. ENDLOOP.
21

Internal Table Examples


REPORT Z_COPY_INTERNAL_TBLC. TYPES: BEGIN OF stravel_type. INCLUDE STRUCTURE stravelag. TYPES: mark_changed(1) type c, END OF stravel_type. DATA: itab_travel TYPE STANDARD TABLE OF stravel_type WITH NON-UNIQUE KEY agencynum, wa_travel TYPE stravel_type. DATA: itab_stravelag LIKE STANDARD TABLE OF stravelag WITH NON-UNIQUE KEY agencynum, wa_stravelag TYPE stravelag. START-OF-SELECTION. SELECT * FROM stravelag INTO TABLE itab_stravelag where agencynum in ('00000055', '00000061', '00000087', '00000093'). LOOP AT itab_stravelag INTO wa_stravelag. MOVE-CORRESPONDING wa_stravelag to wa_travel. wa_travel-mark_changed = 'X'. APPEND wa_travel to itab_travel. ENDLOOP. LOOP AT itab_travel INTO wa_travel. WRITE: / 'wa_travel-MANDT = ', wa_travel-MANDT. WRITE: / 'wa_travel-AGENCYNUM = ', wa_travel-AGENCYNUM. WRITE: / 'wa_travel-NAME = ', wa_travel-NAME. WRITE: / 'wa_travel-mark_changed = ', wa_travel-mark_changed. ENDLOOP.

22

Using Header Lines as Work Areas


When you create an internal table object you can also declare a header line with the same name. You can use the header line as a work area when you process the internal table.
Example: DATA ITAB TYPE HASHED TABLE OF LINE WITH UNIQUE KEY COL1 WITH HEADER LINE.
Operations without header line INSERT <wa> INTO TABLE <itab>. READ TABLE <itab> ... INTO <wa>. MODIFY TABLE <itab> FROM <wa> ... DELETE TABLE <itab> FROM <wa>. LOOP AT ITAB INTO <wa> ... For index tables APPEND <wa> TO <itab>. INSERT <wa> INTO <itab> ... MODIFY <itab> FROM <wa> ... APPEND <itab>. INSERT <itab> ... MODIFY <itab> ... Operations with header line INSERT TABLE ITAB. READ TABLE <itab> ... MODIFY TABLE <itab> ... DELETE TABLE <itab>. LOOP AT ITAB ...

Header

Table
To define the header line (header work area) with the same name as a database table (unlike internal table,) declare this table work area using the TABLES statement. Table work areas with the same name as the database table (necessary before Release 4.0) should no longer be used for the sake of clarity.

23

Internal Table with Header Line


REPORT Z_INTERNAL_TBL_W_HDR. TYPES: BEGIN OF LINE, COL1 TYPE I, COL2 TYPE I, END OF LINE. DATA ITAB TYPE HASHED TABLE OF LINE WITH UNIQUE KEY COL1 WITH HEADER LINE. DO 4 TIMES. ITAB-COL1 = SY-INDEX. ITAB-COL2 = SY-INDEX ** 2. INSERT TABLE ITAB. ENDDO. ITAB-COL1 = 2. READ TABLE ITAB FROM ITAB. ITAB-COL2 = 100. MODIFY TABLE ITAB. ITAB-COL1 = 4. DELETE TABLE ITAB. LOOP AT ITAB. WRITE: / ITAB-COL1, ITAB-COL2. ENDLOOP.

24

Internal Table without Header Line


REPORT Z_INTERNAL_TBL_WOUT_HDR TYPES: BEGIN OF LINE, COL1 TYPE I, COL2 TYPE I, END OF LINE. DATA: ITAB TYPE HASHED TABLE OF LINE WITH UNIQUE KEY COL1, WA LIKE LINE OF ITAB. DO 4 TIMES. WA-COL1 = SY-INDEX. WA-COL2 = SY-INDEX ** 2. INSERT WA INTO TABLE ITAB. ENDDO. WA-COL1 = 2. READ TABLE ITAB FROM WA INTO WA. WA-COL2 = 100. MODIFY TABLE ITAB FROM WA. WA-COL1 = 4. DELETE TABLE ITAB FROM WA. LOOP AT ITAB INTO WA. WRITE: / WA-COL1, WA-COL2. ENDLOOP.
25

Accessing Rows from Internal Table


REPORT Z_COPY_INTERNAL_TBLE. TYPES: BEGIN OF LINE, ZC1(25) TYPE c, ZC3(25) TYPE c, END OF LINE. DATA ITAB_ZMYTABLE TYPE STANDARD TABLE OF LINE WITH NON-UNIQUE KEY ZC1. DATA WA_ZMYTABLE TYPE LINE. * or if there is an exisiting database table *DATA ITAB_ZMYTABLE LIKE STANDARD TABLE OF ZMYTABLE *WITH NON-UNIQUE KEY ZC1. *DATA WA_ZMYTABLE TYPE ZMYTABLE. START-OF-SELECTION. WA_ZMYTABLE-ZC1 = 'MIAMI'. WA_ZMYTABLE-ZC3 = 'MIAMI DESCR'. APPEND WA_ZMYTABLE TO ITAB_ZMYTABLE. WA_ZMYTABLE-ZC1 = 'WASHINGTON DC'. WA_ZMYTABLE-ZC3 = 'WASHINGTON DC DESCR'. APPEND WA_ZMYTABLE TO ITAB_ZMYTABLE. WA_ZMYTABLE-ZC1 = 'SAN FRANCISCO'. WA_ZMYTABLE-ZC3 = 'SAN FRANCISCO DESCR'. APPEND WA_ZMYTABLE TO ITAB_ZMYTABLE. WA_ZMYTABLE-ZC1 = 'CHICAGO'. WA_ZMYTABLE-ZC3 = 'CHICAGO DESCR'. APPEND WA_ZMYTABLE TO ITAB_ZMYTABLE. WA_ZMYTABLE-ZC1 = 'DALLAS'. WA_ZMYTABLE-ZC3 = 'DALLAS DESCR'. APPEND WA_ZMYTABLE TO ITAB_ZMYTABLE. LOOP AT ITAB_ZMYTABLE INTO WA_ZMYTABLE. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3. ENDLOOP. WRITE: /,/.

Note: complete program listing is shown so that you may copy and paste and run the program. Continued to next page

26

Accessing Rows from Internal Table (continued)


* Accessing one record LOOP AT ITAB_ZMYTABLE INTO WA_ZMYTABLE. "This is not efficient IF WA_ZMYTABLE-ZC1 = 'DALLAS'. EXIT. ENDIF. ENDLOOP. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3. * Accessing one record WA_ZMYTABLE-ZC1 = 'CHICAGO'. READ TABLE ITAB_ZMYTABLE FROM WA_ZMYTABLE INTO WA_ZMYTABLE. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3. * Accessing one record READ TABLE ITAB_ZMYTABLE INTO WA_ZMYTABLE WITH TABLE KEY ZC1 = 'S AN FRANCISCO'. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3.
27

Accessing Rows from Internal Table (continued)


* Accessing one record (index 1 is the first record, * index 2 the second record, etc) READ TABLE ITAB_ZMYTABLE INTO WA_ZMYTABLE INDEX 1. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3. WRITE: /,/. LOOP AT ITAB_ZMYTABLE INTO: WA_ZMYTABLE. WRITE: / 'WA_ZMYTABLE-ZC1 = ', WA_ZMYTABLE-ZC1. WRITE: / 'WA_ZMYTABLE-ZC3 = ', WA_ZMYTABLE-ZC3. ENDLOOP.

28

Updating Rows from Internal Table


* First accessing one record from internal table to work area LOOP AT ITAB_ZMYTABLE INTO WA_ZMYTABLE. "This is not efficient IF WA_ZMYTABLE-ZC1 = 'DALLAS'. EXIT. ENDIF. ENDLOOP. * Then updating the work area *WA_ZMYTABLE-ZC3 = 'New Updated Value'. CONCATENATE WA_ZMYTABLE-ZC3 ' - Updated' into WA_ZMYTABLE-ZC3. * Finally updating the internal table MODIFY TABLE ITAB_ZMYTABLE from WA_ZMYTABLE. * First accessing one record from internal table to work area WA_ZMYTABLE-ZC1 = 'CHICAGO'. READ TABLE ITAB_ZMYTABLE FROM WA_ZMYTABLE INTO WA_ZMYTABLE. * Then updating the work area WA_ZMYTABLE-ZC3 = 'New Updated Value'. * Finally updating the internal table MODIFY TABLE ITAB_ZMYTABLE from WA_ZMYTABLE.
29

Updating Rows from Internal Table (continued)


* First accessing one record from internal table to work area READ TABLE ITAB_ZMYTABLE INTO WA_ZMYTABLE WITH TABLE KEY ZC1 = 'SAN FRANCISCO'. * Then updating the work area WA_ZMYTABLE-ZC3 = 'New Updated Value'. * Finally updating the internal table MODIFY TABLE ITAB_ZMYTABLE from WA_ZMYTABLE. * Accessing one record (index 1 is the first record, 2 the second record, etc) READ TABLE ITAB_ZMYTABLE INTO WA_ZMYTABLE INDEX 1. * Then updating the work area WA_ZMYTABLE-ZC3 = 'New Updated Value'. * Finally updating the internal table MODIFY TABLE ITAB_ZMYTABLE from WA_ZMYTABLE.

30

Deleting from Internal Table


LOOP AT ITAB_ZMYTABLE INTO WA_ZMYTABLE. IF WA_ZMYTABLE-ZC1 = 'DALLAS'. DELETE ITAB_ZMYTABLE. "Deleting data only from internal table. ENDIF. ENDLOOP. DELETE ITAB_ZMYTABLE WHERE ( ZC1 = 'CHICAGO' OR ZC1 = 'OTHERCITY' ). WA_ZMYTABLE-ZC1 = 'HOUSTON'. DELETE TABLE ITAB_ZMYTABLE from WA_ZMYTABLE. DELETE TABLE ITAB_ZMYTABLE WITH TABLE KEY ZC1 = 'SAN FRANCISCO'. * Or combine the above two using one command (using the semi colon): DELETE TABLE ITAB_ZMYTABLE: from WA_ZMYTABLE, WITH TABLE KEY ZC1 = 'SAN FRANCISCO'. * Deleting using the line number (here index) DELETE ITAB_ZMYTABLE INDEX 2. * or both line 1 and 2 DELETE ITAB_ZMYTABLE INDEX: 2, 1. * order matters - if there are only say 2 lines in the internal table DELETE ITAB_ZMYTABLE INDEX: 1, 2.

31

Creating a Single Record

To insert a new row in a database table, enter the command. INSERT INTO <dbtab> VALUES <wa>... For this purpose, you must place the line to be inserted in the structure <wa> before the command is called Alternative syntax : INSERT <dbtab> [CLIENT SPECIFIED] FROM <wa>.
32

Creating a Multiple Records

You can use the command INSERT <dbtab> FROM TABLE <itab>. to create several rows in a database table. The internal table <itab> that you should specify here must have the same line structure as the corresponding databse table and the new data records (multiple records.)
33

Creating a Multiple Records (continued)


The client field that may possibly exist in the internal Table <itab> will only be taken into consideration if the CLIENT SPECIFIED addition is specified. If there is no CLIENT SPECIFIED addition, the current execution client applies If it is possible to create all the lines, sy-subrc is automatically set to zero If, however, even one data record cannot be created, the system triggers a runtime error. This means that the entire insertion operation is discarded (database rollback) If, in such a case, you wish to have records that can be inserted actually inserted, use the command addition ACCEPTING DUPLICATE KEYS. This addition has the effect that, if there is an error, the runtime error (and thus also the database rollback) is suppressed, sy-subrc is set to 4, and all the records without errors are inserted The sy-dbcnt system field contains the number of rows that were successfully inserted in the database
34

Changing a Single Record

1) The database record that contains the key in <wa> is overwritten by <wa>. However, the key field MANDT that may possibly exist in <wa> is only taken into consideration if the CLIENT SPECIFIED addition is specified as well (otherwise the current execution client applies) 2) The record specified in the WHERE clause is changed. However, only the fields specified in the SET addition are overwritten on the database side with the values specified. In this syntax version, you must define the record to be changed in the WHERE clause by exactly specifying all the key field evaluations.
35

Changing Several Records

You can perform a mass data change by specifying an internal table that has the same structure as the corresponding database table and the records to be changed The contents of the internal table <itab> overwrite the lines in the database table <dbtab> that have the same primary keys. This UPDATE variant [sy-subrc] has the following return codes: 0: All the specified lines were changed successfully 4: At least one of the specified lines could not be changed (because, for example, it does not exist); the other lines were changed
36

Changing Several Records (Example)


FORM save_changes. * declare internal table and workarea of same linetype as DB table DATA: itab TYPE STANDARD TABLE OF stravelag, wa LIKE LINE OF itab. * search for datasets changed on the screen populate itab happens 4th LOOP AT itab_travel INTO wa_travel WHERE mark_changed = 'X'. MOVE-CORRESPONDING wa_travel TO wa. fill workarea APPEND wa TO itab. fill corresponding internal table ENDLOOP. * mass update on stravelag -> best performance UPDATE stravelag FROM TABLE itab. actual db update using itab * check success happens 5th IF sy-subrc = 0. all datasets are successfully updated MESSAGE s030. ELSE. at least one dataset from the internal table could not be updated MESSAGE i048. ENDIF. ENDFORM. See itab_travel, itab and stravelag being used here
37

Changing Several Records (Example)


* Populate DNYPRO fields [in TC_STRAVELAG table control] from itab_travel happens 2nd

PROCESS BEFORE OUTPUT. MODULE STATUS_0100. * fill table control (only agencies, marked on list) LOOP AT ITAB_TRAVEL INTO WA_TRAVEL WITH CONTROL TC_STRAVELAG. MODULE TRANS_TO_DYNPRO. ENDLOOP. * * Populate mark_changed flag if any fields changed happens 3rd PROCESS AFTER INPUT. MODULE EXIT AT EXIT-COMMAND. LOOP AT ITAB_TRAVEL. CHAIN. FIELD: STRAVELAG-STREET, STRAVELAG-POSTBOX, STRAVELAGPOSTCODE, STRAVELAG-CITY, STRAVELAG-COUNTRY, STRAVELAG-REGION, STRAVELAG-TELEPHONE, STRAVELAG-URL, STRAVELAG-LANGU. * mark datasets, that were changed in table control (subset of all * agencies, thet were shown on table control) MODULE SET_MARKER ON CHAIN-REQUEST. ENDCHAIN. ENDLOOP. MODULE SAVE_OK_CODE. MODULE USER_COMMAND_0100.
38

Changing Several Records (Example)


MODULE trans_to_dynpro OUTPUT. * Field transport to screen MOVE-CORRESPONDING wa_travel TO stravelag. ENDMODULE. " TRANS_TO_DYNPRO OUTPUT MODULE set_marker INPUT. MOVE-CORRESPONDING stravelag TO wa_travel. wa_travel-mark_changed = 'X'. * mark datasets in internal table as modified MODIFY TABLE itab_travel FROM wa_travel. * at least one dataset is modified in table control flag = 'X'. ENDMODULE. " SET_MARKER INPUT

39

Changing Several Records (Example)


Populating itab_travel based on user selection (happens 1st)

AT USER-COMMAND. CLEAR: modify_list, flag, itab_travel. * Collect data corresponding to marked lines into internal table PERFORM loop_at_list USING itab_travel. FORM loop_at_list USING p_itab_travel LIKE itab_travel. DO. CLEAR: mark. READ LINE sy-index FIELD VALUE mark. IF sy-subrc <> 0. EXIT. ENDIF. CHECK NOT mark IS INITIAL. APPEND wa_stravelag TO p_itab_travel. ENDDO. ENDFORM.
40

Modifying Single Record / Several Records

The MODIFY command is SAP-specific. It covers the two commands UPDATE and INSERT : 1) If the data record specified in the MODIFY statement exists, this record is updated ( UPDATE ). 2) If the data record specified in the MODIFY statement does not exist, this record is inserted ( INSERT ).
41

Deleting a Single Record (using where conditions)

The syntax specified above for the DELETE command enables you to delete a single row in a database table. If sy-subrc is 0, implies the row was deleted. If sy-subrc is 4, implies the row could not be deleted because, for example, it does not exist in the database. Alternative syntax : DELETE <dbtab> [CLIENT SPECIFIED] FROM <wa>.
42

Deleting Several Records (using where conditions)

This syntax variant of the DELETE command enables you to delete several lines in a database table. Here, you can specify the lines that are to be deleted in the WHERE clause.
43

Deleting Several Records (using internal table)

If you wish to delete several records from a database table, you can specify them first in an internal table that has the same structure as the respective database table and then use the above syntax of the DELETE command. To do so, all you need to do is specify the key part of the records to be deleted in the internal table (that is non-key fields in the itab can be blank or can have any unrelated or blank data) 44

Specifying Table Dynamically


To specify the database table statically, enter the following for <target>: UPDATE <dbtab> [CLIENT SPECIFIED] <lines>. where <dbtab> is the name of a database table defined in the ABAP Dictionary To specify the database table dynamically, enter the following for <target>: UPDATE (<name>) [CLIENT SPECIFIED] <lines>. where the field <name> contains the name of a database table defined in the ABAP Dictionary
45

Specifying Table Dynamically


(continued)
If you use SET statements, you cannot specify the database table dynamically UPDATE <dbtab> SET <set1> <set 2> ... [WHERE <cond>]. If at least one line is changed, the system sets SY-SUBRC to 0, otherwise to 4. SY-DBCNT contains the number of lines changed Whenever you want to overwrite more than one line in a database table, it is more efficient to work with an internal table than to change the lines one by one
46

ROLLBACK WORK
If an Open SQL statement that executes a change to the database returns a return code different than zero, you should make sure that the database is returned to the same status as before you attempted to make the respective change. You achieve this by performing a rollback, which reverses all changes made There are two ways of causing a database rollback:
Sending a termination dialog message (A-Message) Using the ROLLBACK WORK ABAP statement

The transmission of an A Message causes a database rollback and terminates the program. All other message types (E, W, I) also involve a dialog but do not trigger a database rollback The ABAP statement ROLLBACK WORK, on the other hand, causes a database rollback without terminating the program. In this case, you should be careful since the context has not been reset in the current program

47

Number Range Object/Buffer


In any Organization applications like invoice generation, reimbursement or Expense payment, etc. needs auto generated number for reference, which is done through a Number Range object. The creation and the implementation of Number Range Object based on the Employee's Company code and the current Year For example: In an Invoice creation, number range is the one which refer to unique invoice. This is vital to identify the specific invoice. The custom define Number Range Object can be create in the Transaction Code SNRO and the object has to be called in program with the help of a Function Module NUMBER_GET_NEXT
48

Number Range Object (continued)


When creating a new application, we have the option of creating a new Number Range Object if the existing ones are do not satisfy the requirements of the new one or are completely unrelated For example, if we already have a Number Range Object for creating unique IDs for say Invoices, it may not be appropriate to use the same Object for creating say Unique IDs for say Customer numbers
49

Number Range Object (continued)


Use Transaction Code SNRO to create and maintain new Number Range Object

50

Number Range Object (continued)


The number range is usually setup by the functional power users using the same Transaction SNRO

51

Number Range Object (continued)


The graphic below shows the process flow and the components involved. WP1 instructs a second process (WP2) to fetch from table NRIV in the database as many numbers as are configured in the number range object maintenance (SNRO) under No. of Numbers in Buffer. For this time period WP1 is assigned status stop in the Work Process Overview (SM50) with reason for stopping, NUM. Under detail info for WP2 you can see which number range interval the work process wants to assign numbers to. Before WP2 issues numbers to the first work process, the assigned numbers are immediately written to the database (COMMIT). This has the disadvantage that all the buffered numbers from the interval are lost if the server shuts down.

52

Number Range Object (continued)


The number range buffer proceeds as follows:
It checks whether it already has an area in the buffer for the number range interval required and whether this area is not yet full. If both conditions are satisfied, the current number level in the buffer is increased by the required number and the caller notified of the assigned numbers. Immediately afterwards a new process can assign a number from the same interval. If there is a rollback, the numbers are lost they are not returned to the buffer. If there is a rollback, it creates a gap in the document numbers. Applications that do not want any gaps (or not allowed gaps for legal reasons) should not use the number range buffer.
53

Number Range Object (if gaps are OK)


The underlying table is NRIV, but never access that table directly, instead use a standard SAP function to access the next unique number in the range for any number range object (example: SBUSPID) CALL FUNCTION 'NUMBER_GET_NEXT' EXPORTING nr_range_nr = '01' object = 'SBUSPID' IMPORTING number = p_scustom-id returncode = return EXCEPTIONS OTHERS = 1. CASE sy-subrc. WHEN 0. CASE return. WHEN 1. * number of remaining numbers critical MESSAGE s070. WHEN 2. * last number MESSAGE s071. WHEN 3. * no free number left over MESSAGE a072. ENDCASE. WHEN 1. * internal error MESSAGE a073 WITH sy-subrc. ENDCASE.
54

Number Range Object (if no gaps are acceptable)


Function module NUMBER_GET_NEXT offers you the option of ignoring the buffer if you so desire (interface parameter IGNORE_BUFFER when calling the 'NUMBER_GET_NEXT function) and setting the No. of Numbers in buffer to 0 (Zero) in transaction code SNRO. The data for number ranges is stored in table NRIV. In this table, an entry exists for each individual number range. If a number range object has not been buffered, the system must read directly from the database each time new numbers are assigned. This leads to the corresponding number range being locked until completion of the current LUW. The advantages of non-buffered access are 1) number assignment without gaps 2) chronological sequence of numbers In the function module NUMBER_GET_NEXT, the statement SELECT SINGLE ... FOR UPDATE is used to access table NRIV. This locks the relevant table entry in the database until completion of the current LUW. Disadvantage: This can lead to considerable waiting time when multiple programs request numbers from the same number range. CALL FUNCTION 'NUMBER_GET_NEXT' EXPORTING nr_range_nr = '01' object = 'SBUSPID' ignore buffer = X IMPORTING
55

Message Class
Creating Exception Class and message number messages Note: the Exception Class is not a class in sense of object orientation, but is a group or class of messages] 1) Use the Transaction code - SE91 2) Top menu Goto > Messages while in Object navigator with any program opened 3) Use when in a Package, right click and use the following menu Create > Other(1) > Message Class

56

Message Class (continued)


SE91

57

Message Class (continued)


To create a new message class from the ABAP Editor: In the initial statement (for example, REPORT) or directly in the statement MESSAGE ID <id> enter a parameter value of up to 20 characters as a message ID, for example: REPORT <name> MESSAGE-ID <message class>.Messages are stored systemwide. The chosen message ID (message class) must not already exist in the system. Double-click the message ID. If you enter an ID that already exists in the system, the system calls up Message maintenance. In this case, enter a different ID. Once you have done this, the system asks you whether you want to create a new message class. Choose Yes. The system calls up Message maintenance. Enter a brief description of the class in Short text. Choose Save.

58

Message Class (continued)


Example: IF sy-subrc = 0. all datasets are successfully updated MESSAGE s030. ELSE. at least one dataset from the internal table could not be updated MESSAGE i048. ENDIF. Messages of the type S, I, or W are not sent but are noted in the log ( this is for background processing.) Messages of the type E and A trigger the exception error_message and set sy-subrc to n_error. The message class, message type, message number, and the contents of possible placeholders for the MESSAGE statement are in the fields sy-msgid, symsgno, sy-msgty, and sy-msgv1, ... , sy-msgv4. With messages of the type A, the ROLLBACK WORK statement is also explicitly executed. For information about the behavior in background processing, see Messages in Background Processing. Messages of the type X are not influenced. As always, they cause program termination with a short dump.
59

Message Class (continued)


There are two ways to specify Message Class in a program 1) Use MESSAGE-ID on the REPORT command (definition) REPORT bc402_cps_checkpoints MESSAGE-ID bc402 Here bc402 is the message class for all the messages in the program - any message in the program will refer to this message class and access the message number (and therefore its message text) IF sy-subrc <> 0. MESSAGE a038. ENDIF. 2) Specify the message class on the message command directly Provide the class on the message command directly (example: SAPBC405_SSCS_2) AT SELECTION-SCREEN. * check country for national flights is not empty CHECK national = 'X' AND country = space. MESSAGE e003(bc405).

60

Message Type
Messages Type A (Abend) Messages Type E (Error) Messages Type W (Warning) Messages Type I (Information) Messages Type S (Success) Messages Type X (Terminate with short dump)
The message is the same, just use the right prefix [A099, E099, W099, etc.] Implication: A, X Rollback E, W, I Commit S None

61

Updating Multiple Rows

62

Updating Multiple Rows (continued)

63

Updating Multiple Rows (continued)

64

Updating Multiple Rows (continued)


Various Tables and Work Areas:

STRAVELAG [Database Table]


STRAVELAG [Work Area on Screen 100 with in the table control]

ITAB_STRAVELAG [Internal Table] List Screen


WA_STRAVELAG [Work Area] P_ITAB_STRAVELAG [Formal Parameter in Procedure]

ITAB_TRAVEL [Internal Table as stravelag + mark_changed


flag] Dynpro Screen 100
WA_TRAVEL [Work Area] P_ITAB_TRAVEL [Formal Parameter in Procedure]

ITAB [Internal Table just as stravelag] Populate just before


database update
WA [Work Area]
65

Updating Multiple Rows (continued)


* Standard internal table for travel agency data buffering and * corresponding workarea DATA: itab_stravelag LIKE STANDARD TABLE OF stravelag WITH NON-UNIQUE KEY agencynum, wa_stravelag TYPE stravelag. * declare internal table and workarea of same linetype as DB table DATA: itab TYPE STANDARD TABLE OF stravelag, wa LIKE LINE OF itab.
66

Updating Multiple Rows (continued)


* Line type definition for internal table itab_travel TYPES: BEGIN OF stravel_type. INCLUDE STRUCTURE stravelag. TYPES: mark_changed, END OF stravel_type. * Internal table to collect marked list entries, corresponding workarea DATA: itab_travel TYPE STANDARD TABLE OF stravel_type WITH NON-UNIQUE KEY agencynum, wa_travel TYPE stravel_type.
67

Updating Multiple Rows (continued)


[A] Populate Internal Table: ITAB_STRAVELAG START-OF-SELECTION. * Read data from STRAVELAG into internal table ITAB_STRAVELAG PERFORM read_data USING itab_stravelag. * Write data from ITAB_STRAVELAG on list PERFORM write_data. FORM read_data USING p_itab_stravelag LIKE itab_stravelag. SELECT * FROM stravelag INTO CORRESPONDING FIELDS OF TABLE p_itab_stravelag. ENDFORM.

68

Updating Multiple Rows (continued)


[B] Display List Values: Loop through the above table and copy values to work area (WA_STRAVELAG) before display, also display additional field CHECKBOX START-OF-SELECTION. * Read data from STRAVELAG into internal table ITAB_STRAVELAG PERFORM read_data USING itab_stravelag. * Write data from ITAB_STRAVELAG on list PERFORM write_data. FORM write_data. LOOP AT itab_stravelag INTO wa_stravelag. WRITE AT: /pos1 mark AS CHECKBOX, pos2 wa_stravelag-agencynum COLOR COL_KEY, pos3 wa_stravelag-name, pos4 wa_stravelag-street, pos5 wa_stravelag-postcode, pos6 wa_stravelag-city, pos7 wa_stravelag-country. HIDE: wa_stravelag. ENDLOOP. ENDFORM. 69

Updating Multiple Rows (continued)


[C] Copy rows from the List display to internal table: ITAB_TRAVEL [only those rows whose field CHECKBOX is selected] AT USER-COMMAND. CLEAR: modify_list, flag, itab_travel. * Collect data corresponding to marked lines into internal table PERFORM loop_at_list USING itab_travel. * Call screen if any line on list was marked CHECK NOT itab_travel IS INITIAL. PERFORM call_screen. * Modify list buffer if database table was modified -> submit report CHECK NOT modify_list IS INITIAL. SUBMIT (sy-cprog). FORM loop_at_list USING p_itab_travel LIKE itab_travel. DO. CLEAR: mark. READ LINE sy-index FIELD VALUE mark. IF sy-subrc <> 0. EXIT. ENDIF. CHECK NOT mark IS INITIAL. APPEND wa_stravelag TO p_itab_travel. ENDDO. ENDFORM.

70

Updating Multiple Rows (continued)


[D] Populate Table Control [TC_STRAVELAG]-Screen 0100 PROCESS BEFORE OUTPUT. MODULE STATUS_0100. * fill table control (only agencies, marked on list) LOOP AT ITAB_TRAVEL INTO WA_TRAVEL WITH CONTROL TC_STRAVELAG. MODULE TRANS_TO_DYNPRO. ENDLOOP. MODULE trans_to_dynpro OUTPUT. * Field transport to screen MOVE-CORRESPONDING wa_travel TO stravelag. ENDMODULE.

71

Updating Multiple Rows (continued)


[E] Mark changed rows by updating the field mark_changed = 'X PROCESS AFTER INPUT. MODULE EXIT AT EXIT-COMMAND. LOOP AT ITAB_TRAVEL. CHAIN. FIELD: STRAVELAG-STREET, STRAVELAG-POSTBOX, STRAVELAG-POSTCODE, STRAVELAG-CITY, STRAVELAGCOUNTRY, STRAVELAG-REGION, STRAVELAG-TELEPHONE, STRAVELAG-URL, STRAVELAG-LANGU. * mark datasets, that were changed in table control (subset of all * agencies, thet were shown on table control) MODULE SET_MARKER ON CHAIN-REQUEST. ENDCHAIN. ENDLOOP. MODULE SAVE_OK_CODE. MODULE USER_COMMAND_0100. MODULE set_marker INPUT. MOVE-CORRESPONDING stravelag TO wa_travel. wa_travel-mark_changed = 'X'. * mark datasets in internal table as modified MODIFY TABLE itab_travel FROM wa_travel. * at least one dataset is modified in table control flag = 'X'. ENDMODULE.

72

Updating Multiple Rows (continued)


[F] Populate Internal Table: ITAB (only with rows that changed) MODULE user_command_0100 INPUT. CASE save_ok. WHEN 'SAVE'. IF flag IS INITIAL. * enries on table control not changed. SET SCREEN 0. ELSE. * at least one field on table control changed PERFORM save_changes. SET SCREEN 0. ENDIF. ENDCASE. ENDMODULE FORM save_changes. * declare internal table and workarea of same linetype as DB table DATA: itab TYPE STANDARD TABLE OF stravelag, wa LIKE LINE OF itab. * search for datasets changed on the screen LOOP AT itab_travel INTO wa_travel WHERE mark_changed = 'X'. * fill workarea fitting to DB table MOVE-CORRESPONDING wa_travel TO wa. * fill corresponding internal table APPEND wa TO itab. ENDLOOP. ENDFORM.

73

Updating Multiple Rows (continued)


[G] Update Database Table: STRAVELAG using internal table ITAB FORM save_changes. * mass update on stravelag -> best performance UPDATE stravelag FROM TABLE itab. * check success IF sy-subrc = 0. * all datasets are successfully updated MESSAGE s030. ELSE. * at least one dataset from the internal table could not be updated on * the database table MESSAGE i048. ENDIF. * Flag: List does not show correct data any more modify_list = 'X'. ENDFORM.

74

Locks Setup

75

SAP Logical Unit of Work (LUW) using Update Modules


The following techniques can be used to implement SAP LUWs
Delayed Subroutines Local updates V1 and V2 Updates

We will focus on Update Modules using V1/V2 updates to implement SAP LUW Create Update Modules [V1/V2 Functions] for all the database updates anticipated for an application in design phase. These will have to be called from the Dynpro.
76

Update Modules

77

Update Modules
Function: UPDATE_SBOOK

78

Update Modules
Function: UPDATE_SBOOK

79

Update Modules
Function: UPDATE_SBOOK_A Since message Type I sends a database commit, therefore subsequent updates (if they happen to have any problems) cannot rollback this update, hence this is no longer considered as one SAP LUW

80

Das könnte Ihnen auch gefallen