Sams Teach Yourself ABAP/4® in 21 Days


Day 8

Defining Data in ABAP/4, Part 2


Chapter Objectives

After you complete this chapter, you should be able to:

Defining Constants

A constant is almost identical to a variable except that its value cannot be changed. To define one, you use the constants statement.

Use a constant when you need to include the same literal multiple times in a program. You can define a constant with the same value as the literal and use the constant in the body of the program in place of the literal. Later, if you need to change the value of the literal, you can simply change the value of the constant, causing its value to be updated wherever it is used in the program.

ABAP/4 has one pre-defined constant: SPACE. It is a constant having a value equal to spaces. You can use it in place of the literal ' '.

Syntax for the CONSTANTS Statement

The following code demonstrates the syntax for defining a constant. It is similar to the data statement; however, the addition value is required. In all other ways, constants conform to the same rules as variables defined using the data statement. See Listing 8.1 for examples of constant definitions.

constants c1[(l)] [type t] [decimals d] value 'xxx'.

or

constants c1 like cv value 'xxx'.

where:


Listing 8.1  Definitions of Constants

1 constants c1(2) type c value 'AA'.
2 constants c2 like c1 value 'BB'.
3 constants error_threshold type i value 5.
4 constants amalgamation_date like sy-datum value '19970305'.

TIP
Constants can be defined in a type pool. When they are, they can be shared by multiple programs. For more information, see the section called "Type Pools" at the end of this chapter.

Defining Field Strings

A field string is a type of variable, and is the equivalent of a structure in the DDIC but is defined within an ABAP/4 program. Like a structure, a field string is a series of fields grouped together under a common name. The difference lies mainly in where the definition resides. The term structure in R/3 applies only to a Data Dictionary object containing a collection of fields. The term field string applies to a collection of fields defined in an ABAP/4 program.

Two statements are usually used to define field strings in an ABAP/4 program:

Using the DATA Statement to Define a Field String

A field string defined using the data statement is a modifiable data object. It can have global or local visibility.

Syntax for Defining a Field String Using the DATA Statement

The following is the syntax for defining a field string using the data statement.

data: begin of fs1,
        f1[(l)] [type t] [decimals d] [value 'xxx'],
        f2[(l)] [type t] [decimals d] [value 'xxx'],
        ...
        end of fs1.

or

data begin of fs1.
data f1[(l)] [type t] [decimals d] [value 'xxx'].
data f2[(l)] [type t] [decimals d] [value 'xxx'].
        ...
[include structure st1.]
data end of fs1.

or

data fs1 like fs2.

where:

Field strings follow the same rules as variables defined using the data statement. To refer to an individual component, its name must be prefixed by the name of the field string and a dash (-). For example, to write the number component of the cust_info field string, you would use the statement write cust_info-number.

The include statement is not part of the data statement; it is a separate statement. Therefore, it cannot be chained to a data statement. The statement before it must be concluded with a period.

Examples of programs that define and use field strings are shown in Listings 8.2 through 8.6.


Listing 8.2  A Simple Example of a Field String Defined Using the DATA Statement

 1 report ztx0802.
 2 data: begin of totals_1,
 3         region(7)    value 'unknown',
 4         debits(15)   type p,
 5         count        type i,
 6         end of totals_1,
 7       totals_2 like totals_1.
 8
 9 totals_1-debits = 100.
10 totals_1-count  = 10.
11 totals_2-debits = 200.
12
13 write: / totals_1-region, totals_1-debits, totals_1-count,
14        / totals_2-region, totals_2-debits, totals_2-count.

Line 2 begins the definition of field string totals_1. It contains three fields, the first of which is initialized with the value 'unknown'. On line 7, field string totals_2 is defined exactly like totals_1. The value of totals_1-region is not propagated to totals_2-region. On lines 9 through 11 values are assigned to components of the field strings, and on lines 13 and 14, the values of all components are written out.


Listing 8.3  A Field String Can Contain Another Field String

 1 report ztx0803.
 2 data: begin of names,
 3         name1        like ztxkna1-name1,
 4         name2        like ztxkna1-name2,
 5         end of names.
 6 data: begin of cust_info,
 7         number(10)   type n,
 8         nm           like names,         "like a field string
 9         end of cust_info.
10
11 cust_info-number   = 15.
12 cust_info-nm-name1 = 'Jack'.
13 cust_info-nm-name2 = 'Gordon'.
14
15 write: / cust_info-number,
16          cust_info-nm-name1,
17          cust_info-nm-name2.

Line 2 begins the definition of field string names. It contains two fields that are defined like fields of table ztxkna1 in the Data Dictionary. They are not given any initial values. On line 8, component cust_info-name is defined like field string names. When it is used on lines 12 and 13, nm is included in the component name.


Listing 8.4  A Field String Can Be Defined Exactly Like a DDIC Table or Structure

 1 report ztx0804.
 2 data: my_lfa1 like ztxlfa1,         "like a table in the DDIC
 3       my_addr like ztxaddr.         "like a structure in the DDIC
 4
 5 my_lfa1-name1 = 'Andrea Miller'.
 6 my_lfa1-telf1 = '1-243-2746'.
 7 my_addr-land1 = 'CA'.
 8
 9 write: / my_lfa1-name1,
10          my_lfa1-name2,
11          my_addr-land1.

On line 2, my_lfa1 is defined exactly like the DDIC table ztxlfa1, and my_addr is defined like the DDIC structure ztxaddr.

TIP
To view the DDIC definition of table ztxlfa1, double-click on its name in your source code.


Listing 8.5  DDIC Tables and Structures Can also be Included in a Field String

 1 report ztx0805.
 2 data    begin of fs1.
 3 include   structure ztxlfa1.
 4 data:     extra_field(3) type c,
 5           end of fs1.
 6
 7 fs1-lifnr       = 12.
 8 fs1-extra_field = 'xyz'.
 9
10 write: / fs1-lifnr,
11          fs1-extra_field.

Line 2 begins the definition of field string fs1. The statement ends with a period because include structure is not part of the data statement; it is a separate statement. On line 3, the structure of table ztxlfa1 is included into the field string. On line 4, another field is included in the field string after the fields of table ztxlfa1. Any number of fields could be included, more structures could be included here as well, or any combination thereof.


Listing 8.6  If You Use LIKE Instead of INCLUDE, You Get a Different Result. The Names of the Included Fields Are Prefixed by an Intermediate Component Name.

 1 report ztx0806.
 2 data: begin of fs1,
 3         mylfa1 like ztxlfa1,
 4         extra_field(3) type c,
 5         end of fs1.
 6
 7 fs1-mylfa1-lifnr  = 12.
 8 fs1-extra_field    = 'xyz'.
 9
10 write: / fs1-mylfa1-lifnr,
11          fs1-extra_field.

Line 2 begins the definition of field string lfa1_with_extra_field. The statement ends with a period because include structure is not part of the data statement; it is a separate statement. On line 3, the structure of table ztxlfa1 is included into the field string. On line 4, another field is included in the field string after the fields of table ztxlfa1. Any number of fields could be included, more structures could be included here as well, or any combination thereof.

Using a Field String as a Variable of Type char

Not only can you address the individual components of a field string, you can also address all components at once as if they were a single variable of type char. Listing 8.7 illustrates this concept.


Listing 8.7  An Example of Using a Field String as Both Multiple Variables and as a Single Variable of Type CHAR

 1 report ztx0807.
 2 data: begin of fs1,
 3         c1 value 'A',
 4         c2 value 'B',
 5         c3 value 'C',
 6         end of fs1.
 7
 8 write: / fs1-c1, fs1-c2, fs1-c3,
 9        / fs1.
10
11 fs1 = 'XYZ'.
12
13 write: / fs1-c1, fs1-c2, fs1-c3,
14        / fs1.

The code in Listing 8.7 should produce this output:

A B C
ABC
X Y Z
XYZ

Lines 2 through 6 define field string fs1. It has three components, each with a default value. On line 8, each component is written out individually. On line 9, the field string is written out as if it were a single variable. Consequently, the output shows the contents of fs1 as if it were a single variable defined as char 3. On line 11, the value 'XYZ' is assigned to the field string, again treating it as a char variable. The resulting output shows that the individual components reflect the change because they are accessing the same storage.

One field string can be assigned to another, if they have the same structure, as shown in Listing 8.8.


Listing 8.8  An Example of Assignment Involving Two Field Strings

 1 report ztx0808.
 2 data: begin of fs1,
 3         c1 value 'A',
 4         c2 value 'B',
 5         c3 value 'C',
 6         end of fs1,
 7       fs2 like fs1.
 8
 9 fs2 = fs1.
10 write: / fs2-c1, fs2-c2, fs2-c3.

The code in Listing 8.8 should produce this output:

A B C

Lines 2 through 6 define field string fs1. Line 7 defines field string fs2 exactly like fs1. On line 9, fs1 is moved to fs2, just as if it were a single variable of type char. On line 10, the components of fs2 are written out.

NOTE
A field string containing numeric data types needs special consideration dur-ing assignments. These considerations are covered on Day 9, in the "Assignments" section.

Using the TABLES Statement to Define a Field String

A field string defined using the tables statement is a modifiable data object. Field strings defined using the tables statement follow the same rules as field strings defined using the data statement. An example of a program using a tables field string appears in Listing 8.9.

Syntax for Defining a Field String Using the TABLES Statement

The following is the syntax for defining a field string using the tables statement.

tables fs1.

where:


Listing 8.9  Simple Example of a Field String Defined Using the TABLES Statement

1 report ztx0809.
2 tables ztxlfa1.
3
4 ztxlfa1-name1 = 'Bugsy'.
5 ztxlfa1-land1 = 'US'.
6
7 write: / ztxlfa1-name1, ztxlfa1-land1.

Line 2 defines field string ztxlfa1. Its definition is exactly like the Data Dictionary table of the same name. On lines 4 and 5, values are given to two of its components, which are written out on line 7.

Field String Defined Using TABLES Interacting with SELECT

The tables statement does more than just define a field string. It does two things:

Your first select statement example is reproduced in Listing 8.10. You can now analyze it from a new perspective.


Listing 8.10  Your Second Program, Revisited

1 report ztx0810.
2 tables ztxlfa1.
3 select * from ztxlfa1 into z lfa1 order by lifnr.
4     write / z lfa1-lifnr.
5     endselect.

Line 2 defines field string ztxlfa1. Its definition is exactly like the Data Dictionary table of the same name. There is also a database table of the same name, so the program is given access to that table, meaning that it can now be used in a select statement. Each time line 3 is executed, a record is read from the database table ztxlfa1 into field string ztxlfa1. For each record, the value of component ztxlfa1-lifnr is written out (line 4).

Visibility of a Field String Defined Using TABLES

A field string defined using tables always has both global and external visibility no matter where it is defined in the program. This means that if you place a tables statement in a subroutine, the definition is global and you cannot have another definition for the same field string anywhere in that program.

The field string is also externally visible. This means that if, in a calling and called program, the same tables statement appears, those field strings will share the same memory. This concept is illustrated in Figure 8.1. When the called program executes, it will "see" the value in ztxlfa1 from the first program. If it changes ztxlfa1, the calling program "sees" the changes when it regains control.

Figure 8.1 : Identical tables definitions in a calling and called program causes the memory for those field strings to be shared.

Defining Types

You can define your own data types using the types statement and base them on existing data types.

Syntax for the TYPES Statement

The following is the syntax for defining a type using the types statement.

types t1[(l)] [type t] [decimals d].

or

types t1 like v1.

where:

Listings 8.11 and 8.12 show examples of programs that define and use their own data types.


Listing 8.11  Simple Example of a User-Defined Data Type CHAR2

1 report ztx0811.
2 types char2(2) type c.
3 data: v1 type char2 value 'AB',
4       v2 type char2 value 'CD'.
5
6 write: v1, v2.

The code in Listing 8.11 produces this output:

AB CD

Line 2 defines a data type named char2. It is a two-byte char field. On lines 3 and 4, variables v1 and v2 are defined as two-byte char fields using the data type char2. They are given default values and, on line 6, they are written out.


Listing 8.12  Using Types Can Make Your Code Clearer and Easier to Read

1  report ztx0812.
2  types: dollars(16) type p decimals 2,
3         lira(16)    type p decimals 0.     "italian lira have no 
        decimals
4
5  data: begin of american_sums,
6             petty_cash type dollars,
7             pay_outs   type dollars,
8             lump_sums  type dollars,
9             end of american_sums,
10        begin of italian_sums,
11            petty_cash  type lira,
12            pay_outs    type lira,
13            lump_sums   type lira,
14            end of italian_sums.
15
16 american_sums-pay_outs = '9500.03'.       "need quotes when literal 
     contains a decimal
17 italian_sums-lump_sums = 5141.
18
19 write: / american_sums-pay_outs,
20        / italian_sums-lump_sums.

The code in Listing 8.12 produces this output:

          9,500.00
             5,141

Line 2 defines a data type named dollars as a 16-byte packed decimal field with two decimal places. Line 3 defines a similar data type named lira with 0 decimal places. On lines 5 through 14, two field strings are defined using the new data types. One component of each is assigned a value on lines 16 and 17, and on lines 19 and 20 they are written out.

Think of a user-defined type as a variable, but one that you can't use to store data. It can only be used to create other variables. The same rules apply to types as apply to variables and field strings. Type names, like variable names, are one to 30 characters long, but unlike variables, their names cannot include the characters - < >.

Structured Types

A user-defined type can be based on the definition of a field string. This is known as a structured type. Listing 8.13 shows how you can shorten a program using a structured type.


Listing 8.13  Using Structured Types can Reduce Redundancy and Make Maintenance Easier

 1 report ztx0813.
 2 types: begin of address,
 3            street(25),
 4            city(20),
 5            region(7),
 6            country(15),
 7            postal_code(9),
 8            end of address.
 9
10  data: customer_addr type address,
11        vendor_addr   type address,
12        employee_addr type address,
13        shipto_addr   type address.
14
15 customer_addr-street  = '101 Memory Lane'.
16 employee_addr-country = 'Transylvania'.
17
18 write: / customer_addr-street,
19          employee_addr-country.

Lines 2 through 8 define a data type named address that contains five fields. On lines 10 through 13, four field strings are defined using the new type. Without the new type, these definitions would have used an additional 24 lines of code. Maintenance is also made easier: If a change to the definitions of the address field strings is needed, only the definition of the type needs to be changed.

Type Groups

A types statement can be stored in a type group. A type group (also known as a type pool) is a Data Dictionary object that exists merely to contain one or more types or constants statements. Using the type-pools statement in your program, you access types or constants from a type group and use them in your program. Multiple programs can share a type group, giving you the ability to create centralized definitions. Figure 8.2 illustrates this concept. Listing 8.14 contains an example of a type group, and Listing 8.15 presents an example of a program using types and constants from it.

Figure 8.2 : A type group is a container for types and constants statements. It can be shared among programs.


Listing 8.14  An Example type-pool Statement Containing Types and Constants

1 type-pool ztx1.
2 types:     ztx1_dollars(16)         type p decimals 2,
3            ztx1_lira(16)            type p decimals 0.
4 constants: ztx1_warning_threshold   type i value 5000,
5            ztx1_amalgamation_date   like sy-datum value '19970305'.

Line 1 indicates the beginning of the type group and gives it a name. Lines 2 through 5 define types and constants that can be used in any program.


Listing 8.15  Using Type Group Reduces Duplication of Code for Easier Maintenance

 1 report ztx0815.
 2 type-pools ztx1.
 3 data: begin of american_sums,
 4           petty_cash type ztx1_dollars,
 5           pay_outs   type ztx1_dollars,
 6           lump_sums  type ztx1_dollars,
 7           end of american_sums.
 8
 9 american_sums-pay_outs = '9500.03'.
10
11 if american_sums-pay_outs > ztx1_warning_threshold.
12     write: / 'Warning', american_sums-pay_outs,
13              'exceeds threshold', ztx1_warning_threshold.
14     endif.

Line 2 includes the definitions from type group ztx1 in the program. Lines 3 through 7 define a field string using type ztx1_dollars from the type group. Line 9 assigns a value to pay_outs, and it is compared with constant ztx1_warning_threshold from the type group on line 11.

If the type group has already been included, subsequent attempts to include it are ignored and they do not cause an error.

Type group names can be one to five characters long, and must begin with y or z. Types and constants included in a program using the type-pools statement always have global visibility.

Creating a Type Group

To create a type group in the Data Dictionary, use the following procedure.

Start the ScreenCam "How to Create a Type Group" now.

To create a type group:

  1. Begin at the Dictionary: Initial Screen (menu path Tools->ABAP/4 Workbench, Development->ABAP/4 Dictionary).
  2. Type the name of your type group in the Object Name field.
  3. Select the Type Groups radio button.
  4. Press the Create pushbutton. The Type Group xxxx: Create Text screen is displayed.
  5. Type a description of your type group in the Short Text field.
  6. Press the Save button. The Create Object Catalog Entry screen is displayed.
  7. Press the Local Object button. The ABAP/4 Editor: Edit Type Group screen is
    displayed. On the first line, the statement type-pool t. appears, where t is the name of your type group. If it does not appear, you should type it now.
  8. On subsequent lines, type constants and types statements. All names must begin with t_, where t is the name of your type pool.
  9. Press the Save button on the Application toolbar. At the bottom of the window, the message Type group saved is displayed.
  10. Press the Back button on the Application toolbar to return to the Dictionary: Initial Screen.

To delete a type group, follow steps 1 through 3 of the preceding procedure and then press the Delete button on the Application toolbar.

Summary

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

Q&A

Q
Why do I need to create field strings? Why can't I use just simple variables?
A
Field strings give you a way of organizing your variables into groups. When you have hundreds of variables in a program, organizing them into field strings makes the relationships between the variables clearer. Using field strings to group fields together also enables you to perform an operation on a group of variables as if they were a single variable. So, for example, if you need to move 100 variables, you can usually code a single statement to perform the move from one field string to another, instead of coding 100 assignment statements for individual variables. Moving a single field string is also more efficient than 100 move statements, so your program runs faster. You will see in the coming chapters that many statements can use a field string as an operand. If you can use field strings, you can take advantage of them, and they will save you a lot of coding and debugging time.
Q
Why would I use my own structured type instead of a DDIC structure? Can't I create field strings with both?
A
Yes, you can. The functionality of DDIC structures far outweighs that provided by structured types because they can provide labels, F1, and F4 help. However, types can be used to define nested structured types that contain internal tables. DDIC structures can't. This will be demonstrated in Chapter 12 in the section on internal tables.

Workshop

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."

Quiz

  1. What is the one pre-defined constant that can be used in an ABAP program. What is its equivalent using a literal?
  2. What types of type statement can be used and what type can be defined in the Data Dictionary?

Exercise 1

What is another way to declare the variable below using a "type" declaration?

data: begin of usd_amount,
           hotel      type p decimals 2,
           rent_car   type p decimals 2,
           plane      type p decimals 2,
           food       type p decimals 2,
           end of usd_amount,
      begin of amex_pt,
           hotel      type p decimals 2,
           rent_car   type p decimals 0,
           plane      type p decimals 0,
           food       type p decimals 0,
           end of amex_pt.

Exercise 2

What is the outcome of this program?

report ztx0816.

data: begin of fld_stg1,
       var1 value '1',
       var2 value '3',
       var3 value '5',
       var4 value '7',
       var5 value '9',
       var6 value '4',
       var7 value '8',
       var8 value '6',
       end of fld_stg1,
      fld_stg2 like fld_stg1.

fld_stg2 = fld_stg1.

write: / fld_stg2-var1, fld_stg1-var2, fld_stg2-var6, fld_stg1-var3.
write: / fld_stg1-var5, fld_stg2-var7, fld_stg2-var4, fld_stg1-var8.


© Copyright, Macmillan Computer Publishing. All rights reserved.