BC402 - ABAP Programming Techniques
Short Description
Descripción: abap...
Description
Release 470
12.06.2003
BC402 ABAP Programmiertechniken............................................................................................................. 7
ABAP Workbench......................................................................................................................8 ITS..............................................................................................................................................9 Course Prerequisites.................................................................................................................10 Target Group............................................................................................................................11 Course Goal..............................................................................................................................11 Course Objectives....................................................................................................................12 Course Content.........................................................................................................................13 Course Overview......................................................................................................................14 Main Business Scenario...........................................................................................................15 ABAP Runtime Environment....................................................................................................................... 1
ABAP Runtime Environment Unit Objectives..........................................................................2 Overview: ABAP Runtime Environment...................................................................................3 Structure of an ABAP Program..................................................................................................4 Components of an ABAP program............................................................................................5 Structure of an ABAP program..................................................................................................6 Program Organization................................................................................................................7 Overview - Concept of Inactive Sources....................................................................................8 Developed Version.....................................................................................................................9 Generated Version....................................................................................................................10 Active and Inactive Version.....................................................................................................11 Activate....................................................................................................................................12 Overview - Execution of an ABAP Program...........................................................................13 General ABAP Program Execution..........................................................................................14 Executing a Dialog Transaction...............................................................................................15 Executing an Executable Program...........................................................................................16 Selection Screen Events...........................................................................................................17 List Processing Events.............................................................................................................18 Non-Executable Programs........................................................................................................19 The ABAP Runtime Environment:Unit Summary...................................................................20 ABAP Runtime Environment Exercise....................................................................................21 ABAP Runtime Environment Solutions..................................................................................23 Data Objects, Types, and Statements........................................................................................................ 1
Data Objects, Types, and Statements:Unit Objectives...............................................................2 Overview - Data Objects, Types, and Statements......................................................................3 Overview - Introduction.............................................................................................................4 Definition of Data Objects.........................................................................................................5 Predefined ABAP Types............................................................................................................6 Visibility of Data Objects...........................................................................................................7 Preview: Visibility Areas in Objects..........................................................................................8 Lifetime of Data Objects............................................................................................................9 Overview - Definition of Data Objects....................................................................................10 Definition of Elementary Data Objects....................................................................................11 Runtime Behavior: Initial Value and Start Value....................................................................12 Runtime Behavior: Fields of Dynamic Length........................................................................13 Overview - Numeric data objects.............................................................................................14 Integers and Integer Arithmetic................................................................................................15 Packed Numbers and Fixed Point Arithmetic..........................................................................16 Floating Point Arithmetic.........................................................................................................17 (C) SAP AG
BC402
1
Summary: Recommendations for Using Numeric Data Types................................................18 Calculations: Syntax................................................................................................................19 Arithmetic on Mixed Expressions I.........................................................................................20 Arithmetic on Mixed Expressions II........................................................................................21 Overview - Strings...................................................................................................................22 Predefined ABAP Types for Strings........................................................................................23 Overview: Processing Strings..................................................................................................24 Date Fields................................................................................................................................25 Overview - Automatic type conversion...................................................................................26 Assigning Values......................................................................................................................27 Automatic Type Conversion when Assigning Values.............................................................28 Overview - Fixed-Length Data Objects...................................................................................29 Literals......................................................................................................................................30 Constants..................................................................................................................................31 Text Symbols............................................................................................................................32 Overview - Structures...............................................................................................................33 Definition of Structures............................................................................................................34 Definition of Nested Structures................................................................................................35 Using Named Includes.............................................................................................................36 Value Assignments Using Compatibly-Typed Structures.......................................................37 Value Assignments in String Structures...................................................................................38 Dangers of Assigning Values Between Incompatible Structures.............................................39 Assigning Values to Identically-Named Structure Components..............................................40 Data Objects, Types, and Statements: Unit Summary.............................................................41 Optional Exercise.....................................................................................................................42 Optional Exercise Solutions.....................................................................................................49 Global Types and Global Constants........................................................................................................... 1
Global Types and Global Constants:Unit Objectives................................................................2 Overview - Global Types and Global Constants........................................................................3 Overview: ABAP Dictionary.....................................................................................................4 Overview: Advantages of Global Types....................................................................................5 Advantages for User Dialogs.....................................................................................................6 Advantages When Using Database Dialogs...............................................................................7 Advantages of Reuse..................................................................................................................8 Example: Defining Types for Interface Parameters...................................................................9 Overview of Global Types.......................................................................................................10 Overview: Global Types..........................................................................................................11 Mapping Dictionary Types to ABAP Types............................................................................12 Examples of Predefined Dictionary types................................................................................13 Overview: Elementary Global Types and Their Use...............................................................14 Attributes of Data Elements.....................................................................................................15 Using Data Elements in ABAP Programs................................................................................16 Overview: Structure Types and Their Use...............................................................................17 Structures in the ABAP Dictionary..........................................................................................18 Using Structures for Data Objects............................................................................................19 Using Elementary Structure Components for Selection Screens.............................................20 Using Elementary Structure Components for Screens.............................................................21 Overview: Global Constants (Using Type Groups).................................................................22 Type Groups in the ABAP Dictionary.....................................................................................23 Global Types and Global Constants:Unit Summary................................................................24 Global types Exercise...............................................................................................................25 (C) SAP AG
BC402
2
Global types: Solutions............................................................................................................27 Control Statements..................................................................................................................................... 1
Control Statements: Unit Objectives..........................................................................................2 Overview: Control Statements...................................................................................................3 Overview: Control Structures.....................................................................................................4 Control Structures......................................................................................................................5 Overview: Conditional Branching.............................................................................................6 Conditional branching................................................................................................................7 The CASE Control Structure......................................................................................................8 Overview: Logical Expressions...............................................................................................10 Logical Expressions with Simple Comparisons.......................................................................11 Automatic Type Conversion in Logical Expressions...............................................................12 Comparison Operators for Strings............................................................................................13 Overview: Loops......................................................................................................................14 Index-Controlled Loops...........................................................................................................15 Loops: Testing Condition on Entry..........................................................................................16 Overview - Jump Statements....................................................................................................17 Overview: Leaving Processing Blocks....................................................................................18 Catching Runtime Errors..........................................................................................................19 Catching Runtime Errors..........................................................................................................20 Example: Catching Runtime Errors.........................................................................................21 Example: Solution, Part 1........................................................................................................22 Example: Solution, Part 2........................................................................................................23 Example: Solution, Part 3........................................................................................................24 Example: Solution, Part 4........................................................................................................25 Control Statements: Unit Summary.........................................................................................26 Control Statements Exercise....................................................................................................27 Control Statements Solutions...................................................................................................29 Internal Tables............................................................................................................................................ 1
Internal Tables: Unit Objectives................................................................................................2 Overview: Internal Tables..........................................................................................................3 Overview: Introduction and Advantages of Internal Tables......................................................4 The Internal Table - a Data Object of Variable Length.............................................................5 Attributes of Internal Tables......................................................................................................6 Table Kinds................................................................................................................................7 The Link Between the Table Kind and the Access Type...........................................................8 Overview: Definition..................................................................................................................9 Overview: Types of Definitions for Internal Tables................................................................10 The Data Type of the Internal Table........................................................................................11 Table Attributes: Line Type....................................................................................................12 Table Attributes: Table Kind and Key....................................................................................13 Example: Standard Table with Local Type.............................................................................14 Example: Sorted and Hashed Table........................................................................................15 The Standard Table Type.........................................................................................................16 Overview: Operations..............................................................................................................17 Overview: Types of Operations...............................................................................................18 Ascertaining Internal Table Attributes.....................................................................................19 Limiting the Scope of Line Operations: Target Records and Access Type.............................20 Background Information: Field Symbols.................................................................................21 Overview: Operations on Lines................................................................................................22 (C) SAP AG
BC402
3
Insert.........................................................................................................................................23 Reading a Single Record into a Work Area Using the Line Number......................................24 Reading a Single Record into a Work Area Using the Field Contents....................................25 Reading a Single Record Using a Field Symbol......................................................................26 Changing the Table Using a Work Area..................................................................................27 Changing a Single Record Using a Field Symbol....................................................................28 Delete.......................................................................................................................................29 Loop Processing.......................................................................................................................30 Overview: Notes on Performance............................................................................................31 Loop Processing and Table Kinds............................................................................................32 Accessing Single Records:Completely and Partly Qualified Keys..........................................33 Access Using Field Symbols....................................................................................................34 Overview: Special Situations...................................................................................................35 Internal Tables with an Unstructured Line Type.....................................................................36 Internal Tables with a Header Line..........................................................................................37 Selection Options and Selection Tables...................................................................................38 Internal Tables: Unit Summary................................................................................................39 Internal Tables:Exercise...........................................................................................................40 Internal Tables Solutions..........................................................................................................47 Subroutines................................................................................................................................................. 1
Subroutines: Unit Objectives.....................................................................................................2 Overview: Definition..................................................................................................................3 Overview - Definition of Subroutines........................................................................................4 Structure of a Subroutine............................................................................................................5 Data Passing Methods................................................................................................................6 Defining Types for Interface Parameters...................................................................................7 Overview: Calling Subroutines..................................................................................................8 Calling a Subroutine...................................................................................................................9 Visibility of Global and Local Data Objects............................................................................10 Runtime Behavior 1.................................................................................................................11 Runtime Behavior 2.................................................................................................................12 Runtime Behavior 3.................................................................................................................13 Runtime Behavior 4.................................................................................................................14 Runtime Behavior 5.................................................................................................................15 Runtime Behavior 6.................................................................................................................16 Runtime Behavior 7.................................................................................................................17 Syntax Example: Defining and Calling a Subroutine..............................................................18 Overview of Applied Example: Recursive Call.......................................................................19 Example: Recursive Call 1.......................................................................................................20 Example: Recursive Call 2.......................................................................................................21 Example: Recursive Call 3.......................................................................................................22 Subroutines: Unit Summary.....................................................................................................23 Subroutines Exercise................................................................................................................24 Subroutines Solutions...............................................................................................................28 Function Groups and Function Modules..................................................................................................... 1
Function Groups and Function Modules: Unit Objectives.........................................................2 Overview: Function Groups and Function Modules..................................................................3 Function Modules Compared to Subroutines.............................................................................4 Overview: Creating Function Modules......................................................................................5 Attributes....................................................................................................................................6 (C) SAP AG
BC402
4
Interface......................................................................................................................................7 Processing Logic........................................................................................................................8 Exceptions..................................................................................................................................9 Documenting, Activating, and Testing....................................................................................10 Call...........................................................................................................................................11 Overview: Working with Function Groups..............................................................................12 Function Groups.......................................................................................................................13 Applied Example......................................................................................................................14 Applied Example:Implementing the Functions 1.....................................................................15 Applied Example:Implementing the Functions 2.....................................................................16 Applied Example:Implementing the Functions 3.....................................................................17 Organization of a Function Group...........................................................................................18 Function Groups and Function Modules:Unit Summary.........................................................19 Function Groups and Function ModulesExercise....................................................................20 Function Groups and Function Modules: Solutions.................................................................29 Introduction to ABAP Objects..................................................................................................................... 1
Introduction to ABAP Objects:Unit Objectives.........................................................................2 Overview: Introduction to ABAP Objects.................................................................................3 Functional and Object-Oriented Programming..........................................................................4 From Function Groups to Classes I............................................................................................5 From Function Groups to Classes II..........................................................................................6 Position of ABAP Objects..........................................................................................................7 Overview: Definition of Data Objects.......................................................................................8 Defining Classes.........................................................................................................................9 Constructors.............................................................................................................................10 Applied Example: Declaration.................................................................................................11 Applied Example: Method.......................................................................................................12 Overview: Working with Objects............................................................................................13 Declaring Reference Variables.................................................................................................14 Creating Objects.......................................................................................................................15 Reference Semantics I..............................................................................................................16 Reference Semantics II.............................................................................................................17 Reference Semantics III...........................................................................................................18 Initializing Reference Variables...............................................................................................19 Garbage Collection I................................................................................................................20 Garbage Collection II...............................................................................................................21 Reinstantiation..........................................................................................................................22 Calling Methods.......................................................................................................................23 Independence of Instances.......................................................................................................24 Overview: Working with Interfaces.........................................................................................25 Interfaces..................................................................................................................................26 Defining Interfaces...................................................................................................................27 Applied Example: Declarations...............................................................................................28 Applied Example: Implementations.........................................................................................29 Interface References: Semantics..............................................................................................30 Calling Interface Methods........................................................................................................31 Interim Status...........................................................................................................................32 ABAP Objects: Advanced Topics............................................................................................33 Overview: Working with Events..............................................................................................34 Events.......................................................................................................................................35 Triggering Events.....................................................................................................................36 (C) SAP AG
BC402
5
Handling Events.......................................................................................................................37 Summary:Definitions in Event Triggers and Handlers............................................................38 Registering Event Handlers......................................................................................................39 Applied Example: Trigger event..............................................................................................40 Applied Example: Handling an Event......................................................................................41 Applied Example: Registering Event Handlers.......................................................................42 Preview: Preview: Class Builder (Technical View).................................................................43 Introduction to ABAP Objects:Unit Summary........................................................................44 Calling Programs and Passing Data........................................................................................................... 1
Calling Programs and Passing Data:Unit Objectives.................................................................2 Overview: Calling Programs and Passing Data.........................................................................3 Overview: Synchronous Program Calls.....................................................................................4 Synchronous Program Calls.......................................................................................................5 Executing an Executable Program.............................................................................................6 Calling a Transaction.................................................................................................................7 Overview: Memory Management..............................................................................................8 Logical Memory Model.............................................................................................................9 Inserting a Program I...............................................................................................................10 Inserting a Program II..............................................................................................................11 Terminating the Inserted Program............................................................................................12 Starting a New Executable (Type 1) Program I.......................................................................13 Starting a New Executable (Type 1) Program II......................................................................14 Starting A Transaction I...........................................................................................................15 Starting A Transaction II..........................................................................................................16 Calling Function Modules I......................................................................................................17 Calling Function Modules II....................................................................................................18 Overview: Transferring Data...................................................................................................19 Overview: Passing Data Between Programs............................................................................20 Passing Data Using the Program Interface...............................................................................21 Passing Values for Input Fields................................................................................................22 ABAP Memory and SAP Memory...........................................................................................23 Passing Data Using the ABAP Memory..................................................................................24 Passing Parameters using SAP Memory..................................................................................25 Preview: Passing Data Using an Internal Table.......................................................................26 Fields in the Global Type BDCDATA.....................................................................................27 Example: Passing Data Using an Internal Table......................................................................28 Calling Programs and Passing Data:Unit Summary................................................................29 Dynamic Programming............................................................................................................................... 1
Dynamic Programming:Unit Objectives....................................................................................2 Overview: Dynamic Programming............................................................................................3 Using Dynamic Attributes in Statements...................................................................................4 Field Symbols.............................................................................................................................5 The CASTING Addition............................................................................................................6 References..................................................................................................................................7 Declaring Data Objects Dynamically: Example........................................................................8 Dynamic Type Descriptions for RTTI Classes..........................................................................9 Declaring Types Dynamically: Example.................................................................................10 Dynamic Programming: Unit Summary..................................................................................11 Appendix A................................................................................................................................................. 1
Appendix A: System Architecture.............................................................................................2 (C) SAP AG
BC402
6
The Three-Tier Client/Server Architecture of the R/3 System..................................................3 Structure of a Work Process.......................................................................................................4 Appendix A: Strings...................................................................................................................5 Overview: Processing Strings....................................................................................................6 Searching in a String..................................................................................................................7 Splitting and Joining Strings......................................................................................................8 Changing Strings........................................................................................................................9 Accessing Parts of Fields.........................................................................................................11 Appendix A: Internal Tables....................................................................................................12 Inserting a Single Record by Summation.................................................................................13 Appending a Single Record......................................................................................................14 Appendix B: Selection Table....................................................................................................................... 1
System R/3, Release 4.6C, January 2001, Materialnummer: 5004 1776
(C) SAP AG
BC402
7
0.2 ABAP Workbench Level 2
3 days BC402 ABAP Programming Techniques 3 days BC404 ABAP Objects: Object Oriented Programming in R/3 BC405 3 days Techniques of List Processing and InfoSet Query
BC400 5 days ABAP Workbench: Foundations and Concepts MBC40
2 days
Managing ABAP Developments Projects
BC410 Programming User Dialogs
5 days
BC420 Data Transfer
5 days
BC412 3 days Dialog Programming using EnjoySAP Controls
BC430 ABAP Dictionary
2 days
BC460 3 days SAPscript: Forms Design and Text Management
(C) SAP AG
CA610 (Rel. 4.0) 2 days CATT:Test Workbench and Computer Aided Test Tool
BC402
BC490 3 days ABAP Performance Tuning
2 days BC415 Communication Interfaces in ABAP BC425 3 days Enhancements and Modifications
BC470 2 days Form Printing Using SAP Smart Forms
SAP AG 1999
Level 3 BC414 3 days Programming Database Updates
Recommended supplementary courses are: Business Process Technologies CA925, CA926, CA927 BC095 (Business Integ. Techn.) BC619 (ALE), BC620, BC621
8
0.3 ITS Level 3 Level 3
Level 2 Level 2
BC400 5 days ABAP Workbench: Foundation and Concepts
ITS100 2 days Developing EasyWebTransactions
ITS050 3 days SAP Internet Transaction Server: Foundations
2 days ITS110 Developing Web Scenarios and MiniApps using ITS Flow Logic ITS150
2 days
Corporate Identity Design ITS070 2 days SAP Internet Transaction Server: Administration SAP AG 1999
(C) SAP AG
BC402
9
0.4 Course Prerequisites
SAP 50 (Basis Technology) BC400 (ABAP Workbench: Concepts and Tools) Recommended:
BC430 (ABAP Dictionary)
A little ABAP programming experience
SAP AG 1999
(C) SAP AG
BC402
10
0.5 Course Goal
This course will enable you to: Understand the basic principles of the ABAP
programming language Choose the appropriate ABAP programming
technique to solve a particular problem Write and maintain your own ABAP programs
SAP AG 1999
(C) SAP AG
BC402
11
0.6 Course Objectives
At the conclusion of this course, you will be able to: Describe how the ABAP runtime system works Use ABAP statements and their syntax variants Create, test, compare, and classify ABAP programs Design, write, and modify your own ABAP programs Evaluate alternative programming solutions for data
consistency, possible runtime errors, and the effectiveness of the modularization techniques they use
SAP AG 1999
(C) SAP AG
BC402
12
0.7 Course Content Preface Unit 1
Course Overview
Unit 7
Subroutines
Unit 2
ABAP Runtime Environment
Unit 8
Function Groups and Function Modules
Unit 3
Data Objects, Types and Statements
Unit 9
Introduction to ABAP Objects
Unit 4
Global Types and Global Constants
Unit 10
Calling Programs and Passing Data
Unit 5
Control Statements
Unit 11
Dynamic Programming
Unit 6
Internal Tables The exercises and solutions are at the end of the relevant unit.
Appendix
SAP AG 1999
(C) SAP AG
BC402
13
0.8 Course Overview
Data ABAP Program
Operations
ce ul e rfa od e t In on m ti nc Fu
Object Data Interface Interface
Method
Subroutine Data
SAP AG 1999
(C) SAP AG
BC402
14
0.9 Main Business Scenario
You will use the ABAP Workbench to develop simple busness applications. These are based on the tables, data, and ABAP Dictionary objects of the flight data model. In this course, you will only read the flight data. You will process the data in your programs, but the actual data in the database will not be changed. You will also use, analyze, copy, and modify existing Repository objects.
SAP AG 1999
(C) SAP AG
BC402
15
1 ABAP Runtime Environment
Contents Components of an ABAP program Processors within a work process ABAP programs: Types and execution methods
SAP AG 1999
(C) SAP AG
BC402
1
1.2 ABAP Runtime Environment Unit Objectives
At the conclusion of this unit, you will be able to: Name the components of an ABAP program Describe how an ABAP program is organized Take technical aspects of program execution into account when you write an ABAP program
SAP AG 1999
(C) SAP AG
BC402
2
1.3 Overview: ABAP Runtime Environment
Data ABAP program
Operations
ti nc Fu
Object
o
nm
ul e od
Data Method
Subroutine
Data
SAP AG 1999
(C) SAP AG
BC402
3
1.4 Structure of an ABAP Program Structure Structure of of an an ABAP ABAP program program Concept Concept of of inactive inactive sources sources Execution Execution of of an an ABAP ABAP program program
SAP AG 1999
(C) SAP AG
BC402
4
1.5 Components of an ABAP program Source code PROGRAM sapbc402_rund_test. TYPES ... DATA ... CLASS ... DEFINTION. TYPES ... DATA ... ENDCLASS. CLASS ... IMPLEMENTATION. ... ENDCLASS. MODULE s_100 OUTPUT. ... ENDMODULE. INITIALIZATION. ... START-OF-SELECTION. ... FORM calc USING ... CHANGING ... TYPES ... DATA ... ... ENDFORM.
Documentation
Values in variants
Screens
Application Help
xy 007 xz 008
Verwendung ... Integration ...
Texts
Interface
Attributes
Object Favorites Utilities Settings System Help Data Edit Goto Extras Environment System Help Continue
Hallo Welt! Hello world! ¡Hola mundo!
FirstContinue line LastFirst line line BackLast line MoreBack lines < First screen Erstes Tabellentyp More < Letztes BildBild BackTable typeFirstLast fieldscreen First Back Last fieldfield Last field
Attributes
Attributes SAP AG 1999
An ABAP program contains the following components: Processing blocks... contain the ABAP statements Attributes ... among other things, contain technical settings the system needs to execute the program. Screens... These consist of the screen layout and associated flow logic. You normally create the layout of a screen using the Screen Painter. However, there are special kinds of screens, called selection screens and lists, whose layout and flow logic are designed exclusively using ABAP statements. Interface... The interface contains all of the entries in the menus, the standard toolbar, the application toolbar, and function key settings. It contains titles and statuses. A status is a collection of function key settings and menus. Texts ... are language specific. This means that all short texts and long texts can be translated. Documentation... is also language-specific. Always write documentation from the user's point of view. If you want to document the programming techniques you have used, use comments in the program code instead. Variants ... store predefined input fields on program selection screens.
(C) SAP AG
BC402
5
1.6 Structure of an ABAP program
Global declarations
Dialog module
Event block
Procedure
PROGRAM sapbc402_rund_test. TYPES ... DATA ... CLASS ... DEFINTION. TYPES ... DATA ... ENDCLASS. CLASS ... IMPLEMENTATION. ... ENDCLASS. MODULE s_100 OUTPUT. ... ENDMODULE. INITIALIZATION. ... START-OF-SELECTION. ... FORM calc USING ... CHANGING ... TYPES ... DATA ... ... ENDFORM.
SAP AG 1999
The ABAP programming language is event-driven, and so is suited to processing user dialogs. The source code of an ABAP program can be divided into two parts: Global declarations The statements that declare global data types, global objects, and selection screens, as well as local program classes and interfaces. Processing Blocks (program units that cannot be further divided or nested) You must write processing blocks as a single unit. There are two types of processing blocks: - Event blocks: An event block is introduced by an event keyword. It ends when the next processing block starts. - Dialog modules and procedures A modularization block is introduced and concluded using the relevant keywords. The collection of all processing blocks is known as the processing logic. When you generate the program, the system compiles the processing logic into the relevant runtime objects (load version of the program). The load version of the program is interpreted at runtime.
(C) SAP AG
BC402
6
1.7 Program Organization Create Program
program
Workbench Edit
SAPMZ402_RUND_TEST
Goto
Extras
Environment system Help
Object Navigator
Object name
With TOP include
Global declarations PBO modules PAI modules Subroutines
SAPMZ402_RUND_TEST
Dictionary structures fields PBO modules PAI modules Subroutines Screens GUI statuses GUI titles Transactions Includes MZ402_RUND_TESTTOP MZ402_RUND_TESTO01 MZ402_RUND_TESTI01 MZ402_RUND_TESTF01 MZ402_RUND_TESTE01
Events SAP AG 1999
In the simplest cases, all the source code is entered in one single program. To make your programs clearer, and to maintain and transport different parts of the source code separately, you should use include programs. When you create a program from the Object Navigator, the system suggests that you create a TOP include for the program. This option is particularly advisable if you are creating module pools.
When you create a processing block, the system always asks for the include program in which it should insert the relevant ABAP code. If the include program does not exist, the system creates it and inserts an INCLUDE statement for it in the main program. If you name your module pool according to the naming convention SAPMY|Z and then create a new processing block, the system proposes the name of the new include using the following convention: MY|Z. When you create further processing blocks, the system automatically proposes the appropriate include program. In this way, the system helps you to create programs whose structures are easy to understand. It is much easier for you to find your way around other developers' programs if they comply with these naming conventions.
(C) SAP AG
BC402
7
1.8 Overview - Concept of Inactive Sources Structure Structure of of an an ABAP ABAP program program Concept Concept of of inactive inactive sources sources Execution Execution of of an an ABAP ABAP program program
SAP AG 1999
(C) SAP AG
BC402
8
1.9 Developed Version R/3 Repository Developed version
Object Navigator Display program object Display program objects
ABAP program
Source code Screen Texts Interface
SAP AG 1999
In principle, development objects are stored in the R/3 Repository as they are developed. These are the only versions that can be displayed in the ABAP Workbench.
(C) SAP AG
BC402
9
1.10 Generated Version R/3 Repository Developed version
ABAP program: runtime objects
ABAP program
Source code Screen Texts Interface
Screen
Run program ABAP code ABAP code
ABAP program
Source code Screen
interprets
Texts Interface
ABAP runtime system
Generated version
SAP AG 1999
When a development object is generated, a runtime version of it is created (that is, compiled). This can then be executed (that is, interpreted). The system generates the object automatically. However, generation can also be explicitly triggered.
(C) SAP AG
BC402
10
1.11 Active and Inactive Version 1 Object Navigator
Change program object, R/3 Repository e.g. screen Developed version
Inactive version
Active version
Source code Change screen
Screen
Screen Texts Interface
2
Save ABAP program
Source code Screen Texts Interface Generated version SAP AG 1999
If you change a development object and then save it, the system creates an active version and an inactive version. If necessary, you can switch between displaying each of these two versions. However, you can only edit the inactive version. The syntax check is carried out on the developed version, not the generated version. This means that it can be performed on the inactive version. When running the source code for executable programs that are started from the Editor, the system goes back to the inactive version. A generated version is created temporarily. In all other cases, the system always accesses the active version when the program is generated. This allows you to continue developing, without changing the current system status. Development objects are only visible throughout the system after they have been activated. The introduction of inactive sources offers developers a local, separate view of the R/3 Repository and builds the foundations for a "local runtime system." You can test changes to development objects in such a system, without causing any problems in the environment.
(C) SAP AG
BC402
11
1.12 Activate R/3 Repository Developed version
Object Navigator
Modified program objects
Activate program 3
2
(New) active version
Source code Source code Screen
Screen Texts Interface 4
1 Activation involves: 1) Saving the contents of the tool area 2) A syntax check of all selected objects 3) Overwriting the newly activated program objects in the active version 4) Regenerating the modified program objects
ABAP program
Source code Screen Texts Interface Generated version
SAP AG 1999
The system lists all inactive objects in your worklist. The following steps occur when you activate an object (or several objects): The object is saved - that is; a new inactive version is created. The system performs a syntax check. It then overwrites the current active version. The previously inactive version is now the active version. There is no longer an inactive version. The system creates a new runtime version. The LOAD is updated.
(C) SAP AG
BC402
12
1.13 Overview - Execution of an ABAP Program Structure Structure of of an an ABAP ABAP program program Concept Concept of of inactive inactive sources sources Execution Execution of of an an ABAP ABAP program program
SAP AG 1999
(C) SAP AG
BC402
13
1.14 General ABAP Program Execution
ABAP Program
Processing block
Declarations
passive
passive ABAP runtime system
Processing block
Processing block
passive
passive
active
SAP AG 1999
The individual processing blocks are called in a predetermined sequence at runtime, regardless of the position in which they occur in the program. Once a processing block has been called, the statements within it are processed sequentially. Event block If the system program or a user triggers an event, for which the corresponding event block has been written in the processing logic, that event block is processed. The program flow is controlled either by the system or the user.
Modularization unit When the system encounters a modularization unit call within a processing block, it calls the corresponding processing block. In this case, the programmer controls the program flow. Assigning transaction codes To allow module pool to be executed, you must assign a transaction code to it. You can (but do not have to) assign a transaction code to an executable (type 1) program.
(C) SAP AG
BC402
14
1.15 Executing a Dialog Transaction
LOP
LOAD-OF-PROGRAM. ...
PBO
MODULE ... OUTPUT. ENDMODULE
PAI
MODULE ... INPUT. ENDMODULE
PBO
MODULE ... OUTPUT. ENDMODULE
PAI
MODULE ... INPUT. ENDMODULE
SAP AG 1999
Module programs are designed to provide a flexible layout for user dialogs, using screens. You must assign a dialog transaction to the module pool program, so that users can call it up directly. The following steps occur when you run a dialog transaction: First, the system triggers the LOAD-OF-PROGRAM event. Once this event block has been executed, the ABAP processor passes control to the screen processor. The screen processor processes the initial screen specified in the transaction definition. (The initial screen can be a selection screen (regardless of the program type). The PROCESS BEFORE OUTPUT event is triggered and control passes to the ABAP processor, which processes the first PBO module. The ABAP processor executes the processing block and returns control to the screen processor. Once all PBO modules have been processed, the contents of any ABAP fields with identically named corresponding fields on the screen are transported to the relevant screen fields. Then the screen is displayed (screen contents, active title, active status). Once the user has chosen a dialog function (such as ENTER), the contents of the screen fields are transported back to the corresponding identically-named fields in the ABAP program, and the processing blocks that belong to the PROCESS AFTER INPUT event are processed. The system then continues by processing the next screen. You can call additional selection screens using the CALL SELECTION-SCREEN statement. You can also use the statement LEAVE TO LIST-PROCESSING. This makes all of the list processing events available to you. (C) SAP AG
BC402
15
1.16 Executing an Executable Program
LOP
LOAD-OF-PROGRAM.
INIT
INITIALIZATION.
SOS
START-OF-SELECTION.
GET
GET ...
GETL
GET ... LATE.
EOS
END-OF-SELECTION.
SAP AG 1999
Executable programs have two main characteristics: first, the fact that events are carried out in a fixed sequence, and second, that you can create the standard selection screen and several lists very simply. You can start executable (type 1) programs without using a transaction code. You can also run them in the background. You can, but need not, assign a report transaction to an executable program. The following steps occur when you run an executable program (also known as a report transaction): First, the runtime system calls the LOAD-OF-PROGRAM event. Then it calls the INITIALIZATION event. It calls the standard selection screen, if it has been declared. It calls the START-OF-SELECTION event. (This is the default event block. If you omit this event keyword, any statement that is not assigned to another processing block is treated as though it belonged to this block). If you have attached a logical database to your program, the system triggers the GET and GET LATE events. The END-OF-SELECTION event is triggered. You can call additional selection screens using the CALL SELECTION-SCREEN statement. You can also include screen processing (as in module pools) by using the CALL SCREEN statement.
(C) SAP AG
BC402
16
1.17 Selection Screen Events
ATSSO
AT SELECTION-SCREEN OUTPUT.
ATSS
AT SELECTION-SCREEN.
SAP AG 1999
There are two events belonging to each selection screen: The system triggers the AT SELECTION-SCREEN OUTPUT event before it displays the selection screen. It triggers the AT SELECTION-SCREEN event after the user has triggered a dialog function (such as Enter).
(C) SAP AG
BC402
17
1.18 List Processing Events List buffer for basic list
TOP TextTextText EOP ALS TDLS
TextTextText EOP AUC
TOP-OF-PAGE. WRITE ... WRITE ... END-OF-PAGE. AT LINE-SELECTION. TOP-OF-PAGE DURING LINE-SELECTION. WRITE ... WRITE ... END-OF-PAGE. AT USER-COMMAND.
List buffer for detail list SAP AG 1999
If you fill the list buffer of the basic list (using the WRITE, SKIP, and ULINE statements), two further events are triggered: At the beginning of each new page, the TOP-OF-PAGE event is triggered, and the END-OF-PAGE event is triggered at the end of each page. Once the END-OF-SELECTION event block has been processed, interactive list processing starts. The system displays the formatted basic list. The user can now trigger further events. The function code PICK triggers the AT LINE-SELECTION event. (In standard list statuses, this function code is assigned to the key). This key has a fixed relationship with the user action of double clicking the left mouse button). If you fill the list buffer of the detail list (up to 20 levels) using the WRITE, SKIP, and ULINE statements, two further events are triggered: At the beginning of each new page, the TOP-OF-PAGE event is triggered, and the END-OF-PAGE event is triggered at the end of each page. Interactive list processing is started again. The system displays the formatted detail list, and so on. Any other function codes that have not been "trapped" by the system trigger the event AT USERCOMMAND.
(C) SAP AG
BC402
18
1.19 Non-Executable Programs
Function Builder
Class Builder
ABAP Editor
Function group, type F
Global interface, type J Global class, type K
External subroutine, type S
FUNCTION-POOL ...
CLASS-POOL ...
SUBROUTINE-POOL ...
TYPES: ... DATA: ....
TYPES: ... DATA: ....
TYPES: ... DATA: ....
FUNCTION ... ENDFUNCTION.
CLASS ... ENDCLASS.
FORM ... ENDFORM.
INTERFACE ... ENDINTERFACE. SAP AG 1999
The following types of programs cannot be executed directly. Instead, they are used as containers for modularization units that you call from other programs. When you call one of these modularization units, the whole of its container program is always loaded as well. When the modularization unit is first called, the entire program is loaded. Further information about this is provided further on in the course. Function group (type F) ...contains function modules, local data declarations for the program, and screens. For further information, refer to the Function Groups and Function Modules unit). Interface pool ... can contain a global interface and local program declarations. Class pool ... can contain a global class and local program declarations. Subroutine pool ... contains subroutines and, in some cases, local program declarations. Caution! Type S programs are obsolete and have been replaced by function groups. Include program cannot be directly executed: They can only be included as part of another program. They can contain any ABAP statements. These are then executed as if they were in the main program. This is why the relevant include programs are loaded together with the main programs.
(C) SAP AG
BC402
19
1.20 The ABAP Runtime Environment: Unit Summary
You are now able to: Name the components of an ABAP program Describe how an ABAP program is organized Take technical aspects of program execution into account when you write an ABAP program
SAP AG 1999
(C) SAP AG
BC402
20
1.21ABAP Runtime Environment Exercise Unit: ABAP Runtime Environment Topic:
Creating Repository Objects
At the conclusion of these exercises, you will be able to: • Create development classes • Create programs
You are a developer for an airline consortium. Your task is to develop evaluation programs for several airlines.
Program: Template:
ZBC402_##_EDITOR
None
Model solution: SAPBC402_RUNS_EDITOR ## stands for your (two-digit) group number.
1-2
Create a development class and a program. Use the development class to group together your Repository objects. In accordance with good development practice, assign your objects to a change request as follows: 1-2-1 Create a development class (suggested name: ZBC402_##). 1-2-2 Create an executable program without a TOP include (suggested name: ZBC402_##_EDITOR). 1-2-3 Get to know the Editor and Workbench settings. 1-2-4 Create a simple list using your program. Recommendation: Always work with the Object Navigator tool. This tool offers a variety of logical views of Repository objects in the form of hierarchical lists, which allows you to edit sub-objects of Repository objects simply. Use context menus, which offer you the Object Navigator to edit objects and sub-objects.
(C) SAP AG
BC402
21
(C) SAP AG
BC402
22
1.22ABAP Runtime Environment Solutions Unit: ABAP Runtime Environment Topic: Creating Repository Objects
2Development class Attribute
Value
Development class
ZBC402_##
Short text
BC402: group ## objects
Person responsible
BC402-##
Software component
HOME
Application component
CA
3ABAP program 3.2Attributes Attribute
Value
program
SAPBC402_RUNS_EDITOR
Title
Solution to Exercise 1 (ABAP Runtime Environment)
Type
Executable program
Status
Test program
Application
Basis(System)
Development class
BC402
Fixed point arithmetic
X
3.3Text Symbols Sym
Text
001
This is a simple list output.
3.4
(C) SAP AG
BC402
23
3.5Source code *&-----------------------------------------------------------------* *& Report
SAPBC402_RUNS_EDITOR
*
*&
*
*&-----------------------------------------------------------------* *& solution to exercise 1: ABAP runtime environment
*
*&
*
*&-----------------------------------------------------------------* REPORT
sapbc402_runs_editor.
WRITE: / text-001.
(C) SAP AG
BC402
24
4 Data Objects, Types, and Statements
Contents Data objects in programs Elementary data objects Structures
SAP AG 1999
(C) SAP AG
BC402
1
4.2 Data Objects, Types, and Statements: Unit Objectives
At the conclusion of this unit, you will be able to: Define local program types Define elementary data objects and structures Perform calculations Use automatic type conversion appropriately
SAP AG 1999
(C) SAP AG
BC402
2
4.3 Overview - Data Objects, Types, and Statements
Data ABAP program
Operations
ti nc Fu
Object
o
nm
ul e od
Data Method
Subroutine
Data
SAP AG 1999
(C) SAP AG
BC402
3
4.4 Overview - Introduction Introduction Introduction Elementary Elementary data data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
4
4.5 Definition of Data Objects
The type attributes of the data object must be fully specified
User-defined types
Predefined ABAP Types
How is the type structured? By field • Predefined ABAP type • Length
How is the data stored? How is it interpreted? d n
t x c
i p
DATA: varname TYPE type.
xstring
f
string
Global types in the ABAP Dictionary SAP AG 1999
In general, data objects are defined using the DATA statement, as follows: After the name of the data object, fully specified type is assigned to it using the TYPE addition. The type is linked to the data object statically. It cannot be changed at runtime. There are other syntax variants available (for historical reasons). Note however, that some of these historical variants are supported in ABAP Objects. For further information, refer to the keyword documentation for the DATA statement. All types are based on predefined ABAP types, which are discussed in greater detail on the Predefined ABAP Types slide. Some of these ABAP types are fully specified and can be used themselves to type data objects. Others need to be modified to include the length, and in some cases the number of decimal places. These are the simplest examples of user-defined types. You can create complex structured types of any level of complexity you want, based on elementary types. You can also define types directly in the ABAP Dictionary. You can then use these global types in all appropriate Repository objects in the system.
(C) SAP AG
BC402
5
4.6 Predefined ABAP Types Data type
Description
Static length in bytes
Numeric types
Fixed length
i f p
Attributes are split into:
Integer
4
• Rules for storage
Floating point number
8
• Value range
Packed number
1 .. 16
• Arithmetic used
Character types
n c d t
Sequence of digits
1 .. 65535
Sequence of characters 1 .. 65535 Date 8 Time
Character string operations (allowed for all types) + date calculations
6
+ time calculations
1 .. 65535
Operations on bits
Hexadecimal
Variable length
x
Hexidecimal code
String/hexadecimal Runtime system adjusts length automatically
string Sequence of characters xstring Hexidecimal code
SAP AG 1999
The following ABAP types are fully specified and can be used themselves to type data objects: d, t, i, f, string and xstring. A special feature of the string and xstring types is that their length is adjusted automatically at runtime. Thus, length is not a component of the type. The following ABAP types are not fully specified, so you must extend them to include additional information before you use them to define data objects: c, n and x: You must extend the type to include the length, which must be from 1 to 65535 characters. If you do not declare a length when you define a data object, the system assigns the default length of 1. p: You must extend the type to include the length, and number of decimal places if needed, which must be from 1 to 16 bytes. If you do not declare a length when you define this data object, the system assigns the default length of 8 bytes (that is, 15 digits) and 0 decimal places. The type also contains information on how the data is stored, what range of values is allowed, what operations can be performed on the data, and what sort of arithmetic is used (if the data object is suitable for use in calculations). We will deal with this topic in greater detail later in this unit.
(C) SAP AG
BC402
6
4.7 Visibility of Data Objects Global data objects: visible throughout the entire ABAP program ABAP program
Subroutine Legend Memory made available for data objects Local data objects: Only visible in one modularization unit
Temporary runtime objects
SAP AG 1999
The extent to which data objects are visible depends on the context. For data objects defined using the DATA statement, the following rules apply: If the DATA statement occurs between a FORM and ENDFORM statement, it defines a local data object in that subroutine. At all other points in the source code (with very few exceptions), the DATA statement defines a global data object, visible throughout the program. Local objects obscure global data objects of the same name. Data objects defined using the TABLES statement (that is, structures) are always global, even if this TABLES statement occurs between FORM and ENDFORM.
(C) SAP AG
BC402
7
4.8 Preview: Visibility Areas in Objects Reference variable allows access to the public components of the object ABAP program
Private attributes: only visible within the object
Object public section
private section
Public method Subroutine Private method:
Local data objects: only visible within the method
Local data objects: only visible within the method
SAP AG 1999
If you use objects (that is, instances of ABAP Objects classes) in your program, you have other options for specifying the visibility of your data objects: In object-oriented programming, data objects are known as attributes. The attributes are defined in the class (that is, the object type). Syntactically, the definition of the local program class begins with CLASS class_name DEFINITION and ends with ENDCLASS. If the DATA statement occurs between a CLASS and ENDCLASS statement, it defines an attribute of the class or object. There are two main types of visibility area: Private attributes are only visible within the object All the methods of the object can read and change the data. From outside the object, the attributes can only be accessed indirectly, if a method of the object has been created, that accesses the data. Public attributes are also visible outside the object Other visibility areas exist (protected attributes, class attributes). For more information, see the Introduction to ABAP Objects unit. If the DATA statement occurs between a METHOD and ENDMETHOD statement, it defines a local data object in that method. Local objects obscure global data objects of the same name.
(C) SAP AG
BC402
8
4.9 Lifetime of Data Objects Global data objects
Start of program Lifetime of Data Objects
Call subroutine Local data objects of the subroutine Create object Attributes Call method
Local data objects of the method
Time End of program SAP AG 1999
The lifetime of data objects is linked to their visibility. The lifetime is also important for determining where exactly in the source code the DATA statement is to be implemented: If the DATA statement occurs between a FORM and ENDFORM statement, it defines a local data object in that subroutine. The lifetime corresponds to the runtime of the subroutine. If it occurs between a METHOD and ENDMETHOD statement, it defines a local data object in that method. The lifetime corresponds to the runtime of the method. If the DATA statement is implemented between a CLASS and ENDCLASS statement, it defines an attribute of the class or object. The lifetime begins when the object is instantiated at runtime and ends when the last reference to the object ha been deleted. To find out more about the lifetime of objects, see the Introduction to ABAP Objects unit or the keyword documentation on the CLASS-DATA statement. At all other points in the source code (with very few exceptions), the DATA statement defines a global data object, visible throughout the program. The lifetime corresponds to the lifetime of the program.
(C) SAP AG
BC402
9
4.10 Overview - Definition of Data Objects Introduction Introduction Elementary Elementary data data objects objects Definition Definition Numeric Numeric data data objects objects Strings Strings Automatic Automatic type type conversion conversion Fixed-length data Fixed Fixed-length data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
10
4.11 Definition of Elementary Data Objects User-defined type: c, TYPES : my_type(3) my_type(3) TYPE c explicit type construction percentage_type percentage_type(3) (3) TYPE p DECIMALS 2. 2
DATA : my_var TYPE my_type, my_type percentage TYPE percentage_type. percentage_type
Definition of a data object with reference to a userdefined type
DATA: counter TYPE i i. DATA
Definition of a data object with reference to a fully specified predefined ABAP type
DATA: flag(1) c. DATA (1) TYPE c
Definition with an implicit type construction
DATA: my_var_help LIKE my_var. my_var DATA
Data object inherits type attributes from another data object
SAP AG 1999
You use the TYPES statement to define your own data types. When defining c, n, or x types, you specify the length by entering the number of characters or digits in parentheses after the name. When defining p types, you specify the length by entering the number of bytes required in parentheses after the name. You specify the number of decimal places using the DECIMALS addition. The connection between the value range and the length of the type will be discussed in greater detail later in this chapter. You define data objects using the DATA statement. You assign a type to this data object using the TYPE addition. This can either be a user-defined type or a completely specified predefined ABAP type. When defining a data object, you can also construct a type implicitly: If some information is not available for one of these variants, the system adds this information using type-specific default values: Default length for objects of type c, n, and x: 1 character Default length for objects of type p: 8 bytes; default value for the number of decimal places: 0. You cannot declare a length when defining STRING-type or XSTRING-type data objects. Instead the runtime system adjusts the length of the object as necessary. Thus, the following definition is complete: DATA vstring TYPE string.
(C) SAP AG
BC402
11
4.12 Runtime Behavior: Initial Value and Start Value Definitions: TYPES: c_type(3) TYPE c. DATA: gd_char1 TYPE c_type, gd_char2 TYPE c_type VALUE VALUE 'AB' 'LH', counter type i. gd_char1 Start of lifetime
Start value
gd_char2
counter
AB
0000
gd_char1 = gd_char2.
AB
AB
0000
ADD 1 TO counter.
AB
AB
0001
CLEAR CLEAR: gd_carrid1, gd_carrid2, counter.
0000
ABAP program
ABAP runtime system
Type-specific initial value
Time SAP AG 1999
There is an appropriate initial value assigned to every predefined ABAP type. To find out what these values are in each case, refer to the keyword documentation for the TYPES statement, variant 1, addition 1. An initial value is also assigned to every user-defined type. This value is determined by taking the initial value of the predefined ABAP type and the length (and number of decimal places) declared for the type. When the system enters the validity area, the data objects are instantiated and filled with the initial value. This rule applies: For all global data objects at the start of the program For all private and public attributes, when instantiating an object For all global data objects in a function group, when calling a function module belonging to that function group for the first time For all local data objects, when calling a subroutine, a method, or a function module If you assign a start value to the data object using the VALUE addition to the DATA statement, this start value overwrites the initial value. At runtime, you can restore the type-specific initial value to a variable using the CLEAR statement. You can query the status of this variable using the IS INITIAL comparison. For further information, refer to the keyword documentation for the CLEAR and IF statements.
(C) SAP AG
BC402
12
4.13 Runtime Behavior: Fields of Dynamic Length Definitions: DATA: gd_string TYPE string. gd_string Start of validity gd_string = 'ABCDEFGHIJKLMNOP'.
ABCDEFGHIJKLMNOP
CLEAR CLEAR: gd_string. gd_string = 'ABCD'.
ABCD
Runtime system adjusts length as appropriate ABAP program
ABAP runtime system Time SAP AG 1999
When entering the validity area, there is no need for the system to reserve memory for elementary data objects of variable length, that is for strings (STRING types) or byte sequences (XSTRING types). The necessary memory is only allocated once a value has been assigned to the variable. CLEAR string deletes the content and restores the initial status, that is a string or byte sequence whose length equals zero. The runtime system adjusts the length of the object as necessary at runtime. You can trace the runtime behavior of the string in debugging mode (in terms of length), by displaying the string in the field view and then double clicking the string name to obtain a detailed view. You can find out the length of the string at runtime using the STRLEN( string ) function.
(C) SAP AG
BC402
13
4.14 Overview - Numeric data objects Introduction Introduction Elementary Elementary data data objects objects Definition Definition Numeric Numeric data data objects objects Strings Strings Automatic Automatic type type conversion conversion Fixed-length data Fixed Fixed-length data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
14
4.15 Integers and Integer Arithmetic Length: 4 bytes Value rang [-2147483648; 2147483647]
DATA: max_speed TYPE i VALUE 1.
Integer arithmetic: all internal auxiliary fields are integer fields interim results are rounded. int1 = int2 DIV int3 + int4. int2 = int1
4
1
=
+ * DIV MOD **
3
4 DIV
=
Valid operations for integers:
int3 =
int4 = 3
2
+
2
+
2
=
3
Integer auxiliary variable
Addition Subtraction Multiplication Integer division Remainder from integer division Power
SAP AG 1999
When the system performs integer arithmetic, it always rounds to the nearest whole number. For example: DATA int TYPE i. int = 4 / 10. " result: 0 int = 5 / 10. " result: 1 Calculations performed using integer arithmetic are faster than calculations using fixed point or floating point arithmetic. You can assign a start value to an integer variable using the VALUE addition to the DATA statement. Generally, you enter a numeric literal after VALUE. If you enter a digit in the form of a text literal (enclosed in apostrophes), the runtime system has to convert it. For further information on calculations performed on integers, refer to the keyword documentation for the COMPUTE statement.
(C) SAP AG
BC402
15
4.16 Packed Numbers and Fixed Point Arithmetic DATA: percentage(3) (3) TYPE p DECIMALS 2 VALUE '12.34'.
Length in bytes: n bytes corresponds to 2n - 1 digits
Number of decimal places Fixed point arithmetic: like using paper and a pencil
+
1234,56 78,5 1313,06
Number 12,34 Internal 0 1 2 3 4 D representation 1 digit per half-byte
Sign: C for + D for -
Permitted length: 1 to 16 bytes (1 to 31 digits) Number of decimal places < number of digits (max. 15) For example: Length 3 bytes, 2 decimal places ⇒ Value range: [-999.99,+999.99]
SAP AG 1999
The length of packed numbers is given in bytes. The connection between the value range and the length is determined from the internal representation: Each decimal digit is represented by a half-byte. The last byte is reserved for the sign. The number of decimal places is defined using the DECIMALS addition. The maximum number of decimal places is either 15 or the length of the number minus 1 (that is, there must be at least one digit before the comma). You can give the object a start value by assigning a decimal number as a text literal (that is, by using the VALUE addition to the DATA statement). Use the period symbol (.) as a separator. Decimal point-aligned, fixed-point arithmetic is used for calculations. Packed numbers are thus well suited to business calculations, where the correct rounding for the specified number of decimal places is very important. The algorithm for this arithmetic is similar to using a pencil and paper. In fixed-point arithmetic, the system always uses packed numbers of the maximum length for interim results. In user dialogs, decimal numbers are formatted according to the settings in the user master record. You can switch off fixed-point arithmetic in the program attributes. If you do, the DECIMALS addition when defining a packed number only affects the output of the number. Internally, all numbers are interpreted as integers, regardless of the position of the decimal point. The fixed-point arithmetic option is always selected by default. You should always accept this value and use packed numbers for business calculations.
(C) SAP AG
BC402
16
4.17 Floating Point Arithmetic |
|
1,5 = 1 ⋅ 20 + 1 ⋅ 2 =1
+
−1
Only 53 bits available
1 2
| 0 0 | −3
| ...
| 0 0 | −6
−7
0,15 = 1 ⋅ 2 + 1 ⋅ 2 + 1⋅ 2 + 1 ⋅ 2 =
1 8
+
1 64
+
−10
+ 1⋅ 2
−11
+
≈
1 1 1 + + + 128 1024 2048
= 0,125 + = = =
0,140625 +
Only for approximations!
0,1484375 + 0,1494140625 +
=
0,1499023437
SAP AG 1999
In contrast to packed numbers, floating-point numbers are represented using sums of binary fractions. Floating point numbers are also normalized, and both the exponent and the mantissa are stored in binary form. This representation complies with the IEEE norm for double precision floating-point numbers. The floating-point operations of the relevant processors are used for calculations. Since algorithms are converted to binary, inaccuracies can occur. The extent and effect of these inaccuracies are difficult to estimate. This means that floating point numbers are not suitable for business calculations, which generally need to be calculated "to the last penny", and for which legally stipulated rounding rules must be followed. Example: Suppose you want to calculate 7.72% of 73050 and display the result accurate to two decimal places. The answer should be 5310.74 (73050 * 0.0727 = 5310.7735). However, the program returns the following: DATA: float TYPE f, pack TYPE p DECIMALS 2. float = 73050 * '0.0727'. " result: 5.3107349999999997E+03 pack = float. WRITE pack. " result: 5310.73 You should therefore only use floating-point numbers for approximations. When you compare numbers, always use intervals, and always round at the end of your calculations. The main advantage of floating-point numbers is the large range of values - that is, from 2,2250738585072014E-308 to 1,7976931348623157E+308 including both positive and negative numbers and zero. In addition, you must use floating-point numbers for special aggregation functions of the SELECT statement.
(C) SAP AG
BC402
17
4.18 Summary: Recommendations for Using Numeric Data Types
If you need this:
Integers only
Decimal numbers for business calculations
Decimal numbers for rough calculations performed on very small or very large numbers
Use this predefined ABAP type: Type i, since calculations using integer arithmetic are fastest
Type p
Type f
SAP AG 1999
(C) SAP AG
BC402
18
4.19 Calculations: Syntax
[COMPUTE] result = arithmetic_expression. * expressions: ... op ( expr1 op expr2 ) op ... * functions: ... FUNC( exp ) ... * possible operators op: ... expr1 + expr2 ... ... expr1 - expr2 ... ... expr1 * expr2 ... ... expr1 / expr2 ... ... expr1 ** expr2 ... ... expr1 DIV expr2 ... ... expr1 MOD expr2 ...
"ADD "SUBSTRACT "MULTIPLY "DIVIDE "power operator "integer division "remainder
SAP AG 1999
In ABAP, you can program arithmetic expressions nested to any depth. You must remember that parentheses and operators are keywords, and must therefore be preceded and followed by at least one space. The ABAP runtime environment contains a range of functions for different data types. The opening parenthesis belongs to the functions name itself (and is therefore not separated from it by a space). The remaining elements of each expression must be separated by spaces. The expressions are processed in normal algebraic sequence - parenthetical expressions, followed by functions, powers, multiplication and division, and finally, addition and subtraction. The DIV (integer division) and MOD (remainder of a division) operators always return whole numbers. There are four general categories of runtime error that can occur in calculations: A field that should have been converted could not be interpreted as a number. A number range is too small for a conversion, value assignment, or to store intermediate results. You tried to divide by zero. You passed an invalid argument to a built-in function (For example: ... log( -3 ) ... ). For further information, refer to the ABAP syntax documentation for the COMPUTE statement.
(C) SAP AG
BC402
19
4.20 Arithmetic on Mixed Expressions I
r
a
=
/
b
c
+
Interim result: • What type? • Which arithmetic was used?
Conversion in mixed expressions: Types
Values Interim result
r
a
b
c
a
b
c
r
i
i
i
i
i
1
201
200
0
1
p decimals 2
i
i
p
p
p decimals 3
i
i
p
1.005
201
200
0
1.01
p
1.005
201
200
0
p decimals 2
i
i
f
1.005
f
1.004999999E+00
201
200
0
p decimals 3
i
i
1.00
f
f
1.004999999E+00
201
200
0
p
i
i
1.005
i
p
1.005
201
201
0
1.005
SAP AG 1999
An arithmetic expression may contain any data types that are convertible into each other and into the type of the result field. The system converts all of the fields into one of the three numeric data types (i, p, or f), depending on the data types of the operands. The ABAP runtime system uses different arithmetic processors for each of the three data types. The system then performs the calculation and converts it into the data type of the result field. This may mean that the same arithmetic expression leads to different results when performed on different combinations of data types.
(C) SAP AG
BC402
20
4.21 Arithmetic on Mixed Expressions II Types
Values
Arithmetic
r i
a i
b i
c i
a
b
c
r
201
200
0
1
Integer
p decimals 2 p decimals 3
i
i
201
200
0
1.01
Fixed point
i
i
p p
201
200
0
1.005
Fixed point
p decimals 2
i
i
201
200
0
1.00
Floating point
p decimals 3
i
i
f f
201
200
0
1.005
Floating point
c p
i
i
i
201
201
0
1.005
Fixed point
The data types of all the components combined determined the arithmetic of the whole expression Rules: • Fixed Fixed point point arithmetic arithmetic is the default • Integer arithmetic Integer arithmetic is only used if all the components are integers • Floating Floating point point arithmetic arithmetic is used whenever at least one component is a floating point number SAP AG 1999
An arithmetic expression can also contain character-type data objects, provided it contains at least one number data type object. The values contained in these character-type objects are converted to numeric type objects. Bear in mind that conversions affect performance. Wherever possible, choose a data type that does not require runtime conversion. Note: The results of the following functions have the data type f: Trigonometry functions: COS, ACOS, SIN, ASIN, TAN, ATAN Hyperbolic functions: TANH, SINH, COSH Exponential functions (base e): EXP Natural logarithms (base e): LOG Logarithms to base 10: LOG10 Square root: SQRT When the arithmetic expression contains numeric literals, the arithmetic used depends on the size of the number. If the number lies within the value range for data of type i, the literal is interpreted as an integer. If the value of the literal is greater than 2147483647, it is interpreted as a packed number. DATA int TYPE i. int = 1000000000 / 300000000 * 3. " result: 9 int = 10000000000 / 3000000000 * 3. " result: 10
(C) SAP AG
BC402
21
4.22 Overview - Strings Introduction Introduction Elementary Elementary data data objects objects Definition Definition Numeric Numeric data data objects objects Strings Strings Automatic Automatic type type conversion conversion Fixed-length data Fixed Fixed-length data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
22
4.23 Predefined ABAP Types for Strings
Description
Length
Value range
Type t
Type d
Time
Date
Sequence of digits
FixedFixed-length char. string
6 digits HHMMSS
8 digits YYYYMMDD
1 .. 65535 characters
1 .. 65535 characters
By clock
By Gregorian calender
Digits
Operations
Calculations
Formatting options
Type n
Type c
Type string VariableVariablelength char. string variable
Depends on codepage
String operations Time arithmetic HH:MM:SS
Date arithmetic Based on values in user master record
SAP AG 1999
The value range of each string depends on the code page - a table containing all the supported characters. Internally, each character is represented by a code number. When the system outputs the character, it uses the code page to convert this number. To find the code page valid in a given system, choose Tools -> CCMS -> Spool -> Spool administration -> Full administration -> Character sets. The initial of each character in a fixed-length string is a space character. Numeric strings are represented internally as character strings. Note, however, that only digits are permissible as characters - when character strings are assigned to numeric strings, the system ignores letters and copies only the digits (right-aligned). Missing characters are filled with zeros. The initial value of each character in a numeric string is a zero. Only sequences of digits are valid for values of type d. These digits form a meaningful date, which complies with the Gregorian calendar. The first four digits represent the year, the next two the month and the last two the day. For performance reasons however, the object is only checked if it is an input field on a screen or selection screen. The initial value of a date is '00000000'. The formatting options are determined by the user settings. For values of type t, a sequence of digits is only valid if it can be interpreted as a time on the 24-hour clock. The rules for interpreting the value are similar to those used for dates. The initial value of a time is '000000'.
(C) SAP AG
BC402
23
4.24 Overview: Processing Strings Meaning; Notes Position: sy-fdpos
Search If successful: sy-fdpos = Position of character string found
SEARCH
ABAP
REPLACE
ABAP
BBAP
Replace first occurrence
TRANSLATE
ABAP
Ab Ap
Replace + all occurrences
SHIFT
ABAP
AB
P
Move
A AB
A
P
Remove spaces
CONDENSE OVERLAY CONCATENATE SPLIT
P P
AA AA A B +A P ABAP
ABAP ABAP AB AP
Overlay: Spaces are overwritten by characters from the second string Concatenate several strings Split a string
SAP AG 1999
You can use the following statements to process strings in ABAP: SEARCH To search in a string. Note that there are special comparison operators for strings, which you can use in logical expressions to search more flexibly for character sequences in a string. For more information, see the keyword documentation for IF. REPLACE To replace the first occurrence of a string TRANSLATE To replace all specified characters SHIFT To shift one character at a time CONDENSE To remove spaces OVERLAY To overlay two strings CONCATENATE To chain two or more strings together SPLIT To split a string In all string operations, the operands are treated like type C fields, regardless of their actual field type. They are not converted. All of the statements, apart from TRANSLATE and CONDENSE, set the system field SY-SUBRC. SEARCH also fills the system field SY-FDPOS with the offset of the beginning of the string found. All of the statements apart from SEARCH are case-sensitive. To find out the occupied length of a string, use the standard function STRLEN().
(C) SAP AG
BC402
24
4.25 Date Fields Representation in date format (8 characters) YYYYMMDD
Conversion
Representation as integer: Number of days since the 01.01.0001
Gregorian calendar Used for string operations and output
Output: (10 characters) DD.MM.YYYY MM/DD/YYYY DD.MM.YYYY MM/DD/YYYY
Used for date calculations: adding and subtracting days
MM-DD-YYYY MM-DD-YYYY
DATA: date1 TYPE d d, date2 TYPE syst-datum syst-datum. START-OF-SELECTION. date1 = date2 = sy-datum. WRITE: date1 DD/MM/YYYY, date2.
The user specifies the output format (in the user master record).
"or other formatting options ... "formatting options not necessary
SAP AG 1999
You can add or subtract a number of days by including the date field in an arithmetic expression. PARAMETERS: date1 TYPE d DEFAULT sy-datum, number_of_days type i. date1 = date1 + number_of_days. Internally, the date field is converted to an integer (corresponding to the number of days since the 01.01.0001) using the Gregorian calendar. The system then adds number_of_days and converts the result back to a date using the Gregorian calendar. If a date field is assigned to a numeric field, the runtime system calculates the number of days since 01.01.0001. Conversely, if a numeric value is assigned to a date field, the numeric value is interpreted as the number of days since 01.01.0001 and then converted to a date using the Gregorian calendar. Note that you must enter the date as a text literal, as your start value for a date field (in the VALUE addition of the DATA statement). This is because number literals are of the type integer (that is, the number of days since 01.01.0001). The procedure is similar for performing operations on time fields except that, in this case, the integer represents the number of seconds since 0:00:00.
(C) SAP AG
BC402
25
4.26 Overview - Automatic type conversion Introduction Introduction Elementary Elementary data data objects objects Definition Definition Numeric Numeric data data objects objects Strings Strings Automatic Automatic type type conversion conversion Fixed-length data Fixed Fixed-length data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
26
4.27 Assigning Values
MOVE a TO b. b = a.
When you assign values, both fields should have the same type if possible (identical techical type properties).
Assigning a formatted value to a stringstring-type data object DATA: a TYPE elementary_type, b(c_long_enough) TYPE c. WRITE a TO b [ additions ]. ]
[ additions ] You can use the same additions as in the WRITE statement.
Type of a d t p
Format without additions According to settings in user master record HH:MM:SS According to settings in user master record
SAP AG 1999
You can copy the value in one field to a compatibly-typed data object in two different ways: MOVE source TO target. target = source. You can copy the (formatted) value of the data object source to a target field target of type c. WRITE source TO target. Note that the target field must be long enough to include separators Example: source is a date field containing the value '20001112' and the format is set to MM/DD/YYYY in the user settings. target is of type c and has a length of 10. After the (formatted) value has been assigned to target, its content is: '11/12/2000'. The rules governing the output of a field in a list using the WRITE ... statement are the same as those governing the assignment of a value using WRITE ... TO. To find out which additions you can use, refer to the keyword documentation for the WRITE statement.
(C) SAP AG
BC402
27
4.28 Automatic Type Conversion when Assigning Values Value assignment with automatic type conversion, where fields are are of different types MOVE a TO b b. b = a a. 00123
If a and b have different types: conversion follows the appropriate conversion rule
a Type
123
b
Internal representation
Type
Internal representation
p(3)
0 0 1 2 3C
i
p(3)
0 0 1 2 3C
c(6)
20 20 31 32 33 20
c(6)
3 0 3 0 3 1 3 2 3 3 2D
n(6)
30 30 30 31 32 33
7B 0 0 0 0 0 0
SAP AG 1999
Data objects of different types are generally represented differently internally. Consequently, the value in the source object must be converted to the type of the target object before it is assigned. There are conversion rules for most data types. If so, the value is converted automatically before it is assigned. Otherwise, a runtime error occurs. For further information, refer to the ABAP syntax documentation for the MOVE statement. Values in logical expressions must also be converted whenever the components involved have different types. For detailed information on the rules governing logical expressions, refer to the keyword documentation for the IF statement. Automatic type conversion is very user-friendly and adds to the program's robustness. Bear in mind however, that every conversion increases runtime. Avoid unnecessary conversions by ensuring that fields with the same meaning are given the same type.
(C) SAP AG
BC402
28
4.29 Overview - Fixed-Length Data Objects Introduction Introduction Elementary Elementary data data objects objects Definition Definition Numeric Numeric data data objects objects Strings Strings Automatic Automatic type type conversion conversion Fixed-length data Fixed Fixed-length data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
29
4.30 Literals
statement literal literal ...
Numeric literals: Type i or p Positive integers: 123 Negative integers: -123
literal
Text literals: Type c Strings: 'abcde' Decimal numbers: '123.45' Floating point numbers: '123.45E01'
SAP AG 1999
You use literals to pass values to ABAP statements directly. There are two sorts of literals: Numeric literals These can contain up to 31 digits plus a sign and have the type i or p. Remember the value ranges! Example: DATA: result1 TYPE i, result2 LIKE result1. result1 = -1000000000 / 300 * 3. "result1: 999.999result2 = -10000000000 / 300 * 3. "result2: 10.000.000 Text literals These are enclosed in apostrophes and can contain up to 255 characters. If a text literal contains a quotation mark, you must double it in order for it to be interpreted as part of the literal (and not as the closing quotation mark). Integers (with a preceding minus sign where required) can be represented as numeric literals. All other values (decimal and floating-point numbers, strings, and so on), must be represented as text literals. The system converts types automatically where necessary.
(C) SAP AG
BC402
30
4.31 Constants User-defined types:
Predefined ABAP types t
d n
CONSTANTS CONSTANTS const_name TYPE type VALUE literal literal.
x c
i p
xstring
f
string
Data element Structure field
SAP AG 1999
The value of a constant cannot be changed at runtime You define constants using the CONSTANTS statement. You must use the VALUE addition in the CONSTANTS statement. It is here that you specify the value of the constant. If you want to define a constant with an appropriately typed initial value, use a statement like the following: CONSTANTS const_name TYPE type VALUE IS INITIAL. Recommendation: Avoid literals as much as possible in your programs. If you use constants instead, your programs will be easier to maintain.
(C) SAP AG
BC402
31
4.32 Text Symbols WRITE 'default_text'(tsk). WRITE text-tsk.
* language independent: *********************** WRITE 'Hello World!'. * depends on chosen language: ***************************** WRITE 'Hello 'Hello World!'(ts1) World!'(ts1). * or WRITE texttext-ts2. text-ts2
Text symbols ts1
ts2
DE EN ES : DE :
Hallo Welt! Hello world! ¡Hola mundo! Wie geht's?
SAP AG 1999
Text symbols are a special form of text literals. You can define a set of text symbols for any program using Text element maintenance. These can be used for output in various ways. The advantage of text symbols over normal text literals is that they can be translated. In addition, texts defined in this way are stored separately from the source code of the program. Text symbols are often used to create lists that are not language-specific. You should also use them to assign texts dynamically to screen elements (short texts for pushbuttons). (Static text elements for screen elements can be translated separately). You can display text symbols in two different ways, using the WRITE statement: WRITE text-. (where can be any three-character ID). WRITE 'defaulttext'(ts2). (where can be any three-character ID). In this case, is displayed if there is a text for it in the current logon language. If there is not, the default text is displayed.
(C) SAP AG
BC402
32
4.33 Overview - Structures Introduction Introduction Elementary Elementary data data objects objects Structures Structures
SAP AG 1999
(C) SAP AG
BC402
33
4.34 Definition of Structures Definition of a Structure Type
TYPES: TYPES: BEGIN OF s_name_type s_name_type, prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type.
Definition of a structure with an implicit type construction
DATA: DATA: BEGIN OF s_name, s_name prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name s_name.
Definition of a structure with reference to a user-defined type
DATA: DATA: s_name TYPE s_name_type s_name_type . Alternatives
START-OF-SELECTION. s_name-prename = 'Smith'. s_names_name-surname = 'John'. s_name SAP AG 1999
You can define structures in two ways: First, define a structure type explicitly using the TYPES statement. To do this, enter the name of the structure after BEGIN OF and then list the definitions of all the components. End the definition of the structure type using END OF. You then define the structured data object with the DATA statement, using your own user-defined structure type. Define the data object directly using the DATA statement. The syntax is similar to the definition of a structure type. If you use this option, the corresponding structure type is defined implicitly at the same time. You address components of structures using: structure_name-comp_name. For this reason, you should not use hyphens in variable names.
(C) SAP AG
BC402
34
4.35 Definition of Nested Structures Structured type
TYPES: BEGIN OF s_name_type, s_name_type prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type.
s_name_type forename surname title
DATA: BEGIN OF s_address_nested, name TYPE s_name_type, s_name_type phone_n(15) TYPE n, email(25) TYPE c, END OF s_address_nested.
Nested structure s_address_nested name forename surname title phone_number email
s_address_nested-name-surname = 'Smith'. s_address_nested-telefon = '123456789'
Used to create logical subgroups of data
SAP AG 1999
You can define nested structures by assigning a structure type to a component within a structure type. You can address this sub-structure as a whole using the component name: structure_name-substructure_name. You can also address individual components in the sub-structure: structure_name-substructure_name-comp_name. Structures can be nested to any depth. You can also integrate components of a dynamic type in a structure. This can either be an elementary data object of variable length (string or xstring) or an internal table. These structures are known as deep structures. There are constraints on how such deep structures can be used. For instance, a deep structure cannot be used as a whole in the INTO clause of a SELECT statement. (Instead, each component must be listed separately). Offset operations do not make sense in this context. For more information, refer to SAP Note 176337.
(C) SAP AG
BC402
35
4.36 Using Named Includes Structured type
TYPES: BEGIN OF s_name_type, s_name_type prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type.
s_name_type forename surname title
DATA BEGIN OF s_address. INCLUDE STRUCTURE s_name_type AS name. DATA: telefon(15) TYPE n, email(25) TYPE c, END OF s_address.
Structure with named include s_address_nested forename name surname title phone_number email
s_address-name-surname = 'Smith'. Used: * or: when you want to create a logical s_address-surname = 'Smith'.
subgroup, but where nested structures are technically not possible
SAP AG 1999
In some cases, you cannot use nested structures, for example: ... Because you can only define database tables with flat line types ... In situations where user dialogs with a tabular representation can only contain simple structures ( such as in the SAP List Viewer or Table Control) In situations like these, you may still want to group parts of the structure and address it as a whole. You do this using named includes. You can include a substructure in another structure, and give this substructure a name: DATA: BEGIN OF structure_name, ... . INCLUDE STRUCTURE substructure_type AS name. DATA: ... , END OF structure_name. You can address this sub-structure as a whole using structure_name-name. You can address the fields in the substructure using structure_name-name-comp_name or directly, using structure_name-comp_name. Technically, however, this structure is still "flat", not complex. If naming conflicts occur - for example, if you want to include the same substructure twice - you can append another name to the component names using RENAMING. For further information, refer to the keyword documentation for the INCLUDE STRUCTURE statement.
(C) SAP AG
BC402
36
4.37 Value Assignments Using Compatibly-Typed Structures Structured type
TYPES: BEGIN OF s_name_type, s_name_type prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type.
s_name_type forename surname title Nested structure s_address_nested name forename surname title phone_number email
DATA: BEGIN OF s_address_nested, name TYPE s_name_type, s_name_type telefon(15) TYPE n, email(25) TYPE c, END OF s_address_nested.
Structure
wa_name forename surname title
DATA wa_name TYPE s_name_type s_name_type. MOVE s_address_nested-name TO wa_name.
Structures assigned to each other should have the same type where possible.
SAP AG 1999
If you want to assign the contents of structures to other structures, they should be of the same type wherever possible, so that the system does not have to convert values automatically before assigning them. The same applies to substructures. If the components of two structures are type compatible, but their component names are different, these two structures are still type-compatible as a whole. The contents of flat structures (where all the components are of fixed-length) can also be assigned to incompatible structures. However, errors may occur. The differences are dealt with in the slides Assignments for String Structures and The Dangers of Assigning Incompatible Structures. However, the contents of a deep structure can only be assigned to a compatibly typed structure.
(C) SAP AG
BC402
37
4.38 Value Assignments in String Structures
If all the fields have the type String, you can also assign incompatible structures to each other.
Example: date fields
PARAMETERS p_date LIKE sy-datum DEFAULT sy-datum. DATA: BEGIN OF s_date, year(4) TYPE n, month(2) TYPE n, day(2) TYPE n, END OF s_date. MOVE p_date TO s_date. s_date-day = '01'. MOVE s_date TO p_date. SAP AG 1999
If all the components of a structure are of a string type, of fixed length, you can assign components with different properties to them. Each character is then copied byte-by-byte without being converted. This approach is used, for example, to extract the day or month from a date field. That is, a structure is created, such that the first four characters of a variable specify the year, the next two specify the month, and the last two the day. If a date is assigned to this structure using the MOVE statement, the characters are then copied left aligned. You can then determine the year, month, and day directly using the variables, without having to use offsets. For compatibility, assignments between incompatible structures are also allowed, if they contain numeric or hexadecimal components. The structure is then technically considered to be a string (that is, casting of the structure occurs). The contents are not converted. Between the structures, the same conversion rules apply as for strings: the bytes are copied, left aligned. If the target structure is longer than the source structure, the target structure is filled with spaces, regardless of the component type of the target structure. In conclusion, avoid assigning incompatible structures wherever possible, except where both structures consist entirely of fixed-length string-type fields.
(C) SAP AG
BC402
38
4.39 Dangers of Assigning Values Between Incompatible Structures Field does not have a string type
DATA: BEGIN OF rec1 rec1, text1(3) TYPE text2(4) TYPE pack(8) TYPE text3(10) TYPE END OF rec1, BEGIN OF rec2, rec2 text1(5) TYPE pack(8) TYPE text3(1) TYPE END OF rec2. rec2. MOVE rec1 TO rec2 rec1 text1 text2
pack
c VALUE c VALUE p DECIMALS 2 VALUE c VALUE
'AAA', 'BBCC', '2.26', 'DD',
c VALUE 'YYYYY', p DECIMALS 2 VALUE '72.34', c VALUE 'Z',
text3
AAA BBCC 0000000000002.26 DD _ _ _ _ _ _ _ _
rec2 text1 YYYYY
pack
text3
rec2 text1
0000000000072.34 Z
pack
AAABB C ? ? ?
text3 ?
SAP AG 1999
The ABAP runtime environment has rules for assigning: Flat structures to non-compatible structures Elementary fields to flat structures Flat structures to elementary fields In each of these cases, the system fills the target structure byte-by-byte from the left. If the target structure is longer than the source structure, the latter is filled with spaces. If the source structure contains numeric fields, values that cannot be interpreted may result in the target structure, unless the number of string characters in front of the numeric field is identical. Moreover, target structures containing integer components may cause problems: if the source structure contains an integer field (that is, a field four bytes long), but the number of bytes in front of the integer field is not divisible by four, these bytes will be filled with zeros until the integer address is divisible by four. To avoid this, copy the values component-by-component in these situations. The conversion rules for data objects then apply. You should only use offset addressing on structures if all of the fields in the structure have a string type and all have a fixed length.
(C) SAP AG
BC402
39
4.40 Assigning Values to Identically-Named Structure Components TYPES: name_type(25) TYPE c, title_type(5) TYPE c, email_type(35) TYPE c. DATA: BEGIN OF s_name, prename TYPE name_type, surname TYPE name_type, title TYPE title_type, END OF s_name. DATA: BEGIN OF s_address, prename TYPE name_type, surname TYPE name_type, title TYPE title_type, email TYPE email_type, END OF s_address. ...
MOVE: s_name-prename TO s_address-prename, s_name-surname TO s_address-surname, s_name-title TO s_address-title.
interpreted internally as an assignment using MOVE between all identically-named fields
MOVE-CORRESPONDING s_name TO s_address. SAP AG 1999
You can copy the contents of a source structure to a target structure component by component, using a MOVE-CORRESPONDING statement. The system then copies each source field to the target field with the same name. The conversion rules for elementary data objects then apply. Note that the system does not check that identically named components have the same type. This can be useful, but there are dangers involved.
(C) SAP AG
BC402
40
4.41 Data Objects, Types, and Statements: Unit Summary
You are now able to: Define local program types Define elementary data objects and structures Perform calculations Use automatic type conversion appropriately
SAP AG 1999
(C) SAP AG
BC402
41
4.42 Optional Exercise Unit: Data Objects, Types, and Statements Topic: Numeric Data Types
At the conclusion of these exercises, you will be able to: • Create data objects with numeric types • Perform calculations with numeric data types
Create three programs to demonstrate the effects of the following operations on the three numeric data types (one data type for each program): addition (+), subtraction (-), division (/), multiplication (*), integer division (DIV), modulus (remainder of integer division) (MOD), and powers (**). Programs:
ZBC402_##_DOS_EX1, ZBC402_##_DOS_EX2, ZBC402_##_DOS_EX3
Template:
None
Model solutions:
SAPBC402_DOSS_EXERCISE_1A, SAPBC402_DOSS_EXERCISE_1B, SAPBC402_DOSS_EXERCISE_1C
where ## is your group number 1-1
Create a program with the name ZBC402_##_DOS_EX1. This program will test the effect of the above arithmetic operations for integer variables. Your program should have a selection screen so that the user can enter two values. The system should then perform the calculations on both values and display the results in a list. Create a separate line in the list for each calculation. In each case, display the two values, the operator used, and the result. When creating your list, use the following example as a guide:
(C) SAP AG
BC402
42
Graphic 1: Displaying a list
Calculating integer numbers Operand 1 =
2
Operand 2 =
1
2
+
1 =
3
2
-
1 =
1
2
/
1 =
2
2
*
1 =
2
2 div
1 =
2
2 mod
1 =
0
2 **
1 =
1
Follow the detailed instructions below: 1-1-1 Create a program in the Object Navigator. Name
ZBC402_##_DOS_EX1
Type
Executable program
Application
Basis (System)
Development class
ZBC402_##
1-1-2 Declare two parameters and a results field (as a normal variable) for the two operands. Give each data object the type i (we suggest the following names for the data objects: p_value1, p_value2, result). 1-1-3 Perform the calculations in the START-OF-SELECTION event block. After the calculation has been performed, display the result in the list. 1-2
Create a program with the name ZBC402_##_DOS_EX2. This program will test the effect of the above arithmetic operations for packed numbers. Again, follow the detailed instructions below: 1-2-1 Copy your program ZBC402_##_DOS_EX1(or use the model solution from Exercise 1-1, SAPBC402_DOSS_EXERCISE_1A) and give it the name ZBC402_##_DOS_EX2. 1-2-2 Change your program so that it performs the calculations on data objects of type p. Test your program. 1-2-3 Use packed numbers with decimal places. Test your program again. What do you observe? 1-2-4 Remove the Fixed-point arithmetic attribute in the program attributes. Test your program. What do you observe? 1-2-5 Now check the Fixed-point arithmetic attribute back on in the program attributes. Observe what happens when you change the data type of one of the data objects involved.
(C) SAP AG
BC402
43
1-3
Create a program with the name ZBC402_##_DOS_EX2. This program will test the effect of the above arithmetic operations for floating point numbers. Again, follow the detailed instructions below: 1.3.1
Copy your program ZBC402_##_DOS_EX2(or use the model solution from Exercise 1-2, SAPBC402_DOSS_EXERCISE_1B) and give it the name ZBC402_##_DOS_EX3.
1.3.2
Change your program so that it performs the calculations using floating-point arithmetic.
1.3.3
What do you observe concerning the two parameters?
OPTIONAL: 1-4
Use color to highlight the output length of the data objects in the list, using the FORMAT COLOR ... statement. Note that you can also use the COLOR addition when displaying individual fields with the WRITE statement. For more details, refer to the keyword documentation for the WRITE statement (in the Output Formats for Fields section).
(C) SAP AG
BC402
44
Exercise 2 Unit: Data Objects, Types, and Statements Topic:
Defining Data Types, Data Objects, Basic Statements, and Processing Strings
At the conclusion of these exercises, you will be able to: • Define local program structure types • Define elementary and complex data objects • Split strings • Use conversion rules • Display the contents of data objects in lists In the next few exercises (including this one), you will work through the following scenario step by step: Several data records will be passed to your program, in the form of a long string. Your task is to extract the data from the string and process it further in the correct data format. To simplify this scenario: •
Passing the data as a string should be as simple as possible. In these exercises, therefore, you will read the string using a function module that you call in your program. In practice, you could implement this function using data stored in a sequential file (by means of a data transfer from an internal system).
•
Further processing will be limited to displaying the data in a list. In practice, you would store the extracted data in the database connected to the R/3 System (that is, you would update the SAP System).
•
You will edit the entire scenario step by step, working through each part of the exercise according to the objectives of each unit.
In this first exercise, you should create a program that receives the string; splits it into its components; and displays it in a structured form. Program:
ZBC402_##_DATA_SET
Template:
SAPBC402_DTST_TEMPLATE
Model solution: SAPBC402_DTSS_DATA_SET (C) SAP AG
BC402
45
## stands for your (two-digit) group number. 2-1
Copy the program, SAPBC402_DTST_TEMPLATE, giving it the name ZBC402_##_DATA_SET.
2-2
Read the string containing the data you will be extracting into a data object in your program. Use the function module BC402_CREATE_SEP_STRING. Follow the instructions below: 2-2-1 Become familiar with the interface for the function module BC402_CREATE_SEP_STRING. This function module uses interface parameters to generate a string from the data of a database table. You can use the function module interface to affect: -
The number of table entries to be read to make up the string (im_number).
-
The name of the table from which the system is to review the data (im_table_name).
-
The separator for each individual field in the data record (im_separator).
-
You can also specify whether the string should allow duplicates or whether all entries should be unique (im_unique). (1) You should not change any of the function module IMPORT parameters in the first two exercises. Instead, use the default value for each IMPORT parameter. (2) The function module uses the separator (#) to separate the fields of a data record. Each data record itself is then separated by a double separator.
2-2-2 Define a data object in which the string from the function module will be stored. (We suggest the name datastring, data type: string). 2-2-3 Call the function module BC402_CREATE_SEP_STRING in the STARTOF-SELECTION processing block. Use the default value for each IMPORT parameter. If the function module raises an exception, your program should return the termination message 038 from message class BC402. 2-3
As a first step, split the string and place the various pieces into your (field) components. Use a structure consisting of fields with the type character. Each field of the structure must be the same length as the corresponding component in the structure. 2-3-1 Familiarize yourself with the string structure. Use the Debugger to do this, or display your string in a list (WRITE ...), or both. Note: The string contains a data record with flight data. 2-3-2 Define: (a) a structure type (suggested name: st_flight_c) (b) a structure (suggested name wa_flight_c). Give each of them the type st_flight_c.
(C) SAP AG
BC402
46
The structure type should contain the following components: Component mandt carrid connid fldate price currency planetype seatsmax seatsocc paymentsum
Type c c n n c (!) c c n n c
Length 3 3 4 8 20 5 10 10 10 22
Why must the price component have type c? 2-3-3 When you analyzed the string you should have observed that the data record that is to be filtered out of the string is enclosed by separators. To split the string for the data record (without separators), you need an auxiliary variable, which you should define with the type string.(We suggest the name set_string). 2-3-4 First, get rid of the two separators from the string. Then copy the data record (from the first component to the double separator) to your auxiliary variable set_string. Then split the contents of this auxiliary variable, using the separator, and store it in the structure wa_flight_c. Use the chain operations SHIFT, SEARCH and SPLIT. Find out more about the exact syntax of these statements in the relevant keyword documentation. (Select the keyword and choose F1). Bear in mind that you can also access components in a string using offset/length addressing in the MOVE statement. Use the system field sy-fdpos to do this. 2-3-5 Display the fields of your structure, wa_sflight_c, in a list. 2-4
In Exercise 2-3-5, you should have observed that the program displayed some of the fields without formatting – for example, the PRICE field. You will change this in the next section of the exercise. To do this, convert the data you have extracted by copying them to data objects with suitable types. You should create the target fields as components of a structure. Ignore the client and payment sum in the following section of the exercise. Follow the detailed instructions below: The type of each target field determines its format when displayed. If you assign a source field to a target field of a different type the runtime system converts it.
2-4-1 Define: (a) a structure type (suggested name: st_flight) (C) SAP AG
BC402
47
(b) a structure (suggested name wa_flight). Give each of them the type st_flight. The structure type should contain the following components: Component carrid connid fldate price currency planetype seatsmax seatsocc
Type c n d p (!) c c i i
Length 3 4 predefined 9 5 10 predefined predefined
Decimal places
2
2-4-2 Copy the identically named components of the character-type structure wa_flight_c to the fields of the structure wa_flight. Note the conversion rule used by the system for the price component. 2-4-3 Display the contents of the structure wa_flight in a list. Use the appropriate formatting options for the WRITE statement for the fldate and price components. 2-4-4 If you did not use the template, you should now create a list header. Choose System →List →List Header). Use the list design from the model solution SAPBC402_DTSS_DATA_SET as a guide.
(C) SAP AG
BC402
48
4.43Optional Exercise Solutions Unit: Data Objects, Types, and Statements Topic: Numeric Data Types
5First ABAP program: REPORT
sapbc402_dtss_calc_i.
PARAMETERS: p_value1 TYPE i DEFAULT 5,
" input variable 1
p_value2 TYPE i DEFAULT 3.
" input variable 2
DATA: result
TYPE i.
" result variable
START-OF-SELECTION. WRITE: / text-001.
" p_date
col_positive
Always use col_background to display it_doubles. 1-3-3 Test your program.
OPTIONAL 1-4
Allow the user to choose whether to display the list as an ABAP print list (using WRITE) or using a standard display tool (similar to the optional section in Exercise 2 in the Internal Tables unit). The approach you take to completing this exercise depends on the program you used as your template: (a) If you used your own program, ZBC402_##_SORT_OPT, or the program SAPBC402_TABS_SORT_OPT as a template, adapt it as follows: Since the color values are now specified in it_flights and it_doubles, you only need to copy these internal tables to the STANDARD tables it_list1 and it_list2 and then pass them to the function module BC402_ALV_LIST_OUTPUT. (a) If you used your own program, ZBC402_##_SORT as a template, adapt it as follows: 1-4-1 Allow the user to choose how the system will display the list, using a checkbox on a selection screen. To do this, create a selection parameter class (suggested name: p_list, type: c, addition: AS CHECKBOX, selection text: “output as ALV list”), which you use to display the list as follows: IF p_list IS INITIAL. *
(C) SAP AG
"Conventional" list using WRITE BC402
26
ELSE. *
List displayed using function module (ALV)
ENDIF. 1-4-2 Implement the logical processing block indicated by the comment “List displayed using function module (ALV)” in section 1-4-1. Use the function module BC402_ALV_LIST_OUTPUT. This module expects two database tables and displays their contents using the ALV Grid Control (a tool used to display non-hierarchical lists). Detailed information on using the ALV Grid Control is not part of this course. For this reason, you use a function module that encapsulates all the necessary technical details, which you can treat as a “black box.” If you want to learn about the techniques used in the function module, and then apply them yourself, refer to the implementation of this function module in the appendix unit of this course. For more information on the ALV Grid Control, see: •
The online documentation
•
The example programs of the development class SLIS
•
The ABAP Workbench training course BC412: Dialog Programming with EnjoySAP Controls
You must pass two STANDARD tables of type BC402_T_FLIGHTS_COLOR to the function module BC402_ALV_LIST_OUTPUT. These tables contain the list data and color values for each line in the scenario we are dealing with in this course (that is, flight dates). The table kind STANDARD is the kind used by the ALV Grid Control, which the function module uses. To display it_flights and it_doubles using a module: (a) Define two internal tables (suggested names: it_list1 and it_list2), which have the type BC402_T_FLIGHTS_COLOR. (b) Copy the it_flights and it_doubles tables to it_list1 and it_list2 respectively. (c)Call the function module BC402_ALV_LIST_OUTPUT and pass the tables it_list1 and it_list2 to it. If your program triggers an exception when it executes the function module, it should display an error message. (We suggest “Error processing Control”). (d) Test your program .
(C) SAP AG
BC402
27
17.25Subroutines Solutions Unit: Subroutines Topic: Defining and Calling a Subroutine
18ABAP program REPORT
sapbc402_surs_form.
TYPE-POOLS: col. TYPES: BEGIN OF st_flight_c, mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c, END OF st_flight_c, tt_flights TYPE SORTED
TABLE OF bc402_s_flight_color
WITH UNIQUE KEY fldate carrid connid, *********************************************************** tt_gen
TYPE SORTED TABLE OF bc402_s_flight_color.
*********************************************************** DATA: datastring
TYPE string,
set_string
TYPE string,
wa_flight_c
TYPE st_flight_c,
wa_flight
TYPE bc402_s_flight_color,
it_flights
TYPE tt_flights,
it_doubles
TYPE SORTED TABLE OF bc402_s_flight_color
(C) SAP AG
BC402
28
WITH NON-UNIQUE KEY carrid connid fldate. CONSTANTS c_num TYPE i VALUE 30. PARAMETERS: p_date TYPE s_date. INITIALIZATION. p_date = sy-datum + 30. AT SELECTION-SCREEN. IF p_date < sy-datum. MESSAGE e030(bc402).
" P_ITAB
*----------------------------------------------------------------* FORM list_output USING p_itab TYPE tt_gen. DATA: wa_itab LIKE LINE OF p_itab. LOOP AT p_itab INTO wa_itab. FORMAT COLOR = wa_itab-color.
(C) SAP AG
BC402
31
WRITE: / wa_itab-carrid, wa_itab-connid, wa_itab-fldate DD/MM/YYYY, wa_itab-price CURRENCY wa_itab-currency, wa_itab-currency, wa_itab-planetype, wa_itab-seatsmax, wa_itab-seatsocc. ENDLOOP. *
--------------------------------------------------------
*
alternative solution using field symbols:
*
'copy free' loop
*
--------------------------------------------------------
*
FIELD-SYMBOLS:
*
LIKE LINE OF p_itab.
* *
LOOP AT p_itab ASSIGNING .
* *
FORMAT COLOR = -color.
* *
WRITE: /
*
-carrid,
*
-connid,
*
-fldate DD/MM/YYYY,
*
-price CURRENCY -currency,
*
-currency,
*
-planetype,
*
-seatsmax,
*
-seatsocc.
*
ENDLOOP.
ENDFORM.
(C) SAP AG
" list_output
BC402
32
Exercise 1: Optional Sections Unit: Subroutines Topic: Defining and Calling a Subroutine
19ABAP program REPORT
sapbc402_surs_form_opt.
TYPE-POOLS: col. TYPES: BEGIN OF st_flight_c, mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c, END OF st_flight_c, tt_flights TYPE SORTED
TABLE OF bc402_s_flight_color
WITH UNIQUE KEY fldate carrid connid, tt_gen
TYPE SORTED TABLE OF bc402_s_flight_color.
DATA: datastring
TYPE string,
set_string
TYPE string,
wa_flight_c
TYPE st_flight_c,
wa_flight
TYPE bc402_s_flight_color,
it_flights
TYPE tt_flights,
it_doubles
TYPE SORTED TABLE OF bc402_s_flight_color WITH NON-UNIQUE KEY carrid connid fldate,
it_list1 (C) SAP AG
TYPE bc402_t_flights_color, BC402
33
it_list2
TYPE bc402_t_flights_color.
CONSTANTS c_num TYPE i VALUE 30. PARAMETERS: p_date TYPE s_date, p_list TYPE c AS CHECKBOX. INITIALIZATION. p_date = sy-datum + 30. AT SELECTION-SCREEN. IF p_date < sy-datum. MESSAGE e030(bc402).
" 0. DESCRIBE TABLE wait_list LINES last_pos. IF ip_new_pos > last_pos. APPEND wa_cust TO wait_list. ELSE. INSERT wa_cust INTO wait_list INDEX ip_new_pos. ENDIF. ELSE. INSERT wa_cust INTO wait_list INDEX 1. ENDIF. ELSE. MESSAGE e203(bc402) RAISING not_in_list. ENDIF.
Change position in list
SAP AG 1999
To move an entry in the waiting list, we first delete the existing entry. Then, we enter a new one at position ip_new_pos. This is only possible if the new index is positive and not greater than the total number of lines in the list (last_pos). We determine the value of last_pos using the DESCRIBE TABLE ... LINES ... statement. If you specify an index that is too large, the entry is appended to the internal table (using APPEND).
(C) SAP AG
BC402
17
20.18 Organization of a Function Group Object list
Edit
Goto
Utilities
Environment System Help
Object Navigator
Workbench Edit
Goto
Extras
Environment System Help
Object Navigator
Object list Development class program Function group Class Local objects
Object name BC402_FMDD_WAITLIST
Display
BC402_FMDD_WAITLIST
Function modules Fields PBO modules Screens GUI titles Includes LBC402_FMDD_WAITLISTO01 LBC402_FMDD_WAITLISTTOP LBC402_FMDD_WAITLISTU01 LBC402_FMDD_WAITLISTU02 LBC402_FMDD_WAITLISTU03 LBC402_FMDD_WAITLISTU04 LBC402_FMDD_WAITLISTU05 LBC402_FMDD_WAITLISTU06 LBC402_FMDD_WAITLISTUXX
PBO modules Global declarations Function modules
Include modules in program
Add waiting customer Remove waiting customer Display waiting list Shift waiting list Return position in waiting list Change position in list
SAP AG 1999
As described in the ABAP Runtime Environment unit, the ABAP Workbench helps you to structure your source code when you work with function groups and function modules. Forward navigation ensures that you always enter the correct object. Include programs are named automatically, and the relevant call statements are inserted automatically in the correct positions. You only have to observe the naming convention for function groups: Y|Z. The system then creates a type F program called SAPLY|ZThis contains automatically generated INCLUDE statements. The include programs are also named automatically: LY| Z. The abbreviation is assigned according to the principle described on the Program Organization slide. The system also inserts the include program LY|ZUXX. This contains an include statement for each function module in the form LY|ZU.
(C) SAP AG
BC402
18
20.19 Function Groups and Function Modules: Unit Summary
You are now able to: Create function groups Create function modules Call function modules Handle exceptions raised by function modules
SAP AG 1999
(C) SAP AG
BC402
19
20.20 Function Groups and Function ModulesExercise Unit: Function Groups and Function Modules Topic: Creating and Calling a Function Module
At the conclusion of these exercises, you will be able to: • Create function groups • Create function modules • Call function modules You decide to create a global function (a reuse component) that splits the string with the flight data, and use it in your program. Change the modularization of your program so that a function module splits the string containing the flight data.
Program Function group Function module
ZBC402_##_CALL_FUNCTION ZBC402_##_HANDLE_STRINGS Z_BC402_##_STRING_INTO_FLIGHTS
Template
SAPBC402_FMDT_CALL_FUNCTION
Model solution Program Function group Function module
SAPBC402_FMDS_CALL_FUNCTION BC402_FMDS_HANDLE_STRINGS BC402_STRING_INTO_FLIGHTS BC402_T_FLIGHTS BC402_T_DOUBLES
where ## stands for your (two-digit) group number. 1-1
(C) SAP AG
Create a function module to which you will pass a string containing flight data and a separator. The function module should return the flight data and duplicate records as two internal tables. It should include an exception that is raised if the passed separator does not occur in the string. Since function modules are embedded in a function group, you must also create the latter. Follow the detailed instructions below:
BC402
20
1-1-1 Create a function group (suggested name: ZBC402_##_HANDLE_STRINGS). Supply a short text for your function group (we suggest “Split_String_Group##”). 1-1-2 Create a function module in this function group (suggested name: Z_BC402_##_STRING_INTO_FLIGHTS, short text “Extract flight data from string group ##”), which performs the above task. Use the following information to define your interface: Importing parameters Suggested name
Type
Passed by:
IM_DATASTRING
string
Value
IM_SEPARATOR
c
Reference
You should use the importing parameter IM_DATASTRING to pass the string and IM_SEPARATOR to pass the separator. Exporting parameters Suggested name
Type
Passed by:
EX_IT_FLIGHTS
BC402_S_FLIGHTS Reference
EX_IT_DOUBLES
BC402_T_DOUBLES Reference
The exporting parameter EX_IT_FLIGHTS should contain the extracted flight data and EX_IT_DOUBLES should contain the duplicate records. Exceptions Suggested name SEP_NOT_IN_STRING The exception SEP_NOT_IN_STRING should be raised if the separator does not occur in the string. Document the function module and the interface (provide both short and long texts). To implement your function module, use the appropriate parts of the source text from your solution ZBC402_##_SORT (or SAPBC402_TABS_SORT). If the exception is raised, use the MESSAGE ... RAISING ... variant with the message: Message type
I
Message class
bc402
Message
315
Note that: (1) The function module should only split the string into the two tables, ex_it_flights and ex_it_doubles.
(C) SAP AG
BC402
21
To ensure that the function module can be used “universally”, it must not: sort the table in a special way; nor assign colors based on a criterion (such as whether a flight data belongs to a given time interval). This is why the table types BC402_T_FLIGHTS and BC402_T_DOUBLES do not contain a COLOR column. Both tables are sorted by Airline, flight number, and flight date. Each of the programs that use the function module should assign the color values. (2) You will need the following local auxiliary variables in the function module: •
A structure of type c ( previously with type st_flight_c) to split the data records into fields in your program (suggested name: l_wa_sflight_c).
•
A structure of type bc402_s_flight to store the data in the correct format (suggested name: l_wa_sflight).
•
A variable of type string to spit the string into single records (suggested name: l_set_string).
Define these locally in the function module. (3) You can also define local types in the function module. When you determine whether or not an exception has been raised, simplify your program by checking only whether the separators occur at all in the string. To perform the check correctly, you would have to check whether or not the separator occurred in the correct places in the string.
1-2
Copy your program, ZBC402_##_FORM (ZBC402_##_FORM_OPT), or the program ZSAPBC402_TABS_SORT (SAPBC402_TABS_SORT_OPT), to a new program, and call it ZBC402_##_CALL_FUNCTION.
1-3
Now use your function module, Z_BC402_##_STRING_INTO_FLIGHTS, instead of the algorithm you used previously to split the string in the local program, as follows: 1-3-1 Remove all the data definitions that you needed to split the string. You will now use them locally in the function module. 1-3-1 Remove the statement blocks that split the string into it_flights and it_doubles. 1-3-3 Change the type of the internal tables it_flights and it_doubles to the types in the parameter interface of your function module.
(C) SAP AG
BC402
22
1-3-4 After receiving the string to be split from the function module BC402_CREATE_SEP_STRING, call your function module, Z_BC402_##_STRING_INTO_FLIGHTS. If there is no separator in the string, use the message 040 from message class BC402 to terminate your program. 1-4
Now make sure that the data in it_flights and it_doubles is displayed in the same colors, and sorted in the same way, as before. To do this, copy the data into two internal tables that are correctly sorted and that have a COLOR column for the color values. You should assign the color values when copying the data (using LOOP): 1-4-1 Create two internal tables (suggested names: it_list1 and it_list2) for the flight data and duplicate records. Once filled, these tables can be passed later to the subroutine list_output to be displayed. You can use either a SORTED or STANDARD table, since the table kind is immaterial for the loop processing that follows. However, if you want to do the optional exercise for this unit (displaying a list using ALV), use the STANDARD table kind now. (Otherwise, you will have to change it later). (1) Use the global type BC402_S_FLIGHT_COLOR or BC402_T_FLIGHTS_COLOR. (2) If you used your own program, ZBC402_##_FORM_OPT, as a template, you can keep the definitions of it_list1 and it_list2. 1-4-2 Using a loop, copy it_flights and it_doubles to it_list1 and it_list2, filling the COLOR column with the appropriate color value. Proceed almost as for the previous exercises. 1-4-3 If it_list1 has the type STANDARD, you must sort it by flight date, airline, and connection number. 1-4-4 Pass the tables it_list1 and it_list2 to your subroutine list_output. Note that you must change the generic table type, tt_gen, which has the type of the subroutine interface parameter, to the type of the table that has been passed. If you have defined it_list1 and it_list2 as STANDARD tables, you must also assign the kind STANDARD to tt_gen. 1-4-5 Test your program.
(C) SAP AG
BC402
23
OPTIONAL 1-5
Allow the user to choose whether to display the list as an ABAP print list (using WRITE) or using a standard display tool (similar to the optional section in Exercise 1 the Subroutines unit). The approach you take to completing this exercise depends on the program you used as your template: (a) If you used your own program, ZBC402_##_FORM_OPT, or the program SAPBC402_FMDT_CALL_FUNCTION as a template, adapt it as follows: Call the function module BC402_ALV_LIST_OUTPUT and pass the tables it_list1 and it_list2 to it directly. (a) If you used your own program, ZBC402_##_SORT as a template, adapt it as follows: 1-5-1 Allow the user to choose how the system will display the list, using a checkbox on a selection screen. To do this, create a selection parameter class (suggested name: p_list, type: c, addition: AS CHECKBOX, selection text: “output as ALV list”), which you use to display the list as follows: IF p_list IS INITIAL. *
"Conventional" list using WRITE
ELSE. *
List displayed using function module (ALV)
ENDIF. 1-5-2 Implement the logical processing block indicated by the comment “List displayed using function module (ALV)” in section 1-5-1. Use the function module BC402_ALV_LIST_OUTPUT. This module expects two database tables and displays their contents using the ALV Grid Control (a tool used to display non-hierarchical lists). Detailed information on using the ALV Grid Control is not part of this course. For this reason, you use a function module that encapsulates all the necessary technical details, which you can treat as a “black box.” If you want to learn about the techniques used in the function module, and then apply them yourself, refer to the implementation of this function module in the appendix unit of this course. For more information on the ALV Grid Control, see:
(C) SAP AG
•
The online documentation
•
The example programs of the development class SLIS
•
The ABAP Workbench training course BC412: Dialog BC402
24
Programming with EnjoySAP Controls You must pass two STANDARD tables of type BC402_T_FLIGHTS_COLOR to the function module BC402_ALV_LIST_OUTPUT. These tables contain the list data and color values for each line in the scenario we are dealing with in this course (that is, flight dates). The table kind STANDARD is the kind used by the ALV Grid Control, which the function module uses. To display it_list1 and it_list2 using a module: (a) Change the table kind of the tables it_list1, it_list2, and tt_gen to standard (if you have not already done so). (B)Call the function module BC402_ALV_LIST_OUTPUT and pass the tables it_list1 and it_list2 to it. If your program triggers an exception when it executes the function module, it should display an error message. (We suggest “Error processing Control”). (c) Test your program .
(C) SAP AG
BC402
25
Optional Exercise 2 Unit: Function Groups and Function Modules Topic: Global Data in the Function Group
At the conclusion of these exercises, you will be able to: • Create global data in a function group • Use the global data in a function group as a type of “memory.”
You decide to change the dialog behavior of your program, so that the duplicate records extracted are only displayed if the user asks for them. To do this, use the “memory” property of function groups: Global data objects in function groups are retained in memory for as long as the relevant program is active – that is, the program that called the first function module (chronologically) in the group. Program Function group Function modules
ZBC402_##_CALL_FUNCTION ZBC402_##_HANDLE_STRINGS Z_BC402_##_STRING_INTO_FLIGHTS
Template
Your solution from the previous exercise or SAPBC402_TABS_SORT
Model solution Program Function group Function modules
SAPBC402_FMDS_CALL_FUNCTION2 BC402_FMDS_HANDLE_STRINGS2 BC402_STRING_INTO_FLIGHTS2 BC402_GET_DOUBLE_FLIGHTS
where ## stands for your (two-digit) group number. 2-1
Extend the function module Z_BC402_##_STRING_INTO_FLIGHTS so that it stores the data from the return parameter EX_IT_DOUBLES in a global data object in the function group. You will later read this data from there using a second function module. 2-1-1 Create an internal table for duplicate records (suggested name: it_doubles) as a global data object in the function group. Assign the following attributes to the internal table: table kind SORTED, the line type BC402_S_FLIGHT, and key components carrid, connid, and fldate. Make the table NONUNIQUE.
(C) SAP AG
BC402
26
2-1-2 Change the function module Z_BC402_##_STRING_INTO_FLIGHTS so that it stores the duplicate records found in it_doubles, before the end of the function module. 2-2
Extend the function group ZBC402_##_HANDLE_STRINGS to include a function module that reads data from the global data object it_doubles, as follows: 2-2-1 Create a second function module (suggested name: Z_BC402_##_GET_DOUBLE_FLIGHTS) in your function group, ZBC402_##_HANDLE_STRINGS and provide a short text for it. 2-2-2 The function module should contain the following components: EXPORTING parameter: Suggested name
Type
EX_IT_DOUBLES
BC402_T_DOUBLES
This parameter should return the list of duplicate records in the split string. EXCEPTIONS Suggested name EX_IT_DOUBLES This exception should be raised if there are no duplicate records. 2-2-3 Implement the function module. If the exception is raised, use the MESSAGE ... RAISING ... variant with the following message: Message type
I
Message class
bc402
Message
310
2-3
Copy your program, ZBC402_##_CALL_FUNCTION, or the program SAPBC402_FMDS_CALL_FUNCTION, to a new program, and call it ZBC402_##_CALL_FUNCTION2.
2-4
Make sure that your program displays only the list of flight data. To do this, comment out the lines that return the parameter EX_IT_DOUBLES when the function module Z_BC402_##_STRING_INTO_FLIGHTS is called. Similarly, comment out the code that copies it_doubles to it_list2 and displays it_list2. You should not delete these lines, since you can use them again later.
(C) SAP AG
BC402
27
2-5
In the list, display a pushbutton with the text Duplicates on it, which itself displays the list of duplicate records as a details list when the user chooses it. Use the source code from SAPBC402_FMDS_DETAIL_LIST as a guide: 2-5-1 In END-OF-SELECTION, set a GUI status for the basic list that contains an extra pushbutton (with the function code DUPLICATES and the function text “Display duplicates”). Add this pushbutton to the application toolbar and set the function PICK there to inactive. To do this, open the Object Navigator and copy the GUI status Detail from the program SAPBC402_FMDT_DETAIL_LIST to an identically named GUI status in your program. Set the GUI status using SET PF-STATUS 'DETAIL'. in END-OF-SELECTION. 2-5-2 Make sure that the event block AT USER-COMMAND is executed when the user chooses the Display duplicates pushbutton. Using the function module BC402_GET_DOUBLE_FLIGHTS, read the duplicate records into it_doubles. Copy it_doubles to it_list2 and fill the COLOR column with appropriate values. Display it_list2 using the subroutine list_output. If it_doubles does not contain any data records, display a message informing the user instead. Use the following statement pattern to implement the processing block at the AT USER-COMMAND event: AT USER-COMMAND. IF sy-ucomm = 'DUPLICATES' AND sy-lsind = 1. * Processing block to display it_doubles as a list ELSE. * Message informing user that it_doubles does not contain any data ENDIF.
(C) SAP AG
BC402
28
20.21Function Groups and Function Modules: Solutions Unit: Function Groups and Function Modules Topic: Creating and Calling a Function Module
21Function group: BC402_FMDS_HANDLE_STRINGS 21.2Global data None available
22Function module BC402_STRING_INTO_FLIGHTS FUNCTION BC402_STRING_INTO_FLIGHTS . *"----------------------------------------------------------------*"*"Local interface: *"
IMPORTING
*"
VALUE(IM_DATASTRING) TYPE
*"
REFERENCE(IM_SEPARATOR) TYPE
*"
STRING C
EXPORTING
*"
REFERENCE(EX_IT_FLIGHTS) TYPE
BC402_T_FLIGHTS
*"
REFERENCE(EX_IT_DOUBLES) TYPE
BC402_T_DOUBLES
*"
EXCEPTIONS
*"
SEP_NOT_IN_STRING
*"-----------------------------------------------------------------TYPES: BEGIN OF l_st_flight_c, mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c, END OF l_st_flight_c.
(C) SAP AG
BC402
29
DATA: l_wa_flight_c TYPE l_st_flight_c, l_wa_flight
TYPE bc402_s_flight,
l_set_string
TYPE string,
l_set_sep(2) TYPE c. IF im_datastring CA im_separator. CONCATENATE l_set_sep im_separator INTO l_set_sep. CONCATENATE l_set_sep im_separator INTO l_set_sep. WHILE NOT im_datastring IS INITIAL. SHIFT im_datastring BY 2 PLACES. SEARCH im_datastring FOR l_set_sep. IF sy-subrc = 0. l_set_string = im_datastring(sy-fdpos). SHIFT im_datastring BY sy-fdpos PLACES. SPLIT l_set_string AT im_separator INTO l_wa_flight_c-mandt l_wa_flight_c-carrid l_wa_flight_c-connid l_wa_flight_c-fldate l_wa_flight_c-price l_wa_flight_c-currency l_wa_flight_c-planetype l_wa_flight_c-seatsmax l_wa_flight_c-seatsocc l_wa_flight_c-paymentsum. MOVE-CORRESPONDING l_wa_flight_c TO l_wa_flight. INSERT l_wa_flight INTO TABLE ex_it_flights. IF sy-subrc = 4. INSERT l_wa_flight INTO TABLE ex_it_doubles. ENDIF. ENDIF. ENDWHILE. ELSE. MESSAGE i315 WITH im_separator RAISING sep_not_in_string. ENDIF. ENDFUNCTION. (C) SAP AG
BC402
30
23ABAP program REPORT
sapbc402_fmds_call_function.
TYPE-POOLS: col. TYPES: *
BEGIN OF st_flight_c,
*
" STANDARD -----------------------tt_gen
TYPE STANDARD TABLE OF bc402_s_flight_color.
* ---------------------------------------------------------DATA: datastring *
TYPE string,
set_string
TYPE string,
"
View more...
Comments