Sams Teach Yourself ABAP/4® in 21 Days

Day 7

Defining Data in ABAP/4, Part 1

Chapter Objectives

After you complete this chapter, you should be able to

Before proceeding, please turn to Day 2 and take a few minutes to re-read the analysis in the section "Understanding Code Syntax" now.

Program Buffer and the Roll Area

Programs are buffered on the application server in a program buffer. When a user makes a request to run a program, a search is done in the program buffer for it. If it is found, and if it has not been modified in the database, the buffered copy is used. If not, or if the copy in the database is newer, the program is reloaded.

A separate copy of the program is not made in memory for each user who executes it. Instead, all users execute the same copy of the program. The differentiating factor is a separate memory allocation called a roll area. One roll area is allocated per execution per user per program. The system uses the roll area to hold all information about the current execution of the program and all memory allocations. Information such as the variables and their values, the current program pointer, and the list output are all kept in the roll area. For example, suppose a user executes a program and a roll area is allocated. If, without waiting for it to finish, the user switches to another session and starts up the same program again, another roll area is allocated for the second execution of that program. The user has two roll areas, one for each execution of the program. If the user had instead run a different program, he would still have two roll areas, one for each program.

Elements of ABAP/4 Syntax

Each ABAP/4 program is composed of one or more statements. Each statement contains one or more words separated by at least one space. The first word of a statement is the keyword. A statement can include one or more additions, and always ends with a period.

In Listing 7.1, the keywords are select, write, and endselect. Two additions appear on the select statement: where and order by. What is normally called a clause in other languages is called an addition in ABAP/4: It is any word or group of words after the keyword that modifies the behavior of the statement.

Listing 7.1  Illustration of Basic ABAP/4 Syntax

1 select * from ztxlfa1 where lifnr > '0000001050' order by lifnr.
2     write: \ ztxlfa1-lifnr, ztxlfa1-name1, ztxlfa1-land1.
3     endselect.

A statement can begin in any column and can span any number of lines. To continue a statement on another line, break the statement between any two words. A continuation character is not needed. For example, the code in Listing 7.1 can be reformatted as shown in Listing 7.2.

Listing 7.2  This Code Is the Same as Listing 7.1, Only It Has Been Formatted Differently

1 select * from ztxlfa1
2     where lifnr > '0000001050'
3     order by lifnr.
4     write: \ ztxlfa1-lifnr,
5              ztxlfa1-name1,
6              ztxlfa1-land1. endselect.

ABAP/4 code is not case sensitive.

Defining Data Objects

Data objects are memory locations that you use to hold data while the program is running. There are two types of data objects: modifiable and non-modifiable. The types of non-modifiable data objects are literals and constants. The modifiable data objects are variables, field strings, and internal tables. A field string is the ABAP/4 equivalent of a structure. An internal table is the ABAP/4 equivalent of an array.

When the program starts, the memory allocation for each data object occurs in the roll area of the program. While the program is running, you can read the contents of a non-modifiable data object or put data into a modifiable data object and then retrieve it. When the program ends, the system frees the memory for all data objects and their contents are lost.

Data objects have three levels of visibility: local, global, and external. The visibility of a data object indicates from where in the program the data object is accessible.

Locally visible data objects are accessible only from inside the subroutine in which they are defined. Globally visible objects can be accessed from anywhere within the program. Externally visible objects are accessible from outside of the program by another program. Figure 7.1 displays these three levels of visibility pictorially.

Figure 7.1 : The visibility of a data object indicates its accessibility. If it is locally visible, it is only accessible from within a subroutine. If it is globally visible, it is accessible from any-where within a program. If it is externally visible, it is accessible from outside of the program by another program.

In Figure 7.1, the local data objects in subroutine 1A are visible only from within that subroutine. Any statement outside of it cannot access them. Similarly, the local data objects in subroutines 1B and 2A are not accessible from anywhere but within those subroutines.

Any statement in program 1, regardless of where the statement appears, can access the global data objects in program 1. Similarly, any statement in program 2 can access the global data objects in program 2.

The external data objects could be accessed from any statement in program 1 or program 2. In actuality, whether they can be or not depends on the type of external memory area used and the relationship between the two programs. The details of this are described in the sections on SPA/GPA memory and on ABAP/4 memory.

Defining Literals

A literal is a non-modifiable data object. Literals can appear anywhere in a program, and they are defined merely by typing them where needed. There are four types: character string, numeric, floating-point, and hexadecimal.

Character String Literals

Character string literals are case-sensitive character strings of any length enclosed within single quotes. For example, 'JACK' is a character string literal containing only uppercase characters. 'Caesar the cat' is a character string literal containing a mixture of upper- and lowercase characters. Your first program used the character string literal 'Hello SAP world'.

Because a character string literal is enclosed by quotes, you cannot use a single quote by itself in the value of the literal. To represent a single quote, you must use two consecutive single quotes. For example, the statement write 'Caesar''s tail'. will write Caesar's tail, but the statement write 'Caesar's tail' will cause a syntax error because it contains a single quote by itself. The statement write ''''. will cause a single quote to be written to the output page because the two consecutive quotes within quotes are translated to a single quote. Lastly, write: '''', 'Hello Caesar', ''''. will write ' Hello Caesar '.

Here are some examples of invalid character string literals and the correct way to code them. "Samantha" is incorrect; it should be enclosed in single quotes, not double quotes, and thus should be coded 'Samantha'. In 'Never ending, the trailing quote is missing and thus should be coded 'Never ending'. 'Don't bite' should contain two consecutive single quotes; it should be coded 'Don''t bite'.

When a literal is involved in a comparison, as a rule of thumb you should always use uppercase between quotes. Comparisons with character string lit-erals are always case sensitive, so it is necessary to ensure you use the correct case to get the intended result. If the case doesn't match, usually the pro-gram will still run, but you will get either incorrect output or no output at all. 99.99 percent of the time, the values your character string literal will be compared with will be in uppercase. Therefore, always type the value for a character string literal in uppercase unless you know that it should be other-wise. For example, select single * from ztxlfa1 where lifnr = 'v1' will not find a record, but select single * from ztxlfa1 where lifnr = 'V1' will find a record. Did you notice the lowercase v?

Numeric Literals

Numeric literals are hard-coded numeric values with an optional leading sign. They are not usually enclosed in quotes. However, if a numeric literal contains a decimal, it must be coded as a character string enclosed within single quotes. If it is not, the syntax error Statement x is not defined. Please check your spelling. will occur. Table 7.1 shows the right and wrong ways to code literals.

For example, 256 is a numeric literal, as is -99. '10.5' is a numeric literal that contains a decimal point, so it is enclosed by single quotes. A literal can be used as the default value for a variable, or it can be used to supply a value in a statement. Examples of invalid literals are: 99- (trailing minus sign), "Confirm" (enclosed in double quotes), and 2.2 (contains a decimal but is not enclosed in quotes).

Floating-Point Literals

Floating-point literals are specified within single quotes as '<mantissa>E<exponent>'. The mantissa can be specified with a leading sign and with or without decimal places, and the exponent can be signed or unsigned, with or without leading zeros. For example, '9.99E9', '-10E-32', and '+1E09' are valid floating-point literals.

Hexadecimal Literals

A hexadecimal literal is specified within single quotes as if it were a character string. The permissible values are 0-9 and A-F. There must be an even number of characters in the string, and all characters must be in uppercase.

If you specify a hexadecimal literal using lowercase characters, you will not receive any warnings or errors. However, when your program runs, the value of the literal will be wrong.

Examples of valid hexadecimal literals are '00', 'A2E5', and 'F1F0FF'. Examples of invalid hexadecimal literals are 'a2e5' (contains lowercase characters), '0' (contains an uneven number of characters), "FF" (enclosed in double quotes), and x'00' (should not have a preceding x).

Hexadecimal values are rarely used in ABAP/4, because they are usually machine-dependent. The use of a hexadecimal value that creates machine dependence should be avoided.

Table 7.1 covers the right and wrong way of coding numeric and hexadecimal literals.

Table 7.1  Right and Wrong Ways to Code Literals
Trailing sign not permitted on a numeric unless it's within quotes.
Numerics within quotes can have leading'12-' or trailing sign.
Numerics containing a decimal point must be enclosed in single quotes.
Double quotes are not permitted.
To represent a single quote, use two consecutive single quotes.
Trailing quote is missing.
Floating-point values must be enclosed within quotes.
Lowercase e is allowed for floating-point literals.
Lowercase in hexadecimal literals gives incorrect results.
An uneven number of hexadecimal digits gives incorrect results.
A preceding or following character is not permitted for hexadecimal literals.

Defining Variables

Two statements are commonly used to define variables in an ABAP/4 program:

Using the data Statement to Define Variables

Using data statement, variables can be declared for the program. Variables defined in the data statement are assigned to a data type and can also have defaults.

Syntax for the data Statement
The following is the syntax for defining a variable using the data statement:
data v1[(l)] [type t] [decimals d] [value 'xxx'].
data v1 like v2 [value 'xxx'].
where: Listing 7.3 shows examples of variables defined with the data statement.

Listing 7.3  Examples of Variables Defined with the DATA Statement

1 data f1(2) type c.
2 data f2 like f1.
3 data max_value type i value 100.
4 data cur_date type d value '19980211'.

Variable names can be 1 to 30 characters long. They can contain any characters except
( ) + . , : and must contain at least one alphabetic character.
SAP recommends that variable names should always begin with a character and they should not contain a dash. A dash has special meaning (see field strings below). Instead of a dash, you should use an underscore ( _ ).
Do not use USING or CHANGING as variable names. Although they are syntacti-cally correct, they can cause problems if you try to pass them to subroutines.
The following points also apply to the data statement: The data statement can appear anywhere in a program. The definition for a variable must physically come before the statements that access it. If you place a data statement after executable code, the statements above it cannot access the variables it defines. For an example, see Listing 7.4.

Listing 7.4  Example of a Variable That Is Incorrectly Accessed Before It Is Defined

1 report ztx0704.
2 data f1(2) value 'Hi'.
3 write: f1, f2.
4 data f2(5) value 'there'.

The variable F2 is defined on line 4, and the write statement on line 3 is trying to access it. This will generate a syntax error. The data statement on line four should be moved before line 3.
It is good programming practice to place all data definitions together at the top of your program before the first executable statement.

ABAP/4 Data Types

There are two main categories of data in ABAP/4: character and numeric. Variables receive special treatment by the ABAP/4 processor based on their category that goes beyond the usual treatment given by other languages. Therefore, it is especially important for you to be able to recognize and distinguish between the character and numeric data types.

Character Data Types
The character data types are shown in Table 7.2. Notice that they include type n. Internal lengths are given in bytes. A dash in the Max length column appears for fixed length data types.

Table 7.2  List of Character Data Types


Any char
numeric text
8 (fixed)
6 (fixed)

The Default Initial Value column indicates the value given to the variable by default if you do not specify one using the value addition.
Internal Representation of Variables
Numeric text variables are called numeric character variables and hold unsigned positive integers. Each digit occupies one byte, and internally each is stored as a character. This is a character data type. It can only contain the characters 0-9.
Use numeric text to hold numbers that are used as unique identifiers, such as document numbers, account numbers, and order numbers. Also, use it for variables that hold a numeric extracted from a character data type. For example, if you were to extract the two-character month from a date field and needed a variable to store it, you should use a type n field.
Date and time are fixed length data types. You should not specify a length on the data statement for them. Values for date and time variables are always stored internally as YYYYMMDD and HHMMSS, respectively. The current date is available in the system field sy-datum and the current time in sy-uzeit.
The values of sy-datum and sy-uzeit are set at the beginning of program execution and do not change until the program ends. If you need access to the most current date and time during execution of a long-running pro-gram, use the statement get time. It updates the values of sy-datum and sy-uzeit to reflect the current date and time.

Absolute time values that have millisecond precision are not used in R/3. However, relative time values are available to millisecond precision. To obtain these, use the get run time statement and store them using data type i. See the chapter on runtime analysis for more details.
Numeric Data Types
The numeric data types are shown in Table 7.3. A dash in the Max Length column indicates the length cannot be changed. An asterisk indicates the attribute is machine-dependent.

Table 7.3  Numeric Data Types





-231 to +231
packed decimal
0-9 .
-1E-307 to 1E308

All of the variables in Table 7.3 are signed. In floating-point variables, the exponent is also signed.
Use integers for variables that will be involved in simple computations or when no decimal points are required. Variables such as counters, indexes, positions, or offsets are good examples.
A decimal variable stores (L*2)-1 digits, where L is the length of the variable in bytes. Decimal values are stored two digits per byte, except the end byte, which contains a single digit and a sign. The decimal point itself is not stored; it is an attribute of the definition. For example, data f1(4) type p defines a variable f1 that is four bytes long and can hold seven digits (plus a sign), as shown in Figure 7.2. data f2(3) type p decimals 2 defines a variable f2 that is three bytes long and can hold five digits (plus a sign). The definition data f3 type p defines a variable f3 capable of holding 15 digits because the default length for type p is 8.

Figure 7.2 : Packed decimal values are stored two digits per byte. The end byte is an exception; it stores a single digit and the sign. The decimal point is not stored and so does not take up any space in the field; it is part of the definition.

Floating-point variables are always approximate. They can be used for calculations requiring very large values or many decimal places. Precision up to 15 decimal places is possible, but this is hardware-dependent.
Be careful when you specify initial values on the data statement using the value addition. These values are not validated to see whether they are com-patible with the data type. Using the value addition, you can assign invalid values to integers, date and time variables, numeric text, packed decimal variables, or floating-point variables, either accidentally or intentionally. The results of this assignment are machine-dependent and are undefined.
Mapping DDIC Data Types to ABAP/4 Data Types
Data types in the Data Dictionary are built from the ABAP/4 data types. Table 7.4 shows common Data Dictionary data types and their corresponding ABAP/4 data definitions. L is the length specified in the domain. For a complete list, view the F1 help for the tables statement.

Table 7.4  Data Dictionary Data Types and Their Corresponding ABAP/4 Data Types
Data Type
Data Definition
Character c(L)
Client c(3)
Date d
Time t
Currency key c(5)
Currency p((L+2)/2)
Decimal p((L+2)/2)
Floating-point f
1-byte integer (none)
2-byte integer (none)
4-byte integer I
Language c(1)
Numeric text n(L)
Precision x(2)
Quantity p((L+2)/2)
Units c(L)

Using the parameters Statement to Define Variables

A parameter is a special type of variable that is defined using the parameters statement. parameters is a lot like the data statement, but when you run the program, the system will display the parameters as input fields on a selection screen before the program actually begins to execute. The user can enter or modify their values and then press the Execute button to begin program execution. You can use both parameters and data in the same program. The rules for parameter names are the same as for variable names, except for the following:

Syntax for the parameters Statement
The following code is the syntax for defining a variable using the parameters statement.
parameters p1[(l)] [type t] [decimals d] ...
parameters p1 like v1 ...
... [default 'xxx'] [obligatory] [lower case] [as checkbox] [radiobutton
    group g].
where: Listing 7.5 shows examples of parameters defined with the parameters statement.

Listing 7.5  Examples of Parameters Defined Using the PARAMETERS Statement

1 parameters p1(2) type c.
2 parameters p2 like p1.
3 parameters max_value type i default 100.
4 parameters cur_date type d default '19980211' obligatory.
5 parameters cur_date like sy-datum default sy-datum obligatory.

There are two variations of the parameters statement: parameter and para-meters. Operationally, there is no difference between the two; they are completely interchangeable. However, if you attempt to obtain F1 help on the parameter statement, none will be found. For this reason, I recommend that you use only the parameters statement.

A sample program using parameters is given in Listing 7.6, and the input screen it generates appears in Figure 7.3. Please run this report now.

Figure 7.3 : When you run report ztx0706, the parameters first appear on a selection screen. Obligatory parameters are indicated with question marks. To begin processing, the user must press the Execute button on the Application toolbar.

Listing 7.6  Example of a Program That Accepts Input Parameters Using the PARAMETERS Statement

1  report ztx0706.
2  parameters: p1(15) type c,
3              p2  like p1 obligatory lower case,
4              p3  like sy-datum default sy-datum,
5              cb1 as checkbox,
6              cb2 as checkbox,
7              rb1 radiobutton group g1 default 'X',
8              rb2 radiobutton group g1,
9              rb3 radiobutton group g1.
10  write: / 'You entered:',
11         / '  p1 =', p1,
12         / '  p2 =', p2,
13         / '  p3 =', p3,
14         / '  cb1=', cb1,
15         / '  cb2=', cb2,
16         / '  rb1=', rb1,
17         / '  rb2=', rb2,
18         / '  rb3=', rb3.

The additions to the parameters statement are described in Table 7.5.

Table 7.5  Additions to the PARAMETERS Statement and Their Uses
typeSame as the data statement.
DecimalsSame as the data statement.
LikeSame as the data statement.
DefaultSame as the value addition on the data statement.
ObligatoryThe user must enter a value into the field before the program will execute.
lower casePrevents values from being translated into uppercase.
as checkboxDisplays the input field as a check box.
Radiobutton group g Displays the input field as a radio button belonging to group g.

The following points also apply to the parameters statement:
When the selection screen is shown, obligatory fields contain a question mark. These indicate to the user which fields must be filled in before continuing.
Using the Addition: lower case
All values entered into a parameter are translated into uppercase by default. To turn off this translation, use the addition lower case. This addition only applies to character fields.
Using the Addition: as checkbox
A check box has only two states: ticked and clear. You use them when you want to present the user with an on/off or true/false type of choice. You can use more than one check box on a screen. If you have multiple check boxes on a screen, they operate completely independently from each another.
To display a parameter as a check box, use the addition as checkbox. You cannot specify a data type or length; it will default to type c and length 1. The parameter will contain a capital X if the check box is ticked; it will contain a blank if the check box is clear. If the check box should initially contain a tickmark, use a default value of capital X. Run program ztx506 to see the check box.
Space and capital X are the only valid values. No other values are valid for a check box.
Using the Addition: radiobutton group g
Like check boxes, a radio button also has two states: selected and not selected. Unlike check boxes, radio buttons never operate alone, they operate only in groups. You can have any number of radio buttons in a group, but only one can be selected at a time. They are used when you need to present the user with a list of alternatives in which only one option can be chosen.
To display a parameter as a radio button, use the addition radiobutton group g. You cannot specify a data type or length; it will default to type c and length 1. g is an arbitrary group name one to four characters long. You can have more than one group in a program.
The parameter will contain a capital X if the radio button is selected; it will contain a blank if it is not selected. To be initially selected, the radio button should contain a default value of capital X. No other values are valid for a radio button. Try it by running program ztx006.

Parameter Input Field Labels

On the selection screen to the left of each parameter's input field is a label. By default, the label is the same as the name of the parameter. You can set these labels manually. For parameters defined like Data Dictionary fields, you can retrieve the label automatically from the data element.

Changing Parameter Labels
Start the ScreenCam "How to Change Input Field Labels" now.
To change a parameter's input field label:
  1. Begin at the ABAP/4 Editor: Edit Program screen.
  2. Choose the menu path Goto->Text Elements. The ABAP/4 Text Elements screen is displayed. In the Program Field is your current program name.
  3. Select the Selection Texts radio button.
  4. Press the Change button. The ABAP/4 Text Elements: Change PARAMETERS/SELECT-OPTIONS screen is displayed. Here, you can manually enter labels in the Text column.
  5. Type field labels in the Text column.
  6. For a parameter defined like a DDIC field, you can retrieve labels from the data element. To retrieve a label from the data element for a single field, position your cursor on the field and choose the menu path Utilities->Copy DD Text. The medium-length field label from the data element appears, the Text field is protected, and the Type field changes to contain the characters DDIC. At the bottom of the window the message Dictionary texts transferred for selection xxx appears.
  7. To remove protection from a single field, position your cursor on the field and choose the menu path Utilities->No DD Text. The Text field becomes unprotected and the characters DDIC disappear from the Type field. At the bottom of the window the message Text for xxx no longer transferred from Dictionary. appears.
  8. To retrieve field labels for all parameters that are defined like DDIC fields, choose the menu path Utilities->Copy DD Texts. Field labels for all DDIC fields are retrieved and protected. Any existing values in the Text column are overwritten. At the bottom of the window the message All selection texts transferred from Dictionary appears.
  9. Press the Save button on the Application toolbar. At the bottom of the window, the message Text elements for program xxxxx in language E accepted appears.
  10. Press the Back button on the Application toolbar twice to return to your program.
If you want to override the DDIC label for some fields but not others, type your labels in the Text column and then choose the menu path Utilities->Supplement DD Texts. All blank Text fields will be filled from the Data Dictionary, leaving the values you entered alone.
If the label changes in the DDIC, the label onscreen is not automatically updated. To update it, you must go to the ABAP/4 Text Elements: Change PARAMETERS/SELECT-OPTIONS screen and choose either menu path Utilities->Copy DD Text or Utilities->Copy DD Texts.
The value addition on the parameters statement, as with data, is not vali-dated for compatibility with the data type. Giving a check box or a radio button a default value other than space or capital X is invalid. Although a cursory evaluation might not disclose problems, in-depth testing has uncovered unpredictable behavior in test programs.
Effect of Parameter Definitions: type Versus like
Always use the like addition to define a parameter. When you use it, the parameter acquires the following attributes from the Data Dictionary: A field label is acquired from the data element.
In addition to the advantages provided by the above, In view of all of these advantages, you should always use the like addition to define a parameter. This applies even to check boxes and radio buttons. If necessary, you should create a structure in the DDIC so that you can use like and at a minimum, provide F1 help. Note that F1 help is available even for radio buttons and check boxes.
Effect of a Check Table on a Parameter
If you define a parameter using like st-f1, and st-f1 has a check table, a down arrow appears at the end of the input field when you run the program. You can press the down arrow to obtain a list of valid values for that field. However, the value entered into a parameter input field is not validated against the check table. Validation only occurs for dialog screens such as those you have seen in transaction se16. The user can type any value into the input field and it will be passed to the program when he presses the Execute button.
You can perform your own selection-screen validations. They are detailed on Day 21, "Selection Screens."


DO use an underscore to make your vari-able names easier to read. DON'T use a dash in a variable name; a dash delimits the components of a field string.


Why do I need to code uppercase between quotes? How will I know if I need to code lowercase?
Most of the time, the system automatically converts data to upper case before it is stored in the database. This conversion is performed by the domain. You can determine if the data is converted by looking at the domain. If the data type of the field is CHAR, and if the Lower Case checkbox is tickmarked, only then does the field contains mixed case.
Can I define a parameter that accepts multiple values from the user?
Yes, the select-options statement enables the user to enter multiple values and complex criteria.


The Workshop provides you two ways for you to affirm what you've learned in this chapter. The Quiz section poses questions to help you solidify your understanding of the material covered and the Exercise section provides you with experience in using what you have learned. You can find answers to the quiz questions and exercises in Appendix B, "Answers to Quiz Questions and Exercises."


What is wrong with these literals, if anything? (There can be more than one error in each, and some do not have errors.) Write the correct definitions.

  1. Character string literal: "Don't bite."
  2. Floating-point literal: '+2.2F03.3'
  3. Numeric literal: -99
  4. Hexadecimal literal: x'0000f'
  5. Numeric literal: 9.9-
  6. Floating-point literal: '1.1E308'
  7. Hexadecimal literal: 'HA'
  8. Character string literal: ''''
  9. Character string literal: '''"'''

What is wrong with these data definitions? (There can be more than one error in each, and some do not have errors.) Write the correct definitions.

  1. data first-name(5) type c.
  2. data f1 type character.
  3. data f1 (20) type c.
  4. data 1a(5) type i.
  5. data per-cent type p value 55.5.
  6. data f1(2) type p decimals 2 value '12.3'.

Exercise 1

Write a program using parameters for Figure 7.4.

Figure 7.4 : .

© Copyright, Macmillan Computer Publishing. All rights reserved.