©SAP AG 2006
AC400 Programming in Financials
THE BEST-RUN BUSINESSES RUN SAP © SAP AG 2006
AC400
Programming in Financials
AC400 Programming in Financials
mySAP ERP 2005 Financial Analytics 2006/Q2
©SAP AG 2006
Copyright 2006 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in
any form or for any purpose without the express permission of
SAP AG. The information contained herein may be changed
without prior notice.
Copyright
Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte können Softwarekomponenten auch anderer Softwarehersteller enthalten.
Microsoft, Windows, Outlook, und PowerPoint sind eingetragene Marken der Microsoft Corporation.
IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, und Informix sind Marken oder eingetragene Marken der IBM Corporation in den USA und/oder anderen Ländern.
Oracle ist eine eingetragene Marke der Oracle Corporation.
UNIX, X/Open, OSF/1, und Motif sind eingetragene Marken der Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, und MultiWin sind Marken oder eingetragene Marken von Citrix Systems, Inc.
SAP, R/3, mySAP, mySAP.com, xApps, xApp und weitere im Text erwähnte SAP-Produkte und
-Dienstleistungen sowie die entsprechenden Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und anderen Ländern weltweit. Alle anderen Namen von Produkten und Dienstleistungen sind Marken der jeweiligen Firmen. Die Angaben im Text sind
unverbindlich und dienen lediglich zu Informationszwecken. Produkte können länderspezifische Unterschiede aufweisen.
In dieser Publikation enthaltene Informationen können ohne vorherige Ankündigung geändert werden. Die vorliegenden Angaben werden von SAP AG und ihren Konzernunternehmen („Konzern“) bereitgestellt und dienen ausschließlich Informationszwecken. Der SAP-Konzern übernimmt keinerlei Haftung oder Garantie für Fehler oder Unvollständigkeiten in dieser Publikation. Der SAP-Konzern steht lediglich für Produkte und Dienstleistungen nach der Maßgabe ein, die in der Vereinbarung über die jeweiligen Produkte und Dienstleistungen ausdrücklich geregelt ist. Aus den in dieser Publikation enthaltenen Informationen ergibt sich keine weiterführende Haftung.
©SAP AG 2006
Required:
z
Basic knowledge of programming
Recommended
z
AC010 – Business Processes in Financial Accounting
z
AC040 – Business Processes in Management
Accounting (Controlling)
z
BC400 – ABAP Workbench Basics
Course Prerequisites
Note to participants
y The course materials are not suitable for self-study. The explanations provided by your course instructor are essential to understanding the materials. The participants' handbook contains space for you to write down notes about this additional material.
©SAP AG 2006
Participant
z
Members of financial accounting departments or system
administrators who deal with tasks that cover a range of
subjects
z
Consultants
Duration
z
Three days
©SAP AG 2006
z
Course Goals
z
Course Objectives
z
Course Contents
z
Overview Diagram
z
Overview of the Exercises
Contents:
Course Overview
©SAP AG 2006
This course will prepare you to:
z
Perform technical programming-related tasks
for the Accounting departments, above all to
z
analyze existing programs
z
create your own programs and reports
©SAP AG 2006
Course Objectives
z
Use the development tools of the ABAP Workbench
z
Analyze and debug Accounting programs
z
Create function modules
z
Enable database access
z
Implement your own ALV reports
z
Define authorization checks
z
Develop and incorporate extractors
©SAP AG 2006
Course Content
Unit 1 Overview
Unit 2 The ABAP Workbench Unit 3 First Attempts at
Programming
Unit 4 Dialogs and ALV Reports Preface
Unit 5 Customer Enhancements Unit 6 Extraction
Unit 7 Template Allocation
©SAP AG 2006
Overview of the Exercises
• Exercises for the Units
• Unit 3: First Attempts at Programming • Unit 4: Dialogs
• Unit 5: Customer Enhancements • Unit 6: Extractors
• Unit 7: Template Allocation
• Optional self-study exercises
• Optional exercise F1: Customer address data • Optional exercise F2: Open and close FI periods • Optional exercise F3: Master data group report
©SAP AG 2006
Overview Diagram: The ABAP Workbench
First Attempts at Programming
First Attempts at Programming
Customer Enhancements
Customer Enhancements
Dialogs and ALV Reports
Dialogs and ALV Reports
The ABAP Workbench
The ABAP Workbench
Extraction
Extraction
Template Allocation
©SAP AG 2006
Overview Diagram: The ABAP Workbench
The ABAP Workbench
The ABAP Workbench
First Attempts at Programming
First Attempts at Programming
Dialogs and ALV Reports
Dialogs and ALV Reports Template AllocationTemplate Allocation
Extraction
Extraction
Customer Enhancements
©SAP AG 2006
The ABAP Workbench – Overview
z
The unit provides an overview of the structure of the
ABAP Workbench and the objects in the repository.
It presents the most important commands in the
ABAP programming language.
©SAP AG 2006
z
Describe the structure of the repository
z
Name and use the search tools in the repository
z
Use the Object Navigator for your development
work
The ABAP Workbench: Objectives
©SAP AG 2006 Presentation server layer Application server layer Database
ABAP Program
Client-independent Client-dependent Repository Application tablesCustomizing tables
The Repository – Embedding
The database contains application and Customizing tables that are usually client-dependent. The database also contains the R/3 Repository. Part of the R/3 Repository is made up of the
ABAP Dictionary.
The R/3 Repository thus contains all the development objects, such as programs, database table definitions or central data type definitions. Development objects are therefore also known as repository objects.
Repository objects are always client-independent. They can therefore be used and changed in all clients.
©SAP AG 2006 Function modules Programs Table definitions
. . .
Repository
FI SD CO HR Customer CO MMMM Customer FI Customer MMM M
Package MM_C Package MM_B Package MM_AStructure of the Repository
Repository objects
The R/3 Repository is subdivided into application components.
Within an application component there are several packages to enable more accurate, logical subdivision..
Repository objects are often comprised of subobjects that are themselves repository objects. When you create a repository object, it must be assigned to a package.
©SAP AG 2006 SAP Cross-Application Components Accounting - General Financial Accounting . . .
FBAS Financial Accounting "Basis" . . .
FI-GL General Ledger Accounting FI-LC Consolidation ... Treasury Controlling
+ + Application component Package Selected subtree + + + + + + CA AC FI TR CO ...+
Information System
SAP Application Hierarchy
The structure of the application components is represented in the application hierarchy. You access the application hierarchy from the Easy Access menu by choosing
Tools ABAP Workbench Overview Application Hierarchy.
The application components are represented in a tree structure in the application hierarchy. When you open up the components you can see the packages assigned to them.
You can select subtrees and navigate from the application hierarchy to the Repository
Information System. The system then collects all the packages for the selected subtrees and
©SAP AG 2006
Repository Information System Business Engineering ABAP Dictionary Basic Objects Database Tables Views Data Elements Structures Table Types . . . Other Objects Fields Programming Function Library Program Library Programming Environment Program Subobjects ABAP Objects Class Library Class Subobjects Interface Subobjects Environment Double-click
Selection
Screen for
Delimiting the
Search
The Repository Information System
You can search specifically for repository objects using the Repository Information System. Suitable search criteria are available for the different repository objects.
The objects you find with the Repository Information System depend on how you navigate there:
y In the application hierarchy, if you click on the Information System pushbutton (double-click on the selected application component(s) or package), only those repository objects that are relevant are "filtered out".
y If, from the Easy Access menu, you choose Tools ABAP Workbench Overview Information System, all the repository objects in the system can be searched from here.
©SAP AG 2006
Function Builder
Screen Painter
ABAP Dictionary
ABAP Editor
Object
Navigator
Menu Painter
Debugger
Class Builder
FI HR MM SD MM WM CustomerABAP Workbench Tools
The ABAP Workbench comprises different tools for processing repository objects. The tools cover the whole software development cycle. The most important tools for creating and processing repository objects are:
the ABAP Editor for editing source texts,
the ABAP Dictionary for editing database table definitions, central datatypes and more, the Screen Painter for creating screens (screen layouts including user dialog functions), the Menu Painter for creating user interfaces (menu bar, toolbar, application toolbar, function
key setting),
the Function Builder for processing function modules, the Class Builder for processing central classes.
There are three possible ways of calling the respective tool: y Call the object directly from the Easy Access menu.
©SAP AG 2006
Adjustable border
Context menu
Full screen on/off
Context menu Right mouse button Navigation area Tool area . . . . . .
Screen Layout in the Object Navigator
Right
mouse button
The Object Navigator screen is divided into two areas:
y The navigation area to display an object list as a hierarchy tree,
y The tool area, in which a package can be displayed or processed using the appropriate tool. You can hide or display the hierarchy area.
You can choose functions from the context menu in both windows. In each case, you can only choose those functions intended for displaying or processing the object on which the cursor is positioned. You open the context menu with the right mouse button (if you have set the mouse for left-handed users, this would then be the left mouse button).
©SAP AG 2006 DDIC objects Programs SAPBC400WBD_GETTING_STA SAPBC400WBT_GETTING_STA Function groups BC400 Classes CL_BC400 BC400 Package BC400 Previous/next object list Application hierarchy Package Program Function group Class/Interface ... Inactive objects Local objects Organize Favorites Update object list Higher-level object list Navigation by double-click
The Navigation Area
Repository objects are organized hierarchically:
y An application component can contain various development classes.
y A development class in turn can contain different repository objects: Programs, function groups, ABAP Dictionary objects and so on.
y A repository object can comprise various subobjects:
- For a program: Global data, types, events, subroutines and so on - For a function group: Global data, function modules and so on
You can enter the type of object list and the object names in the upper part of the navigation area. The object list is then displayed in the navigation area.
Double-click on an object in an object list to display the subobjects.
Double-click on an object that does not belong to an object list to display the object using the appropriate tool in the tool area.
©SAP AG 2006 Navigation stack Functions of the current tool Show navigation window Navigation history Previous/next object
Navigation in the Tool Area
You can show a window for historical navigation in the tool area. A list is displayed there with the objects that you have displayed in the tool area since you started the Object Navigator.
©SAP AG 2006 Display object list Double-click or context menu function
Modifying the Tool Area
Navigation in the navigation and tool area is decoupled. This allows the navigation area to be used very flexibly.
Both areas can be made to match one another if required:
y You can access the object display in the tool area by double-clicking the object or from the navigation area. The system then automatically chooses the relevant tool for editing the object you have selected.
y You can call the object list display that belongs to an object that you are currently processing in the tool area by choosing Display Object List.
You can use the context menu for an object type to create objects for an object list. If no entry for the required object type exists in the object list, you can create any objects you like using
©SAP AG 2006 Create package Package Short description Application component Software component Transport layer Package type ZBC400_00 Exercises group 00 CA HOME ZDEV No main package
Where should the development objects
be transported ? To which application component does the
package belong ? Comply with
customer namespace !
Creating Packages
You can create a package from the Object Navigator:
y With Release 4.6 c you can select the Development Class object type and enter the name of the package in the input field. Make sure you comply with the customer namespace in the process. If the package does not exist, the dialog box branches to the screen where you can create a package.
y With Release 4.6 a/b you have to select Edit Object or Other Object in the initial screen. Enter the name of the package on the More tab strip in the Development Class entry field. Check the presettings for the following attributes:
y Transport layer: If you carry out your own development, a transport layer has to be set up for customer development.
y Person responsible: The person responsible carries full responsibility for the objects in this package. Your user name is entered as the default value.
y Software component: You usually enter customer developments under HOME. You will find more detailed information in the F1 help for the field.
y Application component: Determine where the package should appear in the application hierarchy.
©SAP AG 2006 Package
Enter transportable Workbench request ZBC400_00
Enter transportable Workbench request Change requests involving BC400-00
Changeable Transportable IT3K900051 CARSON IT3K900052 CARSON IT3K900053 BC400-00 IT3K900054 BC400-01 Request IT3K90051
Participants' exercises for course BC400 Workbench request
Double-click on order number
Own requests
. . .
Assignment to Change Requests
The creation and change of each repository object must be assigned to the change request for the respective project. For this course, the instructor has created a change request for the project Participants' exercises for course BC400. Each group has a task within this change request.
You can display all the change requests in which you have tasks using the Own Requests pushbutton.
Simply assign all repository objects (packages, programs and so on) to this change request. The system assigns your task more precisely.
©SAP AG 2006
Additions and operands (keyword-specific) ABAP keyword SELECT ENDSELECT. WRITE . . . Period to close the statement DATA . NEW-LINE. WRITE WRITE .
General structure of an ABAP statement
X X X
Y Y Y
Sample Program
...wa_scarr TYPE scarr
* FROM scarr INTO wa_scarr wa_scarr-carrid wa_scarr-carrname wa_scarr-url
ABAP Syntax I
An ABAP program comprises individual statements. Each statement must be concluded with a period. The first word in a statement is a keyword.
Words are separated by at least one blank character. Statements can be indented.
Statements can extend over several lines. One line can comprise several statements.
The ABAP runtime system does not distinguish between upper and lower case keywords, additions and operands. To make things more transparent, all keywords and their additions are written in upper case and all operands in lower case in this course.
You can use the Pretty Printer for indentations and converting upper and lower case: Utilities Settings ABAP Editor Pretty Printer.
©SAP AG 2006 : : ,, . . Chained statement * * * * * * " " Comments (complete lines) comments ... comments ... comments ...
DATA wa_scarr TYPE scarr.
SELECT * FROM scarr
INTO wa_scarr. "" comments ... comments ... Command-related comments NEW-LINE. WRITE wa_scarr-carrid , , wa_scarr-carrname wa_scarr-url ENDSELECT. " " comments ...
ABAP Syntax II
You introduce comment lines with an asterisk *. The corresponding commented line is ignored by the ABAP runtime system.
If you want to add a comment to the remainder of a line that has already been started, you have to use quotation marks ".
You can group successive statements that begin in the same way in a chained statement: y Close the identical start of the statement with a colon.
y Separate the chained parts of the statement that follow the colon with commas.
y Spaces and line breaks can come before and after the separators (colon, comma, period). y Note that the individual components of a chained statement represent separate instructions
©SAP AG 2006 REPORT ...
PARAMETERS pa_carr TYPE scarr-carrid. DATA wa_scarr TYPE scarr.
SELECT SINGLE * FROM scarr INTO wa_scarr
WHERE carrid = pa_carr. IF sy-subrc EQ 0. NEW-LINE. WRITE: wa_scarr-carrid, wa_scarr-carrname, wa_scarr-url. ELSE.
WRITE 'Sorry, no data found!'. ENDIF.
SY-SUBRC as Return Code
For many ABAP statements, the ABAP runtime system writes a numeric value to the system field sy-subrc to indicate how successful the execution of this statement was.
The value zero always indicates that the statement was executed successfully.
You can find out whether and how this return value is set in each individual case in the documentation for the respective statement.
©SAP AG 2006
With TOP include Create program
Program ZBC400_00_GS
Attributes
ABAP program properties ... Header My 1st ABAP program
Type Status Application
Fixed point arithmetic Executable program
Test program
Comply with customer namespace !
. . .
Save . . .
Creating a Program
The following options are available for creating a program from the Object Navigator: y In the navigation area, choose the Program object type and enter a name. Make sure you
comply with the customer namespace in the process. If the program does not exist, the system takes you through a dialog sequence to create the program. (This procedure is only possible as of Release 4.6 c.)
y Display the package for which the program is to be created. Use the context menu for the package or the Programs node to trigger the dialog sequence for creating a program. y Choose Other Object or Edit Object. Choose the Program Objects tab page and enter the
name. Now choose Create.
For this course, remove the With TOP Include indicator (otherwise, your source text would be distributed to several programs).
Change the title to a self-explanatory short text.
©SAP AG 2006
START-OF-SELECTION.
SELECT SINGLE * FROM scarr INTO wa_scarr
WHERE carrid = pa_car. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. CALL SCREEN 100. MOVE-CORRESPONDING sbc400_carrier TO wa_scarr. WRITE: wa_scarr-carrid, wa_scarr-carrname, wa_scarr-currcode. ENDIF.
i
WRITE WRITE ABAP overview ABAP termWhat's new in ABAP ABAP glossary ABAP index . . . Help WRITE F1 Keyword documentation
Documentation of ABAP Terms
There are a number of navigation options for displaying keyword documentation for an ABAP statement:
y The F1-button takes you directly to the documentation for the statement on which the cursor is currently positioned.
y The Information button takes you to a display frame for different views of the keyword documentation.
Under Help SAP Library Basis you will also find comprehensive documentation for all tools and topics relating to the ABAP Workbench.
©SAP AG 2006
Program A ( inactive version )
Saved programs
(for further development/testing)Activated programs
(for using/transporting across all systems)
Program A ( active version ) Activate Program B ( active version ) Program C ( active version ) Program C ( inactive version )
Inactive and Active Development Objects
If you create or change a development object and then save it, an inactive version is always stored in the R/3-Repository first.
A repository object has to exist as an active version before it becomes available across the system, however. This active version of your program is then drawn when a user wants to execute your program, for example.
If your program exists in both versions, you can switch between the two versions in display mode.
If you activate a program, a list of all the inactive objects that you have processed is displayed first in the worklist. When you activate a program, the following occurs:
It is saved, which means that the inactive version is either stored or overwritten. The program syntax is checked.
©SAP AG 2006
Generating Runtime Objects
Saved programs
(for further development/testing)Activated programs
(for using/transporting across all systems)
Program A ( active version ) Program B ( active version ) Program C ( active version ) Program C ( inactive version ) When executed (from the editor),
the relevant runtime object is always generated again.
When executed, the runtime object generated during activation
is used.
When a development object is generated, a separate runtime object (LOAD) is created (compiled) and stored in the R/3 Repository too.
This generated object is the one that is executed (interpreted).
The object is generated automatically, but can also be generated explicitly.
If, for example, a user wants to execute your program and no generated version exists at that time, the active version is taken to be generated.
You yourself can choose which version you want to execute:
If you start your program from the navigation area, the active version is taken for generation. If you test an executable program from the editor, however, the inactive version is taken. A temporary generated version is created.
This makes it possible for you to further develop the program without changing the current system status. The changes to the development object can only be "seen" across the system when the object is reactivated. A local, separate view is created on the R/3 Repository with the inactive versions, which creates the basis for a "local runtime system".
©SAP AG 2006
System System HelpHelp
ZBC400_00_GS
Create report transaction
Transaction code Z00GS Package ZBC400_00 Transaction text Program ... . . . ZBC400_00_GS Classification
Professional User Transaction Easy Web Transaction
. . . . . .
Creating a Transaction Code
If you want to add a program to the menu for a role or to the Favorites in your SAP Easy Access menu, you have to assign it to a transaction code.
To do this, display the object list for your program in the Object Navigator. In the context menu for the program name, choose Create Transaction. Make sure you comply with the customer namespace in the process.
Choose Program and Selection Screen (Report Transaction), if the program is an Executable
Program.
Enter the name of the program on the subsequent screen. Choose Professional User
Transaction.
Save your transaction code.
Since a transaction code is a repository object, you have to assign it to a package and a change request in the subsequent screens.
©SAP AG 2006
Favorites
SAP Menu
SAP Easy Access
Object Navigator
Enter a transaction manually Transaction code Z00GS Insert Transaction
. . . . . .
Inserting Transaction Codes in Favorites
System System HelpHelp
To enter a transaction code in the Favorites for your role menu, proceed as follows: y Navigate to the initial screen (SAP Easy Access menu).
y In the Favorites context menu, choose Insert Transaction. y Enter the transaction code in the dialog box.
The short text for the transaction then appears under the Favorites node. You can use the context menu for this new node to start the relevant program.
©SAP AG 2006
ABAP program
Subroutine Interface Inte rface . . . Definition of input/output fields. . . Definition of data objects
. . . Method Interface . . . . . . Typing interface parameters . . . Typing interface parameters . . . Typing interface parameters Func tion mod ule
Data Types
The type of a data object determines its technical properties.
The type of an interface parameter determines the type of values (actual parameters) that are transferred when a modularization unit is called.
The type of an input/output field can also provide information in addition to the technical properties. For example, it can be used to control the input help.
©SAP AG 2006
ABAP Dictionary Global data types (technical and semantic
properties)
ABAP program
Subroutine Interface Inte rface . . . Method Interface . . . Fun ctio nm odu le Data types local to programs(technical properties only)
Local vs. Global Data Types
Data types can be defined both within an ABAP program (local, keyword TYPES) or in the ABAP Dictionary (global). There are many advantages in using global data types:
Global types are managed centrally and can be used in all repository objects. This improves the consistency of the system and reduces the effort required for maintenance considerably. An environment analysis is available in the ABAP Dictionary (where-used-list).
The content of global data types can be coupled to business variables, and can thus contain semantic as well as technical information.
This can be used to create screens too.
When searching for global types, you should therefore make sure that you take semantic properties into account as well as technical ones. Only this way can you fully exploit the advantages of ease of maintenance and robustness of your program.
©SAP AG 2006
Implemented ABAP types (Standard types in ABAP)
X I F STRING XSTRING T D C N P TYPES type_name TYPE ...
DATA myvar TYPE type_name .
DATA myvar2 LIKE myvar.
ABAP program
Global types ABAP
Dictionary
Declaration of local types
Elementary Data Types
You can use an implemented ABAP type, a local or a global type to type data objects. The following implemented ABAP types are complete:
y d Date (Date, format: YYYYMMDD) y t Time (Time, format: HHMMSS) y i Integer (Integer)
y f Floating point number (Floating point) y string String (String, variable length)
y xstring Byte sequence (HeXadecimal string, variable length) The length must be specified for the following implemented types:
y c Character (Character)
©SAP AG 2006
S_CARR_ID (Data element) ...
TYPES t_percentage(3) TYPE p DECIMALS 2. DATA: percentage1 TYPE t_percentage,
percentage2 TYPE t_percentage, number1 TYPE i VALUE 17, number2 LIKE number1, city(15) TYPE c,
carrid TYPE s_carr_id,
connid TYPE sbc400focc-connid.
number1 percentage2 carrid connid SBC400FOCC (Structure) percentage1 00000+ 0 0 0 0 + 0 0 0 0 0 number2 0 17 city
Declaration of Variables
The predefined ABAP types d, t, i, f, string and xstring are complete. This means that you can define an elementary data object for these types in the following way:
DATA do_name TYPE predefined_ABAP_type.
y With the predefined ABAP types c, n, p, and x you still have to determine the length. This means that you should first define an elementary type:
- TYPES type_name(length) TYPE predifined_ABAP_type. - You then use this to define the data object:
- DATA do_name TYPE type_name.
- For type p, you can also determine the number of decimal places using the DECIMALS addition.
With the VALUE addition you can preassign a value for an elementary data object.
For compatibility reasons, it is still possible to construct data objects in the DATA statement without defining the type locally to a program using a TYPES statement.
When you use global types, the syntax is the same as for user-defined types: DATA do_name TYPE global_type_name.
©SAP AG 2006
Literals:
Constants :
Fixed data objects without identifier
Character string : 'Hallo' Decimal numbers : '123.45'
Floating point numbers : '123.45E01' Text literals
myconst TYPE type_name VALUE { literal | IS INITIAL } . CONSTANTS
positive integer : 123 negative integer : -123
Fixed data objects with identifier
Numeric literals
Fixed Data Objects
You already assign a value to fixed data objects in the source text. This value can therefore no longer be changed at runtime.
With literals you can transfer fixed values to ABAP statements. There are numeric literals and text literals. The latter are enclosed by quotation marks.
y You can represent integers (with a minus sign for negative numbers) as numeric literals. They are then mapped to data type i if they lie within the value range of 4-byte integers. Larger numeric literals are mapped to data type p.
y You must represent all other literals (character strings, floating point numbers, ...) as text literals. They are mapped to data type c and converted later, if necessary.
If a text literal contains an inverted comma, you have to enter this twice.
Constants are defined with the CONSTANTS statement. Typing takes place in the same way as the definition of elementary data objects with DATA. The VALUE addition is mandatory for constants. This determines the value for the constants.
©SAP AG 2006
ABAP runtime system
MOVE c_qf TO carrid1. carrid2 = carrid1. ADD 1 TO counter. CLEAR: carrid1, carrid2, counter.
CONSTANTS c_qf TYPE s_carr_id VALUE 'QF'. DATA: carrid1 TYPE s_carr_id,
carrid2 TYPE s_carr_id VALUE 'LH', counter TYPE i. Program start Data declarations c_qf QF carrid1 carrid2 LH counter 0 QF LH 0 QF QF 0 QF QF 1 0 ABAP program
Value Assignments
If a program is started, the program context is loaded to a storage area on the application server and storage space is made available for all the data objects.
Each elementary data object is given the initial value assigned to its type, unless it has been allocated a different value by means of the VALUE addition.
You can use the MOVE statement to copy the contents of data objects. Two syntax variants are available for this:
y MOVE source TO target. y target = source.
If both data objects belong to different types, the type is converted automatically if a conversion rule exists.
You will find detailed information about copying transactions and conversion rules in the keyword documentation for the MOVE statement.
The CLEAR statement resets the content of a data object to the initial value for the type. You will find detailed information about initial values for types in the keyword documentation for the CLEAR statement.
©SAP AG 2006
DATA: max TYPE sbc400focc-seatsmax,
occ TYPE sbc400focc-seatsocc,
percentage TYPE sbc400focc-percentage.
Keyword COMPUTE is optional :
percentage = occ * 100 / max .
ABAP program
Data declarations
* /
Calculations
COMPUTE percentage = occ 100 max .
In ABAP you can program nested arithmetic expressions as "deep" as you wish. Note that brackets and operators are keywords and must therefore be enclosed by at least one blank character. Valid operators are:
y + Addition y - Subtraction y * Multiplication y / Division y ** Power
y DIV Integral division without remainder y MOD Remainder with integral division
There are numerous functions for the different data types in the ABAP runtime environment. For example, the following statement provides the current length of the content of a character
The usual algebraic rules normally apply for the evaluation sequence, in other words, first the bracketed expressions, then functions, followed by powers, multiplication/division, and finally addition/subtraction.
You will find detailed information about possible operations and functions in the keyword documentation for COMPUTE.
©SAP AG 2006 Statements Statements Statements Statements Statements Statements
Conditional Branches
IF var > 0 . ELSEIF var = 0 . ELSE .ENDIF . CASE mycarrid.
WHEN 'AA'.
WHEN 'LH'.
WHEN OTHERS .
ENDCASE .
In ABAP you have two options for executing different sequences dependent on certain conditions.
With the CASE-ENDCASE construct, the similarity of the data objects is the criterion for executing a statement block. If the comparison fails, the OTHERS branch is executed, providing it exists.
Until the first WHEN branch, all other additions are optional.
With the IF-ENDIF construct you can use any logical expressions you want. If the condition is fulfilled, the relevant sequence is executed. If no condition is fulfilled, the ELSE branch is executed, providing it exists.
Until the first query, all other branches are optional.
With both constructs, only one statement block is ever executed, namely for the first valid case.
©SAP AG 2006
DO.
IF <abort_condition>. EXIT. ENDIF. ENDDO.
DO n TIMES. ENDDO.
WHILE <condition>. ENDWHILE.
SELECT ... FROM <dbtab> ... ENDSELECT.
LOOP AT <internal table> ... ENDLOOP. Loop counter sy-index Statements Statements Statements Statements Statements Loop counter sy-index Loop counter sy-index
Loops
In ABAP there are four loop constructs. LOOP-ENDLOOP and SELECT-ENDSELECT represent special cases. With the first two of the loop types shown here, the number of the current loop pass is counted by the system in the sy-index field. With nested loops the system always counts the current one.
Unconditional/index-controlled loops
The statements between DO and ENDDO are executed until the loop is exited through other statements. Another option is to specify the number of loop passes, otherwise you can get a so-called endless loop.
Precondition loops
The statements between WHILE and ENDWHILE are only executed if the <logical_expression> condition is fulfilled.
With the statements CHECK and EXIT you can influence loop processing in different ways. For example, you can construct a postcondition loop.
©SAP AG 2006
MESSAGE tnnn(message_class) [ WITH v1 [ v2 ] [ v3 ] [ v4 ] ] .
Type Dialog behavior Message appears in i s w e a x Program continues after interruption Program continues without interruption Context-dependent Context-dependent Program is terminated
Runtime error MESSAGE_TYPE_X is triggered
modal dialog box
Status bar of next screen
Status bar Status bar modal dialog box Short dump Meaning Info message Success message Warning Error Abort Short dump
Dialog Messages
You can send dialog messages with the MESSAGE statement. You must specify the three digit number of the message and the message class.
You can also use the WITH addition to include up to four values. These are set dynamically, dependent on the message text.
The type ID t controls the dialog behavior. There are six different qualifications for messages: y a Abort The program is terminated after a dialog box.
y x Exit The program is terminated with a short dump. y e Error The runtime behavior is context-dependent.
y w Warning The runtime behavior is context-dependent. y i Information The program continues after a dialog box.
y s Success The message appears on the following screen in the status bar.
©SAP AG 2006
wa_focc TYPE sbc400focc. wa_spfli TYPE spfli. DATA
DATA
wa_focc
carrid connid fldate seatsmax seatsocc percentage
wa_spfli
carrid connid countryfr cityfrom airpfrom
mandt countryto . . .
Data Dictionary Data element
Structure SBC400FOCC
Transparent table SPFLI
Table types Field type Structure type Type for internal tables
Global Reference Structures
In ABAP you can define structured data objects (known as structures for short). You can group values that belong together logically in one object.
Structures can be nested so that components can, in turn, be derived from structures or even tables.
There are two different ways of defining structures:
y With DATA struc_name TYPE struc_type you can use local or global types struc_type. y With TABLES global_struc_type a structure is defined that is technically managed in a
special storage area. It has an identical name to the global structure global_struc_type or the transparent table global_struc_type.
The global structure has to be "flat" for this variant, in other words, the components must be elementary type components.
©SAP AG 2006
wa_flightinfo
carrid connid fldate seatsmax seatsocc percentage
TYPES: BEGIN OF st_flightinfo,
carrid TYPE s_carr_id,
connid TYPE s_conn_id,
fldate TYPE s_date,
seatsmax TYPE sflight-seatsmax,
seatsocc TYPE sflight-seatsocc,
percentage(3) TYPE p DECIMALS 2, END OF st_flightinfo.
DATA wa_flightinfo TYPE st_flightinfo.
Declaration of a local structure type
Definition of a structure variable
Structures Without Local Reference
You can also define structure types locally with the TYPE statement. The components are enclosed by
y BEGIN OF structure_type_name, y ... ,
y END OF structure_type_name
. Each individual component can also be given any type you wish.
You will find further information in the keyword documentation for TYPES. You define the data object itself in the usual way.
For compatibility reasons, a structured data object can also be defined directly: y DATA: BEGIN OF structure_name,
y ... ,
©SAP AG 2006
DATA wa_scarr TYPE scarr. wa_scarr carrid = 'LH'. SELECT SINGLE * FROM scarr
INTO wa_scarr
WHERE carrid = wa_scarr carrid. WRITE: / wa_scarr carrid,
wa_scarr carrname, wa_scarr url. -wa_scarr
mandt carrid carrname currcode url
400 LH Lufthansa EUR www.lufthansa.com
Accessing Structure Components
Components in a structure are always addressed with a hyphen: structure_name-component_name.
©SAP AG 2006
DATA: wa_sflight TYPE sflight, wa_focc TYPE sbc400focc.
MOVE-CORRESPONDING wa_sflight TO wa_focc.
wa_focc
carrid connid fldate seatsmax seatsocc percentage wa_sflight
carrid connid fldate price seatsmax
mandt seatsocc . . .
. . .
planetype
Value Assignments Between Structures
The MOVE-CORRESPONDING source_struc TO target_struc statement copies the content of the source_struc structure component for component to the target_struc structure. The precondition for the value assignment is that the components have the same name. The other components remain unchanged.
©SAP AG 2006 Dynamic increase in storage capacity Print list Screen display Database tables Files
internal Tables
Internal tables are data objects with which you can hold a number of data records with the same structure in the working memory. The number of data records is unlimited. It is only restricted by the limits placed on capacity by actual system installations.
The length of internal tables is managed dynamically by the ABAP runtime system. This means that the developer does not need to do anything with regard to managing the working memory.
The individual data records of an internal table as known as table entries. The individual components of a line are also known as the columns of the internal table.
The line types of internal tables can be any ABAP data types. They can be elementary, structured or even internal tables themselves.
Internal tables therefore provide you with a very convenient option for processing large data volumes in a structured form in the program. Typical areas of application are:
y Retaining data from database tables for processing at a later stage, y Structuring and staging data for output,
©SAP AG 2006
AA 0017 2.572 LH 0400 6.162 QF 0005 10.000 LH 0402 7.273
CARRID CONNID DISTANCE
SQ 0866 1.625 UA 0007 2.572 • Components • Uniqueness • Sequence Index Index 5 4 3 2 1 6 • Standard • Sorted • Hashed
Line type
Key
Table type
Properties of an Internal Table
1
2
3
The data type for an internal table is completely specified through the following properties: Line type
The properties of the individual columns are derived from this. You usually specify a structure type, however, any data types are possible.
Key definition
The key columns and their sequence determine the criteria for identifying lines in a table. The key can be defined as unique or non-unique, depending on the access type. With unique keys there are no multiple entries in internal tables with identical keys.
Access type
y With key access, data is accessed - in the same way as for database tables - by way of field contents.
Example: Read access with the search term 'UA 0007' to an internal table with a unique key CARRID CONNID and the same data as above will yield exactly one data record.
©SAP AG 2006 Index access Key access Key uniqueness HASHED TABLE
STANDARD TABLE SORTED TABLE
Index tables
Table type
n
NON-UNIQUE UNIQUE | NON-UNIQUE UNIQUE
Usage with predominant
index access
predominant key access
exclusive key access
Table Type and Access Type
Hashed table
Another property of an internal table is the table type. Internal tables can be divided into three table types using the possible access types:
y With Standard tables, line numbering is maintained internally. Both index and key access is possible.
y With sorted tables, the data records are always saved sorted according to the key. With sorted tables, the index is maintained internally too. Both index and key access is possible. y With hashed tables, the data records are managed in the optimum way for runtime. A
unique key is required for this. With hashed tables you can only use key access.
The table type to be used in each individual case depends on the way in which table entries are normally accessed:
y Standard tables are normally used for index access: y Sorted tables are used for unique keys and fixed sorting.
y With hashed tables, runtime optimization is only noticeable if read access with a unique key is predominantly used.
©SAP AG 2006
itab_flightinfo TYPE sbc400_t_sbc400focc. DATA
itab_flightinfo
carrid connid fldate seatsmax seatsocc percentage
Access Key Key type
Key components
Line type SBC400FOCC
non-unique
CARRID, CONNID, FLDATE
SBC400_T_SBC400FOCC
Table type
Standard table
Global Table Types
Table types can be defined locally for a program or globally in the ABAP Dictionary. With DATA itab_name TYPE itab_type you can use local or global types itab_type.
You will find detailed information about defining global table types in the ABAP Dictionary in the SAP Library under Basis ABAP Workbench BC - ABAP Dictionary Types Table
©SAP AG 2006
itab_flightinfo
carrid connid fldate seatsmax seatsocc percentage
WITH NON-UNIQUE KEY
sbc400focc
Local table type
Internal tables
Local Table Types
TYPES tt_flightinfo
TYPE STANDARD TABLE OF
carrid connid fldate.
DATA itab_flightinfo TYPE tt_flightinfo.
You can define internal types locally too, using a TYPES statement. The table type is specified between TYPE and TABLE OF.
The line type follows TABLE OF.
The key fields are listed after the WITH addition. Note that the sequence of the key fields is important here.
You will find detained information about the definition of table types that are local to programs in the keyword documentation for TYPES.
You define the data object itself in the usual way.
For compatibility reasons, you can define an internal table directly too: DATA itab_name TYPE table_kind TABLE OF struc_type WITH key_def.
©SAP AG 2006
DATA wa TYPE spfli. SELECT ... FROM spfli
INTO wa ...
DATA wa TYPE sbc400focc.
DATA itab TYPE
sbc400_t_sbc400focc.
ABAP program ABAP Dictionary Database
SPFLI Transparent table (Description) SBC400FOCC Structure SBC400_T_SBC400FOCC Table type AA 17 ... AA 64 ... ... ... ... LH 400 ... LH 402 ... SPFLI wa wa itab
©SAP AG 2006 Append Insert Read Change Delete wa to itab.
wa INTO TABLE itab <condition>.
itab INTO wa <condition>.
TABLE itab FROM wa [ <condition> ].
itab <condition>. APPEND INSERT READ TABLE MODIFY DELETE
©SAP AG 2006
Single record processing over the whole
(or part) of the internal table
Delete several records
Insert several lines from another internal table
Append several lines from another internal table
Group Access Overview
LOOP AT itab INTO wa <condition> . ...
ENDLOOP .
DELETE itab <condition> .
INSERT LINES OF itab1 <condition1> INTO itab2 <condition2> .
APPEND LINES OF itab1 <condition> TO itab2.
The following set operations are available for internal tables. wa stands for a structure that must be the same type as the line type of the internal table itab:
y LOOP ... ENDLOOP The LOOP places the rows of an internal table one after the other into a structure that is specified in the INTO clause. All single record operations can be carried out within the loop. With single record operations, the system identifies the line to be processed in this case.
y DELETE deletes the lines of an internal table that satisfy the <condition> requirement. y INSERT copies the content of several lines of an internal table into another internal table. y APPEND appends the content of several lines in an internal table to another standard table. You will find detailed information about the ABAP statements listed here in the respective
©SAP AG 2006
* fill structure with values wa_flightinfo-carrid = ... . wa_flightinfo-connid = ... . wa_flightinfo-fldate = ... . wa_flightinfo-seatsmax = ... . wa_flightinfo-seatsocc = ... . wa_flightinfo-percentage = ... .
* insert structure into internal table
INSERT wa_flightinfo INTO TABLE itab_flightinfo. * define internal table and workarea
DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF itab_flightinfo.
itab_flightinfo
wa_flightinfo
Inserting a Single Record
You can insert lines in an internal table by first filling a structure with the required values and then inserting them into the internal table using the INSERT statement.
With standard tables, this appends the line, whereas with sorted and hashed tables, the line is inserted by means of a key.
©SAP AG 2006
LOOP AT itab_flightinfo INTO wa_flightinfo. WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP. sy-tabix
Reading by Loop
* define internal table and workarea
DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF itab_flightinfo.
itab_flightinfo
wa_flightinfo
You can read and process the content of an internal table using a LOOP by accessing the structure components within the loop.
In this example, a list is compiled from the field contents using the WRITE statement. If you want to change the contents of the internal table, first change the value of the
components within the loop and then overwrite the line in the internal table using the MODIFY statement.
©SAP AG 2006
sy-tabix
Reading by Index
LOOP AT itab_flightinfo INTO wa_flightinfo FROM 1 TO 5 . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP.
READ TABLE itab_flightinfo INTO wa_flightinfo INDEX 3 . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'.
You can use the INDEX addition to limit access to specific line numbers. Index operations can only be performed on index tables. They are therefore only supported for standard and sorted tables.
In the above example, only the first five lines of the internal table are processed. In the example below, the third line of the internal table is read.
©SAP AG 2006
sy-tabix
Reading by Key
LOOP AT itab_flightinfo INTO wa_flightinfo WHERE carrid = 'LH' . WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, wa_flightinfo-fldate, wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDLOOP.
READ TABLE itab_flightinfo INTO wa_flightinfo WITH TABLE KEY carrid = 'LH'
connid = '0400' fldate = sy-datum . IF sy-subrc = 0. WRITE: / wa_flightinfo-seatsmax, wa_flightinfo-seatsocc, wa_flightinfo-percentage, '%'. ENDIF. sy-tabix
You can use the WHERE addition to limit access to lines with specific values. Key operations are supported for all table types.
With a completely specified key, key accesses to sorted and hashed tables normally make less demands on runtime than key accesses to standard tables.
In the above example, only those lines in the internal table are processed where the carrid field contains the value "LH".
(Performance aspect: The sorted table is best suited for this kind of processing.)
The example below shows the syntax for reading a line in the internal table with a completely specified key. The return code sy-subrc is set to zero if a corresponding line exists in the internal table.
(Performance aspect: The hashed table is best suited for this type of single record access when the number of data records it contains is very large.)
©SAP AG 2006 DESCENDING ASCENDING REFRESH itab_flightinfo. FREE itab_flightinfo. SORT itab_flightinfo.
Sorting a Standard Table
SORT itab_flightinfo BY carrid.
SORT itab_flightinfo BY percentage
carrid .
You can sort standard tables into columns of your choice by specifying the column name after the BY clause of the SORT statement.
SORT itab [ ASCENDING | DESCENDING ]
[ BY f1 [ ASCENDING | DESCENDING ] ...
fn [ ASCENDING | DESCENDING ] ] [ AS TEXT ]
[ STABLE ].
y Sorting the internal table according to the table key or the specified field sequence: Without addition in ascending order.
With the AS TEXT addition you can take account of culture-specific sort rules when sorting according to character type fields.
When sorting, the relative sequence of the data records that are not differentiated in the sort key is retained only with the STABLE addition.
In this example, the data records for the internal table are sorted in descending order according to the extent to which the flights are used, expressed as a percentage.
©SAP AG 2006 Internal table itab
INSERT itab INDEX n. DELETE TABLE itab.
READ TABLE itab INDEX n. WRITE itab-carrid.
Implicit syntax Explicit syntax
Internal table itab DATA itab
TYPE STANDARD TABLE OF scarr WITH NON-UNIQUE KEY carrid.
. DATA wa LIKE LINE of itab
Internal Tables with and Without Header Lines
DATA itab
TYPE STANDARD TABLE OF scarr WITH NON-UNIQUE KEY carrid WITH HEADER LINE .
Work area wa Header line itab
INSERT wa INTO itab INDEX n. DELETE TABLE itab FROM wa.
READ TABLE itab INTO wa INDEX n. WRITE wa-carrid.
Internal tables can de defined with or without header lines (addition WITH HEADER LINE). An internal table with header line is a data set from a work area (header line) and the actual body of the table.. Both objects are addressed using the same name! The interpretation of this names depends on the context. With MOVE, for example, it stands for the header line, with SEARCH for the body of the table.
In order to avoid confusion, we recommend you use internal tables without a header line. This is particularly evident with nested tables. On the other hand, with operations on internal tables with header lines, a shortened syntax is often possible (APPEND, INSERT, MODIFY, COLLECT, DELETE, READ, LOOP AT). Within ABAP objects, only internal tables without header lines are allowed.
You can always address the body of an internal table itab uniquely by using the following syntax: itab[]. This is the case regardless of whether the internal table has a header line or not. y Example
©SAP AG 2006 Application server Native SQL
ABAP
Open SQL Native SQL Table buffer Database server Database interfaceDatabase Accesses
Open SQL statements are a subset of SQL Standards that are fully integrated in ABAP.
They allow the ABAP developer unified access to data, independent of the installed database system. The database interface converts Open SQL to database-dependent SQL statements.
©SAP AG 2006
Application-related search
Search within a particular application component:
Application hierarchy
Search within a program that accesses the required table:
Source text search: Search in the editor for the SELECT statement
Function debugging: Prior to executing a subfunction
switch to debugging mode ("/h") and set breakpoint at SELECT
statement
Using screen field information: Display corresponding structure field
with F1 + "Technical Information", double-click to navigate to the
relevant data element and execute "Where-Used-List in Table Fields"
Program-related search
Table Drilldown Report
When searching for database tables, you have various options: Using the Application
Hierarchy or the Repository Information System.
If you already know a program that accesses the required database table: y Debugger:
- Start this program in debugging mode and set a breakpoint at the SELECT statement. y Editor:
- Search for the SELECT statement in the source text. y Input field on a screen:
- If you know a program that contains a screen with input fields for the table you are looking for, you can use F1 Technical Information and double-click on the technical name of the screen field to navigate to the ABAP Dictionary. This is frequently a structure field. Double-click to navigate to the data element. You can then use the Where-Used-List to search for transparent tables with the field type.
©SAP AG 2006
specific columns
single/multiple lines
SELECT
<fields>FROM
<table>INTO
<target>WHERE
<condition> .Which columns ? Which table ? Where ? Which lines ?
Read Database Access
You program read database accesses with the open SQL statement SELECT. The SELECT statement is comprised of a number of clauses with different tasks:
y The SELECT clause describes amongst other things whether the selection result should cover several lines or an individual data record, and which fields and tables should be read. y The FROM clause names the source (database table or view) from which the data is to be
selected.
y The INTO clause determines the internal data objects into which the selected data is to be placed.
y The WHERE clause gives the conditions that the selection result must fulfill. It therefore determines the lines in the table that are to be selected.