ABAP for Beginners - www.sapdocs.info

10,016
-1

Published on

Free Download - http://sapdocs.info/sap/abap/abap-training-course-for-beginners/
A must document for those don't have any experience about ABAP, never seen code..

Published in: Self Improvement, Technology
0 Comments
51 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
10,016
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
51
Embeds 0
No embeds

No notes for slide

ABAP for Beginners - www.sapdocs.info

  1. 1. Accenture 2011 ABAP for beginners Musiari Stefano
  2. 2. 2 Table of Contents 1. Introduction.................................................................................................................................................4 2. How to create a new program ...................................................................................................................5 3. Variables and constants..............................................................................................................................8 3.1 Types of data.......................................................................................................................................8 3.2 Data definition ....................................................................................................................................9 4. Working with strings.................................................................................................................................11 5. WRITE statement ......................................................................................................................................13 5.1 Features.............................................................................................................................................13 4.2 Example.............................................................................................................................................14 6. Control instructions ..................................................................................................................................15 6.1 IF instruction .....................................................................................................................................15 6.2 Case instruction ................................................................................................................................16 7. Loops..........................................................................................................................................................17 7.1 DO/ENDDO........................................................................................................................................17 7.2 LOOP/ENDLOOP................................................................................................................................17 7.3 WHILE/ENDWHILE ............................................................................................................................18 8. Tables.........................................................................................................................................................19 8.1 Internal tables...................................................................................................................................19 8.2 Database tables.................................................................................................................................23 8.3 Example.............................................................................................................................................26 9. Parameters and Selection-Screen............................................................................................................29 9.1 Parameters........................................................................................................................................29 9.2 Select-options ...................................................................................................................................31 9.3 Selection-screen................................................................................................................................33 9.4 Example.............................................................................................................................................36 10. Form and functions...................................................................................................................................39 10.1 Forms.................................................................................................................................................39 10.2 Functions...........................................................................................................................................41 11. Error messages..........................................................................................................................................42 12. OUTPUT......................................................................................................................................................44 12.1 Simple view .......................................................................................................................................44
  3. 3. 3 12.2 ALV view............................................................................................................................................47 12.3 ALV view in POPUP ...........................................................................................................................51 13. File..............................................................................................................................................................55 13.1 Declaration........................................................................................................................................55 13.2 Upload a file from UNIX....................................................................................................................56 13.3 Upload a file from DOS.....................................................................................................................57 13.4 Download a file in UNIX....................................................................................................................63 13.5 Download a file in DOS.....................................................................................................................64 14. ABAP Debugger .........................................................................................................................................66
  4. 4. 4 1. Introduction I started to work in Accenture about two years ago and I didn’t know anything about Sap or ABAP, so I started to read some manuals that I found on-line or in my office. I had never seen ABAP code before, and I thought that those manuals were too difficult for a beginner, with examples too complex or not so clear. Some mouths later, I decided therefore to write a little document that could help the beginners to learn the basis of the ABAP code, with a lot of easy examples and not forgetting the little details that often are missing in the specialized texts. Musiari Stefano
  5. 5. 5 2. How to create a new program Use transaction SE38. Write the name of the new program, than select “Create”. Figure 1. Transaction SE38 Fill the fields show in figure 2. Then save. Figure 2. Attributes
  6. 6. 6 Write the “Development class”. If you don’t want to transfer the program in production environment, but you want to stay in test environment, select “Local object”, otherwise select Figure 3. Development class To start writing code, select “Source code”. Figure 4. Source code
  7. 7. 7 Press F5 to add new rows (press enter if you have got an earlier version of Sap). Figure 5. ABAP Editor
  8. 8. 8 3. Variables and constants 3.1 Types of data In ABAP there are different types of data: Type Symbol Initial value Default length Length allowed Range Alphanumeric characters C Blank 1 1 - max / Numeric characters N 00…0 1 1 – max / Integer numbers I 0 4* / -231 +231 -1 Packed numbers P 0 8 1 -16 / Float. Point numbers F 0.000 8* / 1e-307 1e+307 Hexadecimal numbers X X’00’ 1 1 - max / Date yyyymmdd D 00000000 8 8 / Time hhmmss T 000000 6 6 / Table 1. Types of data * The default length depends on your computer. A name of a field can be up to 30 characters, the first must be a letter. You can not include special characters except "_".
  9. 9. 9 3.2 Data definition Field definition A field is defined as a variable if it may take on different values. It is declared with the DATA statement. The type of each field is defined with the appropriate symbol after the TYPE statement. The number in parentheses after the field name is optional and it is used to indicate the length (if it is not written, it is kept the default length). It’s possible to use the LIKE statement to compare two variables. The term VALUE defines the initial value of the variable. In the example shown in the box, the field "name" is alphanumeric and it is 15 characters long, the field "surname" is set equal to "name" field, the field "data_selected" is date type and the field "counter" is an integer data (the counters are always defined in this way) and has got an initial value (1). Record definition A record can contain multiple fields and it is always defined with the DATA statement. To define the start and the end of the record, use the notation BEGIN OF and END OF followed by the name of the record. The LIKE keyword has the same features of the definition of a field. DATA: name(15) TYPE c, surname LIKE name, data_selected TYPE d, counter TYPE i VALUE ‘1’.
  10. 10. 10 Constants definition Unlike variables, constants take always the same value while the program is running. They are defined with the CONSTANTS statement. DATA: BEGIN OF reservation, flight(10) TYPE c, departure_date TYPE d, departure_hour TYPE t, END OF reservation. DATA ticket LIKE reservation. CONSTANTS: factor TYPE p VALUE ‘233243’, country(20) TYPE c VALUE ‘Italy’.
  11. 11. 11 4. Working with strings It’s possible to perform multiple operations with strings: to select a certain number of characters in the contents of a field, to replace characters, to reverse characters, or to concatenate them. Select characters in a string The syntax is: Variable_name+X(Y) X is a number that indicates the last characters not to be taken and Y is a number that indicates how many characters to take. In this example, the variable extract is “56”. Concatenating multiple variables in a string Structure to concatenate two or more variables: CONCATENATE … INTO … In this example, the variable total is “ste56”. DATA code(8) TYPE c VALUE '12345678'. DATA extract(2) TYPE c. extract = code+4(2). DATA code(8) TYPE c VALUE '12345678'. DATA name(7) TYPE c. DATA extract(2) TYPE c. DATA total(5) TYPE c. name = 'Stefano'. extract = code+4(2). CONCATENATE name(3) extract INTO total.
  12. 12. 12 Split a string into multiple variables To split a string into multiple variables, you need to use the following syntax: SPLIT string AT ‘#’ INTO variable1 variable 2 variable 3. String is the name of the variable to split, # is the symbol that indicates the division between the fields and the words after the instruction INTO are the variables where I want to split the string. Search for values within a string The syntax is: SEARCH string FOR ‘gold’. In this example, we want to search the word ‘gold’ into the string. You can also associate an IF statement that check the variable sy-subrc: if it is equal to ‘0’ the word is found within the string, otherwise not. IF sy-subrc = ‘0’. … ELSE. … ENDIF.
  13. 13. 13 5. WRITE statement 5.1 Features WRITE statement is an output statement (for more details about outputs, see the Chapter 11). The words enclosed between two single quotes are shown as they are, while those outside are considered as variables or constants. All ABAP commands, including also the WRITE statement, must end with a point. WRITE: ‘ My name is: ‘ , name.
  14. 14. 14 4.2 Example First of all you must have created a new program in development environment, as shown in Chapter 2. The report will make the sum of the number “5” and number “3” and the result will show on screen. By pressing the F8 key on your keyboard, the program runs and displays the following output: Figure 6. Output report As you can see from this simple report, to assign a value to a variant is necessary to put the equals sign "=" between the two words. REPORT z_test. DATA number_a TYPE n. DATA number_b TYPE n. DATA sum TYPE n. number_a = 5. number_b = 3. sum = number_a + number_b. WRITE: 'The sum is:', sum.
  15. 15. 15 6. Control instructions The two constructs illustrated in the following sections allow you to associate different instructions to different responses to one or more logical conditions. 6.1 IF instruction Each IF must end with ENDIF, while inside you can enter multiple statements ELSE / ELSEIF. The syntax is: IF <logical expression A>. Instruction 1 ELSEIF < logical expression B>. Instruction 2 ELSEIF < logical expression C>. Instruction 3 … ELSE. Instruction X ENDIF. REPORT z_test. DATA number_a TYPE n. DATA number_b TYPE n. DATA sum(2) TYPE n. DATA max(3) TYPE n. number_a = 5. number_b = 3. sum = number_a + number_b. max = 10. IF sum < max. WRITE: 'The sum is < than max’. ELSE. WRITE: 'The sum is > than max’. ENDIF.
  16. 16. 16 6.2 Case instruction The CASE statement is better than IF statement if you have got a lot of cases to test. The syntax is: CASE <field>. WHEN <value A>. Istruction 1 WHEN <value B>. Istruction 2 WHEN <value C>. Istruction 3 … ENDCASE. REPORT z_test . DATA number_a TYPE n. DATA number_b TYPE n. DATA sum(2) TYPE n. number_a = 5. number_b = 3. sum = number_a + number_b. CASE sum. WHEN ‘2’. WRITE: 'The sum is 2‘. WHEN ‘3’. WRITE: 'The sum is 3‘. WHEN ‘4’. WRITE: 'The sum is 4‘. … ENDCASE.
  17. 17. 17 7. Loops The loops are useful to repeat the same instructions more times. With the statement EXIT you can go out from the loop. 7.1 DO/ENDDO You have to write how many times you need to iterate one or more statements. The syntax is: DO <n> TIMES. …instructions… ENDDO. After DO, you can write a number or a name of a numeric variable. 7.2 LOOP/ENDLOOP Often it is used to scroll the contents of internal tables (see Chapter 7). The syntax is: LOOP AT table. …instructions… ENDLOOP. DO 20 TIMES. sum = sum +1. ENDDO.
  18. 18. 18 7.3 WHILE/ENDWHILE With this statement, the commands within are repeated until the logical condition is satisfied. The syntax is: WHILE <logical expression>. …instructions… ENDWHILE. WHILE sum < 20. sum = sum +1. ENDWHILE.
  19. 19. 19 8. Tables 8.1 Internal tables Unlike the database tables, internal tables exist only during the elaboration of the program that uses them. Any entries or changes will be reset once the report has finished processing. Internal tables allow you to perform calculations more quickly and effectively than tables of the SAP database. Declaration The internal tables must be declared at the beginning of the program with the DATA statement. Unlike the definition of a record, you must add the syntax OCCURS 100 (or either OCCURS 0), a parameter that can allocate more memory space. All the fields must be declared specifying length and type, or recalling an existing or a previously declared field using the LIKE statement followed by the syntax "name_table-name_field." Often the internal table has the same structure of a database table, in this case, you can declare it with the syntax INCLUDE STRUCTURE. In the following example, “tb_user” is the internal table and “user” is the database table. DATA: BEGIN OF tb_user OCCURS 100, name(20) TYPE c, surname(20) TYPE c value LIKE test-value, END OF tb_user. DATA: BEGIN OF tb_user OCCURS 100, INCLUDE STRUCTURE user, END OF tb_user.
  20. 20. 20 Insert a record To transfer quickly the contents of a database table in an internal table, you can use the command MOVE-CORRESPONDING which, however, requires that the two tables have the same structure, otherwise only the data that are in fields in both tables will be transferred. The syntax is: MOVE-CORRESPONDING table_db TO table_internal. It’s also possible to transfer the contents of individual fields using the symbol "=". With these instructions a row of the table “user” is copied to the header line of the internal table. To transfer data from the header line to the database table, it is necessary to add the statement APPEND followed by the name of the internal table. Delete a record The statement to use is DELETE, followed by the name of the internal table. With WHERE you can filter the records. DELETE tb_user WHERE name = ‘Zanetti’. MOVE-CORRESPONDING user TO tb_user. OTHERWISE tb_user-name = user-name. tb_user-surname = user-surname. tb_user-value = user-value. APPEND tb_user.
  21. 21. 21 To delete the entire contents of an internal table is used the REFRESH command. Modify a record Use the MODIFY command followed by the name of the internal table. Sort records Use the SORT command; the syntax is: SORT table BY field ASCENDING/DESCENDING. Header line The header line is an additional line in the internal table, where data are inserted before being written into the table. To initiate this line, you can use the CLEAR command. To clarify the operation, is shown an example in which a record is copied from a database table (zhjob) to an internal table (tb_zhjob). (The pictures are taken from ABAP Debugger). REFRESH tb_user. tb_user = ‘new’. MODIFY tb_user. SORT tb_user BY name ASCENDING.
  22. 22. 22 1) Initial situation of tb_zhjob The header line and the internal table are empty 2) Instruction: MOVE-CORRESPONDING zhjob TO tb_zhjob. The header line is enhanced with data from the first row of the table zhjob. The tb_zhjob is still blank. 3) Instruction: APPEND tb_zhjob. The contents of the header line is copied into the first row of the internal table (indicated by the number "1" in blue). 4) Instruction: CLEAR tb_zhjob. The header line is blank.
  23. 23. 23 8.2 Database tables These tables are viewable with the SAP transaction SE11 (to see the structure) and SE16 (to see the content). Any changes will remain permanent. Declaration The structure of these tables must be defined with the transaction SE11. Within the program code, use the TABLES statement followed by the name of the tables. Read a database table The database tables are read with the SELECT statement. The basic syntax is: SELECT fields_to_read FROM table. … ENDSELECT. (If you want to read all the columns in the database table write: SELECT * FROM table.) It’s possible to filter some records with the statement WHERE, or to sort the records with the syntax ORDER BY – ASCENDING/DESCENDING. The construct SELECT / ENDSELECT reads a single record at a time that satisfies the conditions written between the two key words. Once the first record is read, the construct reads the second one and so on. It works like a loop. TABLES: user, zhjob. SELECT * FROM user WHERE name = ‘Diego’ AND surname = ‘Milito’ ORDER BY goals ASCENDING. … ENDSELECT.
  24. 24. 24 If you would rather analyze only the first record that meets the conditions, you can use SELECT SINGLE or SELECT- UP TO 1 ROWS: Both forms do not require ENDSELECT. All structures value the variable sy-subrc, if SELECT construct find a record that satisfies the conditions, its value is '0 ', otherwise it’s '4'. Insert a record To insert a record you must use the INSERT statement followed by the name of the table. Modify a record To modify a record you must use the UPDATE statement followed by the name of the table. SELECT SINGLE * FROM user WHERE name = ‘Diego’ AND surname = ‘Milito’ ORDER BY goals ASCENDING. … user-name = ‘Marco’. user-surname = ‘Materazzi’. user-number = ‘23’. INSERT user. user-name = ‘Marco’. user-surname = ‘Materazzi’. user-number = ‘23’. UPDATE user. SELECT * FROM user UP TO 1 ROWS WHERE name = ‘Diego’ AND surname = ‘Milito’ ORDER BY goals ASCENDING. …
  25. 25. 25 DELETE A RECORD To delete a record you must use the DELETE statement followed by the name of the table. user-name = ‘Marco’. user-surname = ‘Materazzi’. user-number = ‘23’. DELETE user.
  26. 26. 26 8.3 Example In order to clarify the instructions read/write for database tables and internal tables, here you are an example: Initial data The program must read the table PA0001 (the structure is visible from the SE11 transaction) and must check all records relating to the company 8918, indicating for each CID(employ) if his creation has occurred before or after 01.01.2010. Functional analysis First you must declare the database tables to be checked (in this case only the PA0001) and the internal tables to be used; in this example we use an internal table “tb_run”, with the fields PERNR and BEGDA (the same of the table PA0001) plus a new field (TYPE). It reads the PA0001, copying in the internal table tb_run the records that have the company (field BUKRS) = 8918. If no records are found, a message appears on the screen. At this point you are running a loop on the internal table to identify records before and after the date 01.01.2010 (note that the field BEGDA has the structure 'yyyymmdd'. The word "le" means "less than or equal", while "ge" indicate "greater than or equal". At the end are displayed in output the fields pernr and notes of the internal table. As you can see in the example, to add a comment, you simply start the sentence with an asterisk (*) or, in any position, you can write the double quote (") followed by comment. To make the code prettier, write to the yellow line "pp" (pretty printer), as shown in Figure 7, and press enter. The same command is also editable from the toolbar. Figure 7. Pretty printer
  27. 27. 27 By pressing the F8 key on the keyboard, the program runs and shows a spool like this: REPORT z_test . TABLES pa0001. * variables DATA: BEGIN OF tb_run OCCURS 0, pernr LIKE pa0001-pernr, begda LIKE pa0001-begda, type(40) TYPE c, END OF tb_run. * run program SELECT * FROM pa0001 WHERE bukrs = '8918'. MOVE-CORRESPONDING pa0001 TO tb_run. APPEND tb_run. CLEAR tb_run. ENDSELECT. IF sy-subrc NE 0. WRITE: 'No record for company 8918'. ENDIF. LOOP AT tb_run. IF tb_run-begda LE '20000101'. tb_run-type = 'Record before 01.01.2010'. ELSE. tb_run-type = 'Record after 01.01.2010'. ENDIF. MODIFY tb_run. ENDLOOP. * view LOOP AT tb_run. WRITE:/ tb_run-pernr. WRITE: tb_run-type. ENDLOOP.
  28. 28. 28 Figure 8. Report output
  29. 29. 29 9. Parameters and Selection-Screen 9.1 Parameters They are optional input items. These elements can be declared with the statement PARAMETER individually or simultaneously using the command PARAMETERS: followed by a list of fields separated by a comma. These objects, which must be declared at the beginning of the report, can be at most 8 characters long, but the name that is displayed on the screen, can also be different from the name written in the Abap code. To do this, simply follow the path shown in Figure 9 where you can put names to display. Figure 9 Change parameters name All parameters have optional options: OBLIGATORY: it implies that the field must necessarily be compiled by the user DEFAULT: is given a default value of the parameter LOWER CASE: default values are read as upper-case, with this option, the value is read as lower-case.
  30. 30. 30 Checkbox Within a program they are independent and can be unlimited. Each of them can take only two values: a blank character (by default, if it’s not selected) or an uppercase X (if the field is selected). Syntax: PARAMETER name AS CHECKBOX. Label The label allows the user to manually write an input. Syntax: Radiobutton Like the checkbox, they can have only two states (' ' and 'X'). They could not work alone but they must be connected in a group, but however only one can be selected (for this reason are often used in cases of constrained choice). PARAMETER run AS CHECKBOX DEFAULT ‘X’. PARAMETER company LIKE PA0001-BUKRS OBLIGATORY. PARAMETERS: type_a RADIOBUTTON GROUP g1 DEFAULT 'X', type_b RADIOBUTTON GROUP g1, type_c RADIOBUTTON GROUP g1.
  31. 31. 31 9.2 Select-options The select-options are used to manage a range of values. The syntax is: SELECT-OPTIONS so_name FOR name_tab-name_field. After the word FOR you must enter the name of the database table and the name of the field in which the select-options will find the values. The select-option is useful to filter and to read a database table. Note that, for comparing the contents of a select-option to another field, you have to use the syntax IN instead of the equal sign. A select-option is like this: By selecting the yellow arrow on the right, you can fill one of the four tables present: individual values, ranges of values to be read, single values not to be read and ranges of values to be not considered (see Figure 10). TABLES user. SELECT-OPTIONS so_name FOR user-name. SELECT * FROM user WHERE name IN so_name. … ENDSELECT.
  32. 32. 32 Figure 10. Select-option NOTE: if you don’t write anything, the report will read all the records.
  33. 33. 33 9.3 Selection-screen A selection-screen is like a box that can contain various elements, including parameters and select- options, linked together in a logical way. N.B.1: it is not possible to insert more radiobuttons of the same group in different selection-screens. N.B.2: you can insert more groups of radiobuttons within the same selection-screen. The syntax is: SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME. ... SELECTION-SCREEN: END OF BLOCK b1. You can also specify a name for the frame: SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-xxx. ... SELECTION-SCREEN: END OF BLOCK b1. “xxx” are 3 digits (usually you start with 001) that link the frame to the title. To create a title for a frame you must follow the path shown in Figure 11 and then fill the table like the Figure 12.
  34. 34. 34 Figure 11. Text symbols Figure 12. Text symbols 2 Within a frame the various objects run sequentially in the vertical direction. To insert a space between two elements use the syntax: SELECTION-SCREEN SKIP.
  35. 35. 35 To view more items on one line: SELECTION-SCREEN BEGIN OF LINE. …elements… SELECTION-SCREEN END OF LINE. To show a simple text, the syntax is: SELECTION-SCREEN COMMENT (30) text-002. The number in parentheses indicates the length of the string and the code 002 is the number of the record in the table of text symbols (Figure 12).
  36. 36. 36 9.4 Example Now we continue on the same report described in section 7.3, with the addition of the elements discussed in this chapter. With the parameters is now possible to make the program more flexible and realistic, because the user can use a specific date and he can also select one or more companies simultaneously. In the old version of the program, the date was always 2010.01.01 and the company was always 8919, with no possibility for the user to change them. ABAP instructions (the new ones from the previous version are in bold): REPORT z_test. TABLES: pa0001. SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001. PARAMETER date LIKE pa0001-begda OBLIGATORY. SELECTION-SCREEN SKIP. SELECT-OPTIONS: so_bukrs FOR pa0001-bukrs. SELECTION-SCREEN: END OF BLOCK b1. SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002. PARAMETER run AS CHECKBOX DEFAULT 'X'. SELECTION-SCREEN: END OF BLOCK b2. * variables DATA: BEGIN OF tb_run OCCURS 0, pernr LIKE pa0001-pernr, begda LIKE pa0001-begda, type(40) TYPE c, END OF tb_run. * run the program IF run = 'X'. SELECT * FROM pa0001 WHERE bukrs IN so_bukrs. MOVE-CORRESPONDING pa0001 TO tb_run. APPEND tb_run. CLEAR tb_run. ENDSELECT.
  37. 37. 37 The text symbols are: IF sy-subrc NE 0. WRITE: 'No record for company 8918’, so_bukrs. ENDIF. LOOP AT tb_run. IF tb_run-begda LE date. tb_run-type = 'Record before the date’. ELSE. tb_run-type = 'Record after the date’. ENDIF. MODIFY tb_run. ENDLOOP. * view LOOP AT tb_run. WRITE:/ tb_run-pernr. WRITE: tb_run-type. ENDLOOP. ELSE. WRITE: 'Select the flag '. ENDIF.
  38. 38. 38 Go out from the folder and come back to the Abap code, then press F8 on the keyboard: At this point the user can fill the fields, then click on the button to run the program.
  39. 39. 39 10. Form and functions They allow you to repeat several times a group of operations without to rewrite them every time, but simply calling them. They make easier to read the code. 10.1 Forms A form is defined by the instructions FORM / ENDFORM, within you must write the code. To recall a form use the PERFORM statement followed by the name of the form. A program can be structured as follows: NOTE: with a double-click on the name "PERFORM ...", instructions form / endform are created automatically. When you need to repeat the same form several times, but with different input data, you can specify in the PERFORM the tables and variables that you want to use. Report … * Declaration database tables * Declaration selection screens e parameters * Declaration variables * Run code START-OF-SELECTION. PERFORM input. PERFORM processing. END-OF-SELECTION. FORM input. … ENDFORM. FORM processing. … ENDFORM.
  40. 40. 40 In the example below, the form processing use the table tab_ok and use the values of the variables text1 and text2. The first time that you run this form, you use the table table_a with the variables va_textA and va_textB; the second time, you use the table table_b and the variables va_textC and va_textD. PERFORM processing TABLES table_a USING va_textA va_textB. PERFORM processing TABLES table_b USING va_textC va_textD. FORM processing TABLES tab_ok USING text1 text2. … ENDFORM.
  41. 41. 41 10.2 Functions Unlike the form, the functions can also be used in different programs. To create a function, you have to use the transaction SE37. They are defined by the syntax FUNCTION/ENDFUNCTION. To recall a form use the CALL FUNCTION statement followed by the name of the function. CALL FUNCTION ‘FUNCTION_TEST’. FUNCTION ‘FUNCTION_TEST’. …instructions… ENDFUNCTION. Example of function: Other examples of functions will be shown in Chapter 12, related to file management. CALL FUNCTION 'CONVERT_DATE_TO_INTERN_FORMAT' EXPORTING datum = tb_filein-begda dtype = 'DATS' IMPORTING idate = xbegda.
  42. 42. 42 11. Error messages In many cases it may be necessary to show a video an error message, for example if the user write incorrect entries, if a file it’s not correct and so on. Usually the messages are used in IF statements. To active the messages you must add in the code the syntax REPORT MESSAGE-ID followed by the class of messages to be used (for example, zt). REPORT z_test MESSAGE-ID zt. To insert the text of the message follow the path shown in Figure 13. Figure 13. Messages After entering the class of messages (for example, zt) you can see the list of all messages previously created, each with its own code. Within the program you can use an existing message or you can create a new one, entering the code and selecting the button Individual maint. (see Figure 14). NOTE: the symbol "&"allows you to see the value of a variable (see example at the end of the chapter).
  43. 43. 43 Figure 14. List messages To recall a message in the report use the following syntax (the WITH statement is optional and it is used to indicate variables to be displayed): MESSAGE type error message code WITH variables. The types of errors are: s: The program run and only in the end is shown an error message i: You get a popup that shows the error but by pressing the Enter key, the program will process w / e: The report ends immediately and you will be brought out of the program a: The report ends immediately and you will be taken out of the transaction x: The report ends with dump Example: You can see the message 001 in the figure 14, but instead of the symbol “&”, you have the value of the variable my_password. Further examples of error messages will be presented in Chapter 13, relating to file management. REPORT z_test MESSAGE-ID zt. … MESSAGE e001 WITH my_password.
  44. 44. 44 12. OUTPUT 12.1 Simple view As explained in Chapter 4, the easiest way to view an output is to use the WRITE statement. Usually the output instructions are placed in a special FORM, which is elaborated in the end of the code. SKIP statement This instruction lets you to insert a blank line in the spool (screen output), useful for example to separate multiple WRITE statements. It may be followed by a number indicating how many blank lines should be included. Ex. SKIP 2. Colors For a clearer view, you can color the output using the word COLOR. The list of colors available for the SAP version 4.5 is shown in the following table. Name color Main use Description color Col_heading Header Blue Col_key Name of the columns Light green Col_normal List Light grey Col_background Background Grey Col_positive Positive values Green Col_negative Negative values Red Col_group Check levels Light purple Col_total Total Yellow Table 2. Colors The color can be changed with the statement INTENSIFIED OFF.
  45. 45. 45 The syntax is: WRITE ‘Test’ COLOR col_heading INTENSIFIED OFF. Tables and lines It is not possible to directly create a table, but you must draw it piece by piece through the characters "_" and "|". To draw a horizontal line you can use the following syntax: WRITE 01 sy-uline(75). the first number indicates the position from which the line starts, while the second number indicates the length of the line. To draw a vertical line you can use the following syntax: WRITE 01 sy-vline(75). Example There are two counters (cont_tot and cont_ok) and an internal table tb_zharch. As for the table, you must first create the head, then through a loop insert the content field to field. FORM spool. WRITE:/'Test' COLOR COL_HEADING. WRITE:/'Total records in the file: ', cont_tot. SKIP. WRITE:/'Inserted records in the table ZHARCH' COLOR COL_HEADING. WRITE:/01 sy-uline(75). WRITE:/01 '| Soc.' COLOR COL_POSITIVE, 07 '| CID' COLOR COL_POSITIVE, 17 '| Num' COLOR COL_POSITIVE, 29 '| Vers' COLOR COL_POSITIVE, 35 '| Name COLOR COL_POSITIVE, 75 '|'. WRITE:/01 sy-uline(75).
  46. 46. 46 If you want to see a table with more columns, it is better to display in ALV style. LOOP AT tb_zharch. WRITE:/01 '|' , tb_zharch-bukrs, 07 '|' ,tb_zharch-pernr, 17 '|' ,tb_zharch-reinr, 29 '|' ,tb_zharch-pdvrs, 35 '|' ,tb_zharch-ename, 75 '|'. WRITE:/01 sy-uline(75). ENDLOOP. ENDFORM. " SPOOL
  47. 47. 47 12.2 ALV view This view is better if you should show a table with many and more complex fields. You can’t concatenate into a single view both types of output, but you can create and display them sequentially. Immediately after the report definition, you must add the following string: TYPE-POOLS: slis. Then you have to declare a set of variables and then you have to create one or more Perform using also the REUSE_ALV_LIST_DISPLAY function. NOTE: In the following example will be shown only the most important feature of the ALV, in this case we want to view the table tb_recout (which has got four fields: pbukr, posid, post1, stato). REPORT zextract_stato_wbs MESSAGE-ID zt. TYPE-POOLS: slis. DATA: s_layout TYPE slis_layout_alv, * s_grid_settings TYPE lvc_s_glay, fcat TYPE slis_t_fieldcat_alv, ls_fieldcat TYPE slis_fieldcat_alv, g_repid LIKE sy-repid, header_alv TYPE slis_t_listheader, keyinfo TYPE slis_keyinfo_alv, header_alv_wa TYPE slis_listheader, gt_events TYPE slis_t_event, event_exit TYPE slis_t_event_exit, event_exit_ln LIKE LINE OF event_exit, s_sortcat TYPE slis_t_sortinfo_alv, s_sortcat_ln LIKE LINE OF s_sortcat, * g_boxnam TYPE slis_fieldname VALUE 'CB', g_variant LIKE disvariant, gt_repid LIKE sy-repid. … PERFORM… PERFORM alv.
  48. 48. 48 FORM alv. PERFORM do_alv. gt_repid = sy-repid. CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY' EXPORTING i_callback_program = gt_repid is_layout = s_layout it_fieldcat = fcat it_sort = s_sortcat i_save = 'A' it_events = gt_events TABLES t_outtab = tb_recout EXCEPTIONS program_error = 1 OTHERS = 2. ENDFORM. *********************************************** FORM do_alv. PERFORM layout. PERFORM fieldcat USING fcat[]. * PERFORM sortcat. PERFORM event. ENDFORM. *********************************************** FORM layout. s_layout-colwidth_optimize = 'X'. s_layout-zebra = 'X'. ENDFORM. " LAYOUT ***********************************************
  49. 49. 49 FORM fieldcat USING p_gt_fieldcat TYPE slis_t_fieldcat_alv. CLEAR ls_fieldcat. ls_fieldcat-fieldname = 'PBUKR'. ls_fieldcat-seltext_l = Società'. ls_fieldcat-col_pos = '1'. APPEND ls_fieldcat TO p_gt_fieldcat[]. CLEAR ls_fieldcat. ls_fieldcat-fieldname = 'POSID'. ls_fieldcat-seltext_l = 'Elemento WBS'. ls_fieldcat-col_pos = '2'. APPEND ls_fieldcat TO p_gt_fieldcat[]. CLEAR ls_fieldcat. ls_fieldcat-fieldname = 'POST1'. ls_fieldcat-seltext_l = 'Descrizione WBS'. ls_fieldcat-col_pos = '3'. APPEND ls_fieldcat TO p_gt_fieldcat[]. CLEAR ls_fieldcat. ls_fieldcat-fieldname = 'STATO'. ls_fieldcat-seltext_l = 'Stato WBS'. ls_fieldcat-col_pos = '4'. APPEND ls_fieldcat TO p_gt_fieldcat[]. ENDFORM. " FIELDCAT *********************************************** FORM event. DATA: lt_events TYPE slis_alv_event. lt_events-name = 'TOP_OF_LIST'. lt_events-form = 'TOP_OF_LIST'. APPEND lt_events TO gt_events. lt_events-name = 'TOP_OF_PAGE'. lt_events-form = 'TOP_OF_PAGE'. APPEND lt_events TO gt_events. ENDFORM. " EVENT
  50. 50. 50 The only form that requires some work is fieldcat, where must be declared: all the fields to display, the technical name of the column, its description and location to be displayed in the table (there are also other fields optional). Now you can see the table tb_recout like this: Figure 15. ALV Output On the top is created automatically switches that allow for quick different operations, such as filter and sort values or download the table locally.
  51. 51. 51 12.3 ALV view in POPUP This view allows you to display the contents of an internal table in ALV format into a popup. The following example displays the tb_output, which has the same structure of the database table zharch, but with some fields less (by entering the name of the database table in REUSE_ALV_FIELDCATALOG_MERGE function, is no longer necessary to declare all fields). If you don’t want to see certain fields, you must use the syntax: gt_fieldcat-no_out = 'X'. To change the position of a field use: gt_fieldcat-col_pos = '19'. TABLES zharch. DATA: BEGIN OF tb_output OCCURS 0, pernr LIKE pa0001-pernr, reinr LIKE ptrv_head-reinr, zort1 LIKE ptrv_head-zort1, pdvrs LIKE ptrv_perio-pdvrs, hdvrs LIKE ptrv_perio-hdvrs, zland LIKE ptrv_head-zland, datv1 LIKE ptrv_head-datv1, datb1 LIKE ptrv_head-datb1, kunde LIKE ptrv_head-kunde, bukrs LIKE pa0001-bukrs. DATA: END OF tb_output. ************ ALV instructions*********************** TYPE-POOLS: slis. DATA: s_layout TYPE slis_layout_alv, * s_grid_settings TYPE lvc_s_glay, fcat TYPE slis_t_fieldcat_alv, ls_fieldcat TYPE slis_fieldcat_alv, g_repid LIKE sy-repid, header_alv TYPE slis_t_listheader, keyinfo TYPE slis_keyinfo_alv, header_alv_wa TYPE slis_listheader, gt_events TYPE slis_t_event, event_exit TYPE slis_t_event_exit, event_exit_ln LIKE LINE OF event_exit, s_sortcat TYPE slis_t_sortinfo_alv, s_sortcat_ln LIKE LINE OF s_sortcat, g_variant LIKE disvariant, gt_repid LIKE sy-repid.
  52. 52. 52 * POP-UP ALV DATA gt_fieldcat TYPE slis_t_fieldcat_alv WITH HEADER LINE DATA: gs_selfield TYPE slis_selfield, g_exit(1) TYPE c, extab TYPE slis_t_extab. DATA va_again. ************************************************** CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE' EXPORTING i_structure_name = 'zharch' CHANGING ct_fieldcat = gt_fieldcat[]. CLEAR gt_fieldcat. READ TABLE gt_fieldcat WITH KEY fieldname = 'ENAME'. IF sy-subrc = 0. gt_fieldcat-key = ' '. gt_fieldcat-no_out = 'X'. MODIFY gt_fieldcat INDEX sy-tabix. ENDIF. CLEAR gt_fieldcat. READ TABLE gt_fieldcat WITH KEY fieldname = 'PDVRS'. IF sy-subrc = 0. gt_fieldcat-seltext_l = text-003. gt_fieldcat-seltext_m = text-003. gt_fieldcat-seltext_s = text-003. gt_fieldcat-reptext_ddic = text-003. MODIFY gt_fieldcat INDEX sy-tabix. ENDIF. CLEAR gt_fieldcat. READ TABLE gt_fieldcat WITH KEY fieldname = 'BUKRS'. IF sy-subrc = 0. gt_fieldcat-col_pos = '19'. MODIFY gt_fieldcat INDEX sy-tabix. ENDIF. CLEAR extab. REFRESH extab. APPEND '&ETA' TO extab. APPEND '&OL0' TO extab. Field not to be displayed 
  53. 53. 53 DATA: p_title TYPE sy-title, va_pernr LIKE ptrv_archive-pernr. CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT' EXPORTING input = so_pernr IMPORTING output = va_pernr. num_ins = cont_ok. CONCATENATE text-002 va_pernr text-004 num_ins INTO p_title SEPARATED BY space. va_again = 'X'. WHILE va_again = 'X'. CALL FUNCTION 'REUSE_ALV_POPUP_TO_SELECT' EXPORTING i_title = p_title * i_selection = 'X' i_zebra = 'X' i_screen_start_column = 10 i_screen_start_line = 1 i_screen_end_column = 106 i_screen_end_line = 25 * i_checkbox_fieldname = * I_LINEMARK_FIELDNAME = * i_scroll_to_sel_line = 'X' i_tabname = '1' * i_structure_name = it_fieldcat = gt_fieldcat[] it_excluding = extab * i_callback_program = * I_CALLBACK_USER_COMMAND = * is_private = gs_private IMPORTING es_selfield = gs_selfield e_exit = g_exit TABLES t_outtab = tb_output EXCEPTIONS program_error = 1 OTHERS = 2. Title to show Graphics setting of the popup  Function not inherent to ALV  Table to show 
  54. 54. 54 The output is like this picture: IF g_exit NE 'X'. READ TABLE tb_output INDEX gs_selfield-tabindex. SUBMIT zg0hr014_ver AND RETURN WITH p_cid = va_pernr WITH p_ntr = tb_output-reinr WITH p_ver = tb_output-pdvrs. va_again = 'X'. ELSE. CLEAR va_again. ENDIF. ENDWHILE. ENDFORM. " ALV
  55. 55. 55 13. File 13.1 Declaration A file is simply declared in a SELECTION-SCREEN with the following syntax: PARAMETER file_out LIKE rlgrap-filename. On the screen the user can write the path and the file name: NOTE: to modify the name on the screen, see the chapter 9 It’s possible to write a default path of the file as the following example: PARAMETER file_out LIKE rlgrap-filename DEFAULT ‘C:Userstest.txt’. To keep a field obligatory, write OBLIGATORY, like the PARAMETERS.
  56. 56. 56 13.2 Upload a file from UNIX The syntax is: OPEN DATASET file_unx FOR INPUT IN TEXT MODE. READ DATASET file_unx INTO tb_recin . …istructions… CLOSE DATASET file_unx. File_unx is the name of the file ( .TXT) and tb_recin is the internal table where the content of the file is copied (its structure must be the same of the file). PARAMETER: file_unx LIKE rlgrap-filename. * internal table DATA: BEGIN OF tb_recin OCCURS 0, bukrs LIKE pa0001-bukrs, reinr LIKE ptrv_head-reinr, pdvrs LIKE ptrv_perio-pdvrs, data_arch LIKE zharch-data_arch, END OF tb_recin. OPEN DATASET file_unx FOR INPUT IN TEXT MODE. IF sy-subrc NE 0. MESSAGE e007 WITH file_unx. STOP. ENDIF. DO. CLEAR tb_recin. READ DATASET file_unx INTO tb_recin. APPEND tb_recin . ENDDO. CLOSE DATASET file_unx.
  57. 57. 57 13.3 Upload a file from DOS To upload a file from DOS, you need to use the function WS_UPLOAD, where you have to write the file name, the type of the file (.txt or .csv) and the internal table. Often it’s useful to create a match code that allow you to write quickly the path of the input file or the patch of the output file; you can use the function WS_FILENAME_GET. Example: REPORT z_newcdc MESSAGE-ID zt. TABLES: … ******* PARAMETERS *********************** … PARAMETERS: filein LIKE rlgrap-filename OBLIGATORY. … ********* VARIABLES************************ … DATA: BEGIN OF tb_recin OCCURS 0, kokrs LIKE csks-kokrs, khinr_old LIKE csks-khinr, khinr_new LIKE csks-khinr, END OF tb_recin. … *********RUN PROGRAM *********************
  58. 58. 58 You have to write these instructions before the START-OF-SELECTION. NB: The WS_FILENAME_GET function doesn’t upload the file. AT SELECTION-SCREEN ON VALUE-REQUEST FOR filein. PERFORM get_in_filedos. AT SELECTION-SCREEN. START-OF-SELECTION. PERFORM … PERFORM … … END-OF-SELECTION. *&-------------------------------------------------------- *& Form GET_OUT_FILEDOS *&-------------------------------------------------------- FORM get_out_filedos. CALL FUNCTION 'WS_FILENAME_GET' EXPORTING def_path = 'D:' mask = ',*.* ,*.*.' mode ='0' title = 'Write the input file path' IMPORTING filename = filein EXCEPTIONS inv_winsys = 1 no_batch = 2 selection_cancel = 3 selection_error = 4 other = 5. ENDFORM. " GET_IN_FILEDOS
  59. 59. 59 Upload file .TXT You have to declare the file, the internal table, then use the function WS_UPLOAD; filetype= ASC AT SELECTION-SCREEN ON VALUE-REQUEST FOR filein. PERFORM get_in_filedos. AT SELECTION-SCREEN. START-OF-SELECTION. PERFORM open_file. PERFORM … … END-OF-SELECTION. *&-------------------------------------------------- *& Form open_file *&-------------------------------------------------- FORM open_file. CLEAR tb_recin. REFRESH tb_recin. CALL FUNCTION 'WS_UPLOAD' EXPORTING filename = filein filetype = 'ASC' TABLES data_tab = tb_recin EXCEPTIONS conversion_error = 1 file_open_error = 2 file_read_error = 3 invalid_table_width = 4 invalid_type = 5 no_batch = 6 unknow_error = 7 gui_refuse_filetransfer = 8 OTHERS = 9. ENDFORM. "open_file
  60. 60. 60 Upload file .CSV In this case, in addition to the internal table where you want to copy the data file, you have to specify two additional tables (i_upload and app_up) consisting of a single long field. In the function, to specify the type DAT. Example: REPORT z_newcdc MESSAGE-ID zt. TABLES: … ******* parameters ******* … PARAMETERS: filein LIKE rlgrap-filename OBLIGATORY. … ********* variables******** DATA: BEGIN OF tb_recin OCCURS 0, pbukr LIKE prps-pbukr, posid LIKE prps-posid, END OF tb_recin. DATA:BEGIN OF i_upload OCCURS 0, line(250), END OF i_upload. DATA:BEGIN OF app_up OCCURS 0, line(250), END OF app_up. … ********* Program ******* *** AT SELECTION-SCREEN ON VALUE-REQUEST FOR filein. PERFORM get_in_filedos. AT SELECTION-SCREEN. START-OF-SELECTION. PERFORM open_file. PERFORM … … END-OF-SELECTION.
  61. 61. 61 *&-------------------------------------------------- *& Form open_file *&-------------------------------------------------- FORM open_file. CALL FUNCTION 'WS_UPLOAD' EXPORTING filename = filein filetype = 'DAT' TABLES data_tab = i_upload EXCEPTIONS conversion_error = 1 file_open_error = 2 file_read_error = 3 invalid_table_width = 4 invalid_type = 5 no_batch = 6 unknow_error = 7 gui_refuse_filetransfer = 8 OTHERS = 9. PERFORM upload_tb_recin. ENDFORM. "open_file *&------------------------------------------------- *& Form UPLOAD_TB_RECIN *&------------------------------------------------- FORM upload_tb_recin. CLEAR tb_recin. LOOP AT i_upload. CLEAR app_up. REFRESH app_up. SPLIT i_upload-line AT ';' INTO TABLE app_up. LOOP AT app_up. CASE sy-tabix. WHEN '1'. tb_recin-pbukr = app_up-line. WHEN '2'. tb_recin-posid = app_up-line.
  62. 62. 62 The CASE instruction has got the same number of lines like the columns of the internal table; in this case only two: pbukr e posid. ENDCASE. ENDLOOP. APPEND tb_recin. CLEAR tb_recin. ENDLOOP. ENDFORM. " UPLOAD_TB_RECIN
  63. 63. 63 13.4 Download a file in UNIX In this section you will learn how to transfer the contents of an internal table with one field in a file to be saved in a UNIX environment. The syntax is: OPEN DATASET fileunix FOR OUTPUT IN TEXT MODE. …TRANSFER / TO. In this example, the table tb_buffer is copied in the file fileunix. The path is written from the user. PARAMETERS: fileunix LIKE rfpdo1-allgunix. DATA: BEGIN OF tb_buffer OCCURS 0, buffer(1000) TYPE c. DATA: END OF tb_buffer. LOOP AT tb_buffer. OPEN DATASET fileunix FOR OUTPUT IN TEXT MODE. TRANSFER tb_buffer TO fileunix. ENDLOOP. CLOSE DATASET fileunix.
  64. 64. 64 13.5 Download a file in DOS To make easier for the user to define the output path, you can use the same instructions of the form get_in_filedos (WS_FILENAME_GET function included). To download the file, you have to use the function WS_DOWNLOAD, where you have to write the name file, the type of the file ( ASC = file .TXT or DAT = file .CSV) and the internal table where take the information. AT SELECTION-SCREEN ON VALUE-REQUEST FOR filein. PERFORM get_out_filedos. AT SELECTION-SCREEN. START-OF-SELECTION. PERFORM ... PERFORM do_file_out. … END-OF-SELECTION. *&------------------------------------------------------ *& Form GET_OUT_FILEDOS *&------------------------------------------------------ FORM get_out_filedos. CALL FUNCTION 'WS_FILENAME_GET' EXPORTING def_path = 'D:' mask = ',*.* ,*.*.' mode ='0' title = 'Write the output file path' IMPORTING filename = file_out EXCEPTIONS inv_winsys = 1 no_batch = 2 selection_cancel = 3 selection_error = 4 other = 5. ENDFORM. " GET_OUT_FILEDOS
  65. 65. 65 *&----------------------------------------------------- *& Form do_file_out *&----------------------------------------------------- FORM do_file_out. CALL FUNCTION 'WS_DOWNLOAD' EXPORTING filename = file_out filetype = 'ASC' TABLES data_tab = tb_recout EXCEPTIONS file_open_error = 1 file_write_error = 2 invalid_filesize = 3 invalid_table_width = 4 invalid_type = 5 no_batch = 6 unknow_error = 7 gui_refuse_filetransfer = 8 other = 9. ENDFORM.
  66. 66. 66 14. ABAP Debugger This tool allows the programmer to see step by step the instructions that are processed by the program, in order to better appraise the operation, and especially to find the causes of errors. This feature is enabled not only to analyze the report processing, but also for all other objects such as functions, tables, views, etc.. To use the ABAP debugger, write /h, like the picture below, and run: Figure 16. Run debug Example of ABAP code: Figure 17. Debug screen
  67. 67. 67 To scroll through the code instruction by instruction, you have to use the F5 key on the keyboard. To run the code more quickly, without entering into the individual form or function, use the F6 key. At any time by pressing the F8, the report run until the end. You can select what you want to see on the top of the screen (fields, tables,…): To set a breakpoint you can also make a double-click on the line where you want to stop the elaboration: Figure 18. Breakpoint With a double-click on a variable or on a table you can see or modify the content. The Watchpoints is useful to stop the elaboration when a condition is true.
  68. 68. 68 You can also set more conditions at the same time.

×