You are on page 1of 444

TAW10 Introduction to the ABAP Workbench (1/2)

TAW10 1/2
ABAP Workbench Fundamentals
AG 2003 SAP SAP AG

n n n n

R/3 System Release 4.6D or above 2003/Q2 Material number 5006 0990

SAP AG

TAW10

0-1

Copyright

Copyright 2003 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. All rights reserved.

SAP AG 2003

Comments on trademarks: n Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. n Microsoft, WINDOWS, NT, EXCEL, Word, PowerPoint and SQL Server are registered trademarks of Microsoft Corporation. n 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, Informix and Informix Dynamic ServerTM are trademarks of IBM Corporation in USA and/or other countries. n ORACLE is a registered trademark of ORACLE Corporation. n UNIX, X/Open, OSF/1 and Motif are registered trademarks of the Open Group. n Citrix, the Citrix logo, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, MultiWin and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc. n HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology. n JAVA is a registered trademark of Sun Microsystems, Inc. n JAVASCRIPT is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
n MarketSet and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One.

SAP, R/, mySAP, mySAP.com, xApps, xApp, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies.

SAP AG

TAW10

0-2

Development Consultant mySAP Technology ABAP Workbench

TAW10

10 days

TAW12

15 days

mySAP Technology ABAP Workbench Fundamentals

mySAP Technology - ABAP Workbench Concepts

Development consultant certification mySAP Technology ABAP Workbench

SAP AG 2003

SAP AG

TAW10

0-3

Course Prerequisites

Required

l Solid EDP basic knowledge l Good programming experience in a different programming language

SAP AG 2003

SAP AG

TAW10

0-4

Target group Target group

l Development consultants and developers who are responsible for adapting and developing ABAP/ABAP Objects programs

Duration
l 10 days

SAP AG 2003

SAP AG

TAW10

0-5

Course Goals

At the end of this course, you will be able to:


l Work with the ABAP Workbench tools l Write your own simple ABAP programs l Program object-oriented ABAP Objects

SAP AG 2003

SAP AG

TAW10

0-6

Course Content: mySAP Technology ABAP Workbench Fundamentals

Preface Complex Complex Complex mySAP.com Technologies ABAP Workbench Fundamentals ABAP Objects Case Study

SAP AG 2003

n n

This SAP Consultant Education training course contains different individual courses (sections), each of which deals with a separate topic Each individual course (section) is divided into different units.

SAP AG

TAW10

0-7

Course Content: mySAP Technology ABAP Workbench Concepts

Preface Complex Complex Complex ABAP Dictionary Techniques of List Processing Programming User Dialogs Complex Complex Complex Programming Database Updates Solution Manager Enhancements and Modifications Case Study

SAP AG 2003

n n

This SAP Consultant Education training course contains different individual courses (sections), each of which deals with a separate topic Each individual course (section) is divided into different units.

SAP AG

TAW10

0-8

Complex: mySAP.com Technologies

SAP AG 2003

SAP AG

TAW10

1-1

Course Content: mySAP.com Technologies

Unit Unit Unit Unit

mySAP.com Navigation Technical Structure of an SAP System Cross-System Concepts

SAP AG 2003

SAP AG

TAW10

1-2

mySAP.com

Contents:
l System Overview l Internet Technologies l Interfaces l SAP Service Marketplace

SAP AG 2003

SAP AG

TAW10

2-1

mySAP.com (1)

System System Overview Overview Internet Internet Technologies Technologies Interfaces Interfaces SAP SAP Service Service Marketplace

SAP AG 2003

SAP AG

TAW10

2-2

Possibilities Offered by mySAP.com


Only a fraction of the integration possibilities is shown here...

R/3

The Internet, or 'the rest of the world' Other software New business partner
R/3: FI/CO BW R/3: HR CRM Legacy software R/3: SD

Marketplace

Laptop or PDA (handheld) Field staff

Only browser required Customer


TM

R/3 APO

Other software Business partner

Your company

SAP AG 2003

mySAP.com provides the option of mapping internal business processes with employees and external business processes for partners, customers or suppliers using the Internet.

SAP AG

TAW10

2-3

SAP R/3 (Enterprise)


SAP GUI for HTML

browser browser Classic users

SAP R/3 (Enterprise)

SAP SAP GUI GUI ESS Middleware components


(such as SAP ITS)

browser browser

ESS = Employee Self-Service


SAP AG 2003

n n

SAP R/3 Enterprise provides a wide range of core business functions (as did its precursor, SAP R/3), including Financial Accounting and Human Resources Management. SAP R/3 Enterprise, which excellently complements all SAP solutions, can be used as an ERP backend system.

SAP AG

TAW10

2-4

mySAP CRM
e.g. Internet selling

browser browser

Mobile Services

Middleware components

CRM System

ERP Backend

Laptop

Call Center

SAP SAP GUI GUI


SAP AG 2003

n n

Many companies now attach growing importance to generating and maintaining customer loyalty. This is why it is necessary to manage customer information efficiently. mySAP Customer Relationship Management (mySAP CRM) not only enables you to do this, it also enables you to optimize your customer relationships as a whole and throughout the life cycle from customer acquisition through sales processes and order fulfillment to customer service.

SAP AG

TAW10

2-5

mySAP E-Procurement

Catalog

Employees within your company

...
Middleware EBP System ERP Backend

SAP SAP GUI GUI

... Internet Marketplace


Not necessarily required

SAP AG 2003

mySAP E-Procurement supports business-to-business procurement of both production materials and indirect materials (pencils, paper, etc.). You can make purchases on e-marketplaces, use electronic bid invitations or search for the best offers on the World Wide Web.

SAP AG

TAW10

2-6

mySAP BI
BW System
ERP Backend

Manager

... GUI GUI

SEM System

ERP Backend

Not necessarily required


SAP AG 2003

The mySAP Business Intelligence solution provides you with a variety of options for extracting, evaluating, storing and disseminating the data in your systems so you can make business or strategic decisions. mySAP BI components: - SAP Business Information Warehouse (SAP BW) - SAP Strategic Enterprise Management (SAP SEM)

SAP AG

TAW10

2-7

mySAP SCM
Manager (person responsible)
BW System ERP Backend

GUI GUI (Excel-based (Excel-based for for example) example)

Manager (planner)
APO System

Other ERP Backend

SAP SAP GUI GUI


SAP AG 2003

mySAP Supply Chain Management (mySAP SCM) gives you the tools you need to manage your entire logistics chain, so you can control all intracompany and intercompany processes, from mapping the logistics chain to sourcing, and from requirements planning to sales. The Internet-enabled functions in mySAP Supply Chain Management allow you to control the logistics chain even beyond your company boundaries. This enables you to collaborate with your partners and customers, exchanging important information and reacting swiftly as the need arises. One of the central modules of mySAP SCM is the Advanced Planner & Optimizer (APO). APO includes the following components: Supply Chain Cockpit, Demand Planning, Supply Network Planning and Deployment, Production Planning and Detailed Scheduling and Global Available-toPromise. By combining APO with the Business Information Warehouse, SAP customers can optimize performance and costs along the entire logistics chain.

SAP AG

TAW10

2-8

mySAP Enterprise Portal

ERP Backend

Employee

Portal

browser browser browser browser browser browser

Other ERP Backend

Browser Browser

Other sources of information or systems (such as the Internet)


SAP AG 2003

Possibilities offered by mySAP Enterprise Portal: - Simple, uniform access to different sources of information (single point of entry) - Easy access to different software components from various providers (for example, Baan, PeopleSoft, Oracle, and Siebel, alongside SAP) - Users need to log onto the portal once only to access all systems (Single Sign On) - Role-based access to functions - The portal can be personalized by adjusting it to personal needs - Secure access from anywhere mySAP Enterprise Portal can be used as an employee, customer and/or supplier portal, amongst others.

SAP AG

TAW10

2-9

mySAP.com (2)

System System Overview Overview Internet Technologies Internet Technologies Technologies Interfaces Interfaces SAP SAP Service Service Marketplace

SAP AG 2003

SAP AG

TAW10

2-10

SAP ITS, SAP Web AS: HTTP Communication


HTTP request
HTTP

Web server
HTTP

SAP ITS
RFC/ DIAG SAP Application Server previously "SAP Basis") SAP Web Application Server optional RFC Various SAP systems

SAP AG 2003

There are basically two ways of accessing an SAP component in dialog mode from the Internet: - Using the SAP Internet Transaction Server (SAP ITS) - Using the Internet Communication Manager (ICM) of the SAP Web Application Server (SAP Web AS)

SAP AG

TAW10

2-11

The SAP Internet Transaction Server


SAP ITS

Service files

Common host
Web browser HTTP Web server DIAG RFC SAP System

CGI* HTML page

WGate

TCP/IP AGate

CSS files

HTMLBusiness Templates Flow files

SAP AG 2003

* NSAPI and ISAPI are also supported

The SAP ITS provides the following options: - Automatic conversion of SAP screens into HTML format - Use of screen-based IACs (Internet Application Components) that have been delivered with the R/3 System for years (the online store, for example) - Use of the SAP GUI for HTML, a 1:1 conversion of SAP screens into HTML

SAP AG

TAW10

2-12

The SAP Web Application Server


SAP Application Server, up to (incl.) Rel. 4.6D SAP Web Application Server as of Rel. 6.10

Dispatcher WP WP WP WP

Dispatcher Dispatcher WP WP
Memory pipes

ICM

DB
SAP AG 2003

DB

n n n n

The SAP Web AS is a further development of the classic SAP Basis technology. A new process has been added to the SAP kernel, the Internet Communication Manager (ICM). The ICM enables you to process directly queries that were placed from the Internet/Intranet via a browser. The Web browser and ICM communicate using Business Server Pages; these are HTML pages that also contain ABAP coding, for example, so that the HTML page can be filled with data at runtime. The SAP GUI for HTML cannot currently be used with the ICM (-> SAP ITS)

SAP AG

TAW10

2-13

mySAP.com (3)

System System Overview Overview Internet Internet Technologies Technologies Interfaces Interfaces SAP SAP Service Service Marketplace

SAP AG 2003

SAP AG

TAW10

2-14

Interfaces Technologies Used in SAP Systems

SMTP SMTP
II D E ED
BAPI BAPI OLE OLE RFC RFC CPI-C CPI-C

P H HTT

A AL LE

Open Interfaces Interfaces


TCP/IP TCP/IP
SAP AG 2003

LU6.2 LU6.2

Open Interfaces

n n

mySAP.com is an open system. It supports a variety of network communication protocols. Information can be exchanged between component systems and non-SAP systems. SAP supports the TCP/IP (Transmission Control Protocol/Internet Protocol) and SNA LU6.2 (System Network Architecture; Logical Unit 6.2) protocols. Communication in mySAP.com takes place using the standard TCP/IP protocol. LU6.2 was developed by IBM and is used to communicate with mainframe-based R/2 Systems. R/3 application programming supports CPI-C (Common Programming Interface Communication), RFC (Remote Function Call) and OLE Automation (Object Linking and Embedding) as communication interfaces. Other interfaces are based on this technology, such as communication via BAPIs (Business Application Programming Interfaces), EDI (Electronic Data Interchange) or an ALE (Application Link Enabling) distribution model. It is also possible to send and receive mails using SMTP (Simple Mail Transfer Protocol).

SAP AG

TAW10

2-15

Business Process Distribution Using ALE

Distributed business processes


n n

n n n n n

Plant maintenance Inventory management Internal sales, shipping and billing Local purchasing PP

Accounting Central Controlling n Information systems: n Inventory n Purchasing n Sales n Central purchasing n Reference system for master data and tax data

Sales, shipping and billing n Purchasing of trading goods n Inventory management n Local Controlling

SAP AG 2003

ALE is the business-controlled message exchange - Through synchronous and asynchronous communication - Using BAPI interfaces and IDoc data containers - Using consistent data (the applications do not use a central database, but are filled independently by regional databases with their own database) - Across loosely linked SAP applications.

SAP AG

TAW10

2-16

RFC Connection Options


SAP system
(SAP R/2 also possible)

External system

ABAP program RFC interface

External program RFC interface

SAP system

RFC interface ABAP program

SAP AG 2003

Remote Function Call (RFC) is a communications interface that is based on CPI-C, but which has more functions and is easer for application programmers to use. You can use R/3 and R/2 Systems as well as external applications as RFC communication partners. See also SAP Notes 13903 and 116051. RFC is the protocol for calling special subroutines over the network. These subroutines are labeled function modules. Function modules are comparable with C functions or PASCAL procedures. They have a defined interface via which data, tables and return codes can be exchanged. Function modules are managed in the R/3 System in their own function library, called the Function Builder.

SAP AG

TAW10

2-17

Remote Function Call in Detail


Calling system
RFC DESTINATION R/2 R/3 DEST

System called

...

... CALL FUNCTION XY DESTINATION DEST EXPORTING... IMPORTING... ... RFC interface

FUNCTION XY. . . . ENDFUNCTION. RFC interface interface RFC

SAP AG 2003

n n

Function modules remote calls across system borders are only different to local remote calls in that a special parameter (Destination) specifies the destination host on which the program is to be executed. There are three types of RFC call: - Synchronous RFC call: the calling program stops until the function module has been processed in the destination system and any results have been returned to the caller. Only then does the calling program continue processing. - Asynchronous RFC call: the calling program runs parallel to and independently of function module processing in the destination system. Programmers are responsible for handling result processing. In addition, the destination system must also be available at the time of the RFC call. - Transactional RFC call: several function modules can be grouped into one transaction. They are processed in the destination system within an LUW once only, and in the sequence in which they were called. In the case of an error, the calling system receives a confirmation that you can access using Transaction SM58. In the case of transactional RFC, the destination system does not have to be available at the time of the RFC call. In addition, you can configure the frequency and intervals of individual queries.

SAP AG

TAW10

2-18

mySAP.com (4)

System System Overview Overview Internet Internet Technologies Technologies Interfaces Interfaces SAP SAP Service Service Marketplace Marketplace

SAP AG 2003

SAP AG

TAW10

2-19

service.sap.com the SAP Service Marketplace


Current Output / messages? Notes database

?? ?

Problem messages

Corrections

Training course information

Service requirements
SAP AG 2003

SAP Software Change Registration

n n n

The SAP Service Marketplace under http://service.sap.com is aimed at SAP customers and partners (unlike http://www.sap.com, which provides information on all SAP solutions and on SAP as a company for everyone). At the SAP Service Marketplace you can access various services, special information and additional offers. You must be registered as a user to use the SAP Service Marketplace. There is normally a contact person in each company who creates users for employees as required and sets authorizations. Access to the SAP Service Marketplace is free of charge (apart from the necessary Internet access).

SAP AG

TAW10

2-20

mySAP.com: Unit Summary

You are now able to l Name some of the advantages that your company gains by using mySAP.com e-business solutions. l Describe where SAP ITS and SAP Web AS can be used and how they work l Name various interface technologies used by SAP systems l Use the SAP Service Marketplace

SAP AG 2003

SAP AG

TAW10

2-21

Navigation

Contents:
l Logon and Screen Design l User Guide l Getting Help l User Settings

SAP AG 2003

SAP AG

TAW10

3-1

Navigation (1)

Logon Logon and and Screen Screen Design Design User User Guide Guide Getting Getting Help Help User User Settings Settings

SAP AG 2003

SAP AG

TAW10

3-2

The SAP Logon Program

SAP Logon 610


Language
DEV [SPACE]

SID
DEV

Group/Server
SPACE

Sys.No. Messageserver
00 twdf0670

Logon

Properties Groups...

Server...
New... Delete

SAP AG 2003

The SAP GUI program connects the front-end computer with a specific SAP System. Theoretically you can specify the SAP system required at command-line level when calling the SAP GUI program. In practice, you never need to do this. SAP provides another program for starting the SAP GUI: SAP Logon. When you call up the SAP Logon, it displays a list of SAP systems whose logon process can be started. This list is derived from a file on the front-end computer: saplogon.ini. This file is normally preconfigured centrally and made available to end users.

SAP AG

TAW10

3-3

The Logon Screen for an SAP System

Users

System

Help

SAP R/3
New password

client User Password

100 |

Language

DE

Please call your user administrator on Tel. 1972 if you have problems logging on

DEV (1) (100)

TWDF0670 OVR

SAP AG 2003

n n

SAP systems are client systems . You can use the client concept to control several separate enterprises in one system at the same time. The BW and KW components are exceptions since each uses one client only. Each user session only accesses data on the client that you selected when you logged on. A client is a self-contained organizational unit in the system. Each client has its own data environment and, therefore, its own user master and transaction data, assigned user master records and chart of accounts and specific Customizing parameters. So that you can log onto the system, you must have a user master record created for you for the corresponding client. For reasons of access protection, you must enter a password when you log onto the system. The system does not display the password that you enter (stars are displayed in place of the password). SAP systems are multilingual. You can use the Language field to select the logon language for the current session. Multiple logons are recorded as of Release 4.6. This is for reasons of both security and licensing. If the same user logs on more than once, then the system displays a warning message for each subsequent logon. You can add your own texts to the logon screen in different ways. For more information, see SAP Note 205487.

SAP AG

TAW10

3-4

SAP Easy Access

Menu

Edit

Favorites

Extras

System

Help

SAP Easy Access


Other menu Favorites SAP menu Office Information Systems tools Create role Assign users Documentation

DEV (1) (100)

TWDF0670

OVR

SAP AG 2003

n n

The SAP Easy Access screen is the standard way to access the system. You navigate within the system using a clearly arranged tree structure. You can attach an image such as your company logo to the right side of the screen. This image can be assigned throughout the system and is valid for all clients. Given that you have authorization to do so, you can find a detailed description of the settings that are required to do this by choosing Extras -> Administration information. Please note that the graphic is stored in the system and transported to the front-end every time SAP Easy Access is called. Although it is transported in compressed form, the graphic should not exceed 20 KB. You can also prevent the graphic from being called by choosing the setting Low Speed Connection in the SAP Logon program (see SAP Note 161053), or by choosing Extras --> Settings in the SAP Easy Access screen. See also "User Settings".

SAP AG

TAW10

3-5

Screen Elements
Users Edit Goto System Help

Maintaining your user profile

User Last changed by

Command field ESCH


ESCH

Menu bar Standard toolbar Title bar Application toolbar


Status

05.07.2001 15 : 46 : 37

Saved

Address StartMenu Logon language

Defaults

Parameter s

Tab page Input fields Checkboxes Radio buttons

Output Controller OutputDevice

Decimal notation
1.234.567,89 1,234,567.89 1 234 567,89

Output immediately Delete after output Personal time zone


CET

Date format
DD.MM.YYYY MM/DD/YYYY MM-DD-YYYY YYYY.MM.DD YYYY/MM/DD YYYY-MM-DD

CATT Test status

Status bar
DEV (1) (100) TWDF0670 OVR

SAP AG 2003

n n

n n n n n

Command field: you can start applications directly by entering their transaction code in the command field (this is hidden by default). You can find the transaction code for an application either in the SAP Easy Access menu tree (see "User Settings") or in the application itself under System -> Status. Menu bar: the menus shown here depend on which application you are in. These menus may also contain cascading menus. Standard toolbar: the icons in the standard toolbar are shown on every R/3 screen. If they are not available in an application, the pushbuttons that you cannot use on that screen are deactivated. If you position the cursor over an icon for a short time, the system displays quick info text with the name or function of the icon. If appropriate, you also see the corresponding function key setting. The application toolbar shows the icons available in the application you are currently in. Title bar: the title bar names the function that is available in the application you are currently in. Checkboxes: checkboxes enable you to select several options from a group of fields at the same time. Radio buttons: radio buttons enable you to choose exactly one item from a selection. Tab: arranges several information screens to improve clarity. Status bar: the status bar displays information such as warnings and errors about the current system status.

SAP AG

TAW10

3-6

Navigation (2)

Logon Logon and and Screen Screen Design Design User Guide User Guide Guide Getting Getting Help Help User User Settings Settings

SAP AG 2003

SAP AG

TAW10

3-7

Favorites List and User Menu

Menu

Edit

Favorites

Extras

System

Help

SAP Easy Access


Other menu Favorites URL - SAP Service Marketplace SM50 - Process Overview SM04 - User List Role SAP_BC_BASIS_ADMIN System: Running Operation System Configuration Performance Analysis Problem Analysis Overview RZ20 - CCMS Monitoring Details Create role Assign users Documentation

Favorites list

Role-based menu

DEV (1) (100)

TWDF0670

OVR

SAP AG 2003

n n n n n

Role: a role describes a number of activities in the system that it makes sense to define. These represent the scope of functions that users typically require at their work station. Roles (formerly "activity groups") must be set up using the Profile Generator so that SAP system users can work with user-specific or work station-related menus . Roles are also used to assign users with authorization for the activitie s defined in menus. Predefined user roles from all application areas are included in the standard system as of Release 4.6. When users are assigned roles, they can choose between the standard SAP menu and their user menus. In addition to their roles, end users can also use Favorites to personalize their access to the system. You can create your own Favorites list of the transactions, reports, files and Web addresses that you frequently use. You can create edits using the Favorites menu or simply using the mouse to "drag & drop" URLs or links to files to your personal favorites list.

SAP AG

TAW10

3-8

Navigation Options

Menu

Edit

Favorites

Extras

System
Create session End session

SAP Easy Access Command field


Other menu Favorites URL - SAP Service Marketplace SM50 - Process Overview SM04 - User List Role SAP_BC_BASIS_ADMIN System: Running Operation System Configuration Performance Analysis Problem Analysis Overview
RZ20 - CCMS Monitoring

User profile Services Utilities List Services for object Object history Own spool requests Own jobs Short message Status... Log off

Details

Menu

SAP Easy Access and Favorites list


SAP AG 2003

You can call the following types of system functions: Using the mouse by selecting a - menu entry - Favorites - an SAP Easy Access entry - using the keyboard (ALT + the underlined letter of the menu option required) - by entering a transaction code in the command field: In SAP systems, each function (not each screen!) is assigned a transaction code. You can call the allocated transaction code from any system screen. For example, you can display the customer master data, enter "/n" and then enter the corresponding transaction code: "/nfd03". You can determine the transaction code by choosing Status in the System menu. Additional input options: - "/n" ends the current transaction. - "/i" deletes the current session - "/osm04" opens a new session and branches to the specified transaction (SM04).

SAP AG

TAW10

3-9

The System and Help Menus

Menu

Edit

Favorites

Extras

System Create session

Help
Application help SAP Library Glossary Create roleRelease Notes Assign users SAP Service Marketplace Feedback Settings... Documentation

SAP Easy Access


Other menu Favorites SAP menu Office Information Systems tools

End session User profile Services Utilities List Services for object Object history Own spool requests Own jobs Short message Status... Log off

DEV (1) (100)

TWDF0670

OVR

SAP AG 2003

You can find the following options amongst others in the System menu option: Create/end session: creates and ends a session. System administrators can use parameter rdisp/max_alt_modes to set the maximum number of sessions to a number between 2 and 6. User profile: contains user-specific settings. Choose Own data to use parameters IDs that fill specific fields in the system (such as the company code field) with default values. List: important list functions, such as searching by character string, saving to PC files, printing and so on. - Status: displays the most important user and system data - Logoff: ends the SAP R/3 session (with a request for confirmation) The menu option Help contains the following options, amongst others: - A context-sensitive Application Help - SAP Library call (see next page) - A Glossary

SAP AG

TAW10

3-10

Navigation (3)

Logon Logon and and Screen Screen Design Design User User Guide Guide Getting Getting Help Help User User Settings Settings

SAP AG 2003

SAP AG

TAW10

3-11

F1 Help
Output Controller OutputDevice

Output immediately Delete after output Personal time zone


CET

Technical information

CATT Test status

F1 help

Performance Assistant

Print parameter 2
Indicates whether spool requests are printed immediately. Select this field to print your spool requests immediately. lassen. Leave the field blank to retain spool requests in the spool system until they are released. To release these spool requests for printing, you can use System -> Services -> Output controller. SAP AG 2003

n n

You can choose the F1 key to display an explanation of fields, menus, functions and messages. The F1 help also displays technical information on the relevant field. This information includes, for example, the parameter ID that you need to set user-specific default values for input fields that are also linked to the parameter ID.

SAP AG

TAW10

3-12

F4 Help
Address StartMenu Logon language Output Controller OutputDevice Defaults

Language (2)38 Entries found Restrictions

Langu... Language AF Afrikaans Arabic Bulgarian Czech Danish German Greek English Spanish Estonian Finnish French Hebrew Croatian Hungarian Indonesian AR BG CS DA DE EL EN ES ET FI FR HE HR HU ID

F4 help

SAP AG 2003

You can use F4 to display possible input values. You can also call up the F4 help for a field using the button immediately to the right of the selected field.

SAP AG

TAW10

3-13

The SAP Library

SAP Library Hide Tree

Getting Started Area

Release Notes

IMG

Glossary

Search

Help on Help

Open All Previous

Close All Next Synchronize

SAP Library

SAP Library Getting Started SAP Web Application Server SAP Knowledge Management Help on Help Help on the Web Copyright

SAP Web Application Server, Release 6.10, June 2001 Copyright 2001 SAP AG. All rights reserved.

Local intranet

SAP AG 2003

SAP Systems provide extensive online help. You can call this help from every screen in the system. You can call up help by choosing the Help menu, or by choosing the appropriate icon (yellow question mark). You can also access the SAP Library easily and quickly from the SAP Service Marketplace. You can find the SAP Help Portal under Knowledge and Training. You can display the help in HTML format and also perform a very efficient full text search in the library. If the SAP Library has been installed, you can also call this option within your company. You can also access the Help Portal directly at http://help.sap.com.

SAP AG

TAW10

3-14

Navigation (4)

Logon Logon and and Screen Screen Design Design User User Guide Guide Getting Getting Help Help User Settings User Settings Settings

SAP AG 2003

SAP AG

TAW10

3-15

Two of the Many Personalization Options


Menu Edit Favorites Extras System Help Shift+F6 Ctrl+Shift+F10 Shift+F9 Create role Shift+F7 Options ... New Visual Design ... Assign users Documentation Clipboard Generate graphic Create shortcut ... Activate GuiXT Default size Hardcopy Quick Cut and Paste Spelling Check Sapgui Help

Display documentation

SAP Easy Access


Other menu Favorites SAP menu Office Information Systems tools

Technical details Settings Set start transaction

Settings
This is used to specify settings Display favorites at end of list Do not display menu, only display favorites Do not display picture Display technical names

About ...

A range of settings simplifies working with the system


DEV (1) (100) TWDF0670 OVR

SAP AG 2003

Choose Extras ->Settings to change the appearance of the initial screen, for example, by turning off the graphics display on the right side of the screen, or by displaying technical names (transaction codes) on the SAP Easy Access screen. When you choose Options, you have the option of activating Quick Cut and Paste. Under Options... you have the option of setting the reaction speed of the quick info text that is displayed when you position the cursor over an icon or pushbutton. You can set personal standard values by choosing System -> User Profile -> Own Data . You can do this on the tab pages Address, Defaults, and Parameters.

SAP AG

TAW10

3-16

Navigation: Unit Summary

You are now able to l Log on to the system successfully l Name and use elements of a SAP GUI screen l Use F1 and F4 help l Display the information in the online documentation l Use the various options for personalizing the SAP system

SAP AG 2003

SAP AG

TAW10

3-17

Navigation - Exercises
Unit: Topic: Navigation Basic Functions

At the conclusion of these exercises, you will be able to: Log on to an SAP system Identify transaction codes Access SAP Library information Use the F1 help to find field information Use the F4 help to search for possible field values

As a new SAP system user, start to navigate in the system using menu paths and transaction codes, and use the various types of online help.

All menu paths in the exercises refer to the SAP standard menu. 1-1 Logging on the system Select the corresponding system for this training course. Enter the client, user name, initial password, and the logon language specified by the instructor. When logging on for the first time, a window appears in which you must enter a new password twice. Note the Client: _ _ _ User: _ _ _ _ _ _ _ _ Password: __________ Language: _ _. 1-2 What is the maximum number of parallel sessions (windows of the SAP system) can you open by choosing System Create session? Number: __ 1-3 What are the functions called that you access using the following SAP standard menu paths and what are the corresponding transaction codes? 1-3-1 Tools Administration Monitor System Monitoring User Overview Function name: ___________________________________________ Transaction: _________________________________________________

SAP AG

TAW10

3-18

1-3-2 Accounting Financial Accounting Accounts Receivable Master records Display

Select Customer 1000 in Company code 1000 to access the following screen.

Function name: ___________________________________________ Transaction: _________________________________________________ 1-4 Help 1-4-1 On the SAP Easy Access initial screen, if you choose Application Help ("Help" menu), you branch to which area of the SAP Library? _________________________________________________________

To answer the question below, you must call the transaction for displaying the customer master record. 1-4-2 Use the F1 help for the Customer field to answer the following question. What do you use the Customer field for?
Summarize the business-relevant information here. ______________________________________________________

1-4-3 Use the F1 help for the Company code field. To which business area of the SAP Library does the system branch when you choose the Application Help icon at the top edge of the F1 help window?
______________________________________________________

1-4-4 Which icon at the upper edge of the F1 help window can you use to find the parameter ID for the Company code field?
______________________________________________________

SAP AG

TAW10

3-19

1-4-5 Use the F4 help for the Customer field to find the number of customer "Becker ##". To do this, call the F4 help and use the search term "Becker*". Hint: ## is your group number.
___________________________________________________

SAP AG

TAW10

3-20

Unit: Topic:

Navigation User-Specific Settings

At the conclusion of these exercises, you will be able to: Fill a field with default parameters Make various user-specific settings Maintain your favorites list Define a user-specific start transaction

Start to define various user-specific settings.

Optional exercises are marked with an asterisk (*). 2-1 Define user parameters. 2-1-1 Assign a default value to the Company code field for your user. Hint: Your instructor will specify the Company code value (such as "1000"). You can find a hint on default values in the notes on the "User Settings" page. Parameter: ___ ___ ___ Parameter value: ___ ___ ___ ___ 2-2 Define user-specific settings by choosing System --> User Profile --> Own Data. 2-2-1 Set your Logon Language to the language that you are using in the training course. 2-2-2 Define the Decimal Notation and the Date Format you require.

SAP AG

TAW10

3-21

2-3

Maintain favorites 2-3-1 Create at least one new folder below the favorites folder. 2-3-2 Add two of your favorite transactions to this folder. 2-3-3 Add the Internet address http://www.sap.com below the title SAP Homepage.

2-4*

Define a start transaction in the "Extras" menu. 2-4-1 Set a transaction as the start transaction. You must now log off and on again so that the system can update the changes. Hint: You can also reset the start transaction to the standard value simply by deleting your entry.

SAP AG

TAW10

3-22

Solutions
Unit: Topic:
1-1 1-2

Navigation Basic Functions

Log on to the system indicated by the instructor and change your password. To create and end sessions, choose System Create session (or choose the corresponding icon) and System End session. Depending on the system setting, up to six sessions can be opened simultaneously during one user terminal session. You can find the transaction code under System Status. These screens and transaction codes correspond to the menu paths: 1-3-1 SM04 for User List 1-3-2 FD03 for Customer Display: General Data

1-3

1-4

Help 1-4-1 The Getting Started unit is displayed with information about using SAP Easy Access. 1-4-2 Suggestion: The Customer field is used within an SAP system to identify a customer uniquely. 1-4-3 FI Accounts Receivable and Accounts Payable 1-4-4 Using the Technical Info icon you can find: Parameter ID: BUK 1-4-5 Customer## (## is your group number)

If you use the F4 help for the Customer field, a dialog box appears in which you can enter various search criteria. The different tabs on the dialog box contain different search criteria. Use the Search term search criteria and enter the following data: Criterion Name Search term Value Becker*

If you perform the search using the Enter key, a list of possible hits is displayed, from which you can select the corresponding value.

SAP AG

TAW10

3-23

Unit: Navigation Topic: User-Specific Settings

2-1

Define user parameters 2-1-1 To define default values for a field, you need the parameter ID of the field concerned. To find this, you must first select a transaction that contains this field. Position the cursor on the corresponding field (just click on it with the mouse). Choose F1 Technical Information Parameter ID to display the information you require. For the Company code field, the parameter is BUK. Now enter this parameter into your user settings (System User Profile Own Data) in the Parameter tab and assign it the value that will be valid for the object in future. Then save your data.

2-2

Define user-specific settings 2-2-1 To set the logon language, go to the user profile (System User Profile Own Data) and then choose the Defaults tab. Enter the logon language you require in Logon Language. 2-2-2 See 2-2-1

2-3

Maintain favorites 2-3-1 To place favorites in a folder, you must first create a folder (functional areas): Favorites Insert folder with a name of your choice. You can create as many folders as you like. You can move folders using the mouse to drag & drop them. 2-3-2 To create favorites, select specific applications (transactions) in the menu tree of the SAP standard menu that you require as favorites (those applications that you use daily). You can add entries to your favorites list by selecting the application and choosing Favorites Add. You can subsequently move favorites into folders by choosing Favorites Move favorites. You can also move favorites using the mouse to drag & drop them. 2-3-3 You create Internet addresses by choosing Favorites Add Web address or file.

SAP AG

TAW10

3-24

2-4

Define a start transaction 2-4-1 Extras Set start transaction Enter a transaction and then choose Enter. The system message in the status bar displays that this transaction will be the start transaction the next time you log on. Hint: To reset this action, you must choose the menu path again and delete the transaction code you entered. The next time you log on to the system, the initial SAP Easy Access screen will be displayed again.

SAP AG

TAW10

3-25

Technical Structure of an SAP System

Contents:
l Data Structure l System Kernel

SAP AG 2003

SAP AG

TAW10

4-1

Technical Structure of an SAP System (1)

Data Data Structure Structure System System Kernel Kernel

SAP AG 2003

SAP AG

TAW10

4-2

mySAP.com System Data Structure

Client 100
(Authorizations, Master Record...)

Client 200
(Authorizations, Master Records...)
4-3

Application Data User


(Orders, Invoices,...)

Application Data User


(Orders, Invoices,...)

Client-Specific Customizing
(Company Codes, Plants, Stores, ...)

Client-Specific Customizing

...

(Company Codes, Plants, Stores, ...)

Cross-Client Customizing

Repository Objects
(For example: Table Definitions, Programs, Transactions, Function Modules) Customer
Developments Basis FI CO HR PP MM SD ...

Development Classes
SAP AG 2001

n n

n n

mySAP.com Systems contain different types of data. Some data can only be accessed from one client, such as business application data (documents, material masters, and so on), and most Customizing settings. Customizing is used to define a customers organizational structures, such as distribution channels, company codes, and so on, and to set customer-specific parameters for SAP transactions. The client-specific data is closely related. At input, application data is checked against the Customizing settings in the client. If inconsistencies are found, the input is rejected. This is why application data usually makes sense only in its own Customizing environment. In addition to the client-specific Customizing settings, there are other settings that are set once and are active for all clients. These cross-client Customizing settings include printer settings, for example. The Repository is also client-independent. It contains all ABAP Dictionary objects (tables, data elements, and domains) as well as all ABAP programs, menus, screens, and so on. Because they are cross-client, Repository objects developed in one client are the same in all other clients in the same system.

SAP AG

TAW10

Customizing
ASAP Roadmap
View: View : Change Company Company Code
New entries

CoCd.

Company name

Customizing
Customizing

. . . . Customizing

SAP AG 1999

n n

In addition to the various data types in the SAP R/3 System, there are also different types of changes and adaptations in the SAP R/3 System, and in other mySAP.com component systems. As the SAP R/3 System is standard software, it must be adapted to the individual needs of each company that uses it. This tailoring process is called Customizing, which includes the client-specific and cross-client data shown in the slide. A small amount of Customizing may also be required after an SAP R/3 System upgrade. Customizing is not developed and tested in the same client in which it will be in production. This means that several clients are required during an SAP R/3 implementation. Customizing is executed and tested in one client. In a large installation, it may make sense to combine and test Customizing subprojects in another client. Production occurs in its own client.

SAP AG

TAW10

4-4

Changes to Repository Objects


DEV
. . .

SAP Namespace

Customer Namespace Repository


QAS

PRD

Modifications
SAP AG 1999

Extension

Customer Development

In contrast to Customizing, the Repository does not necessarily need to be changed or enhanced for a mySAP.com System implementation: Customers can add their own developments to the Repository. In addition, customers can add what are called customer enhancements, which are customer objects added to existing objects in the SAP standard system. Customers add their enhancements using Customer Exits. Modifications change SAP objects, such as reports and table definitions. The Repository delivered from SAP is not only enhanced, but changed as well. This is why the modifications may need to be adjusted to a new Repository installed during the next SAP R/3 upgrade. This adjustment may take some time. n As Repository objects are cross-client, it is not possible to use a development system as a production environment. The danger of creating data inconsistencies would be too great. n Therefore, if changes are to be made to the Repository, we recommend two, even better, three systems. The third SAP R/3 System can be used for testing and quality assurance. n All customer developments take place in the customer namespace. This means that all objects created by customers have names within a certain namespace, for example beginning with Y or Z for ABAP programs.

SAP AG

TAW10

4-5

Technical Structure of an SAP System (2)

Data Data Structure Structure System System Kernel Kernel

SAP AG 2003

SAP AG

TAW10

4-6

The System Kernel

Applications
Programming Interfaces Communication Interface

Screen Processor User Interface ABAP Dictionary

ABAP Interpreter

Runtime Environment

Operating System and Hardware Platform


SAP AG 1999

This unit introduces the central processes of mySAP.com Basis Technology. This includes an explanation of how a user request is sent to and processed by the application layer, and which process types are involved in processing the request. Data entered by the user is sent through the user interface (the SAP GUI) to the dispatcher, which coordinates further processing. The work processes use the same source code as the dispatcher and whose substructures such as the Screen Interpreter and the ABAP Interpreter are presented here. Another topic is data exchange with the database.

SAP AG

TAW10

4-7

Processing User Requests

Presentation

SAP GUI

SAP GUI

SAP GUI

SAP GUI

Communication

Application Dispatcher Buffer


Work Process Work Process Work Process

Database
SAP AG 1999

Database Processes

DB

The dispatcher is the central process of the application server. The dispatcher manages, in association with the operating system, the resources for the applications written in ABAP. The main tasks of the dispatcher include distributing transaction load to the work processes, connecting to the presentation level, and organizing communication. User input is received by the SAP presentation program SAPGUI, converted into its own format and then sent to the dispatcher. The processing requests are then saved by the dispatcher in request queues and processed according to a first in-first-out principle. The dispatcher distributes the requests one after the other to available work processes. Data is actually processed in the work process, although the user, who creates the request using the SAP GUI, is not always assigned the same work process. There is no fixed assignment of work processes to users. Once the data has been processed, the processing result from the work process is sent via the dispatcher back to the SAP GUI. The SAP GUI interprets the received data and generates the output screen for the user with the help of the operating system on the front end computer. During initialization of the mySAP.com component system, the dispatcher executes the following actions among others: It reads the system profile parameters, starts work processes, and logs on to the message server (this service will be explained later).

SAP AG

TAW10

4-8

SAP GUI Types

SAP GUI for Windows

Windows 32 Bit

SAP GUI for Java

Java Application

Browser-Based

SAP GUI for HTML

SAP AG 1999

n n

The presentation interface SAPGUI (GUI = Graphical User Interface ) implements the platformspecific input and output functions of an SAP business application. The SAP GUI is primarily based on the Windows Style Guide and is available for several platforms providing the same functions for each. If you have learned to use the SAP GUI on one platform, with the exception of a few small platform-specific GUI attributes, you can use the system on another platform exactly the same as before. The presentation software implements the graphical user interface using the functions provided by the relevant presentation environment. As of SAP R/3 Release 4.6B you have a choice between the classic SAP GUI and a number of alternative access possibilities: SAP GUI for HTML SAP GUI for Java

SAP AG

TAW10

4-9

Presentation Layer

Presentation
Windows PC Terminal Client Windows PC and Browser for SAP GUI for HTML

Workstation/PC

Java Environment SAP GUI

SAP GUI Process

Terminal Server

SAP GUI Process

LAN / WAN Network

Application
Dispatcher
SAP AG 1999

The data flow between the presentation level and the application level when using the SAP GUI for Windows consists not of prepared images, but of compact, logical information about control elements and user entries (DIAG Protocol). The amount of data that must be transferred for each screen change when using the SAP GUI for Windows is typically several kB. You can also connect application servers over Wide Area Networks (WANs). For more information, see SAP Note 161053. An Internet Transaction Server is used for the SAP GUI for HTML to turn the SAP GUI data flow from the dispatcher into HTML, and conversely. In this case, an HTML data flow is exchanged between the WGate of the ITS (see the Communications and Integrations Technology unit) and the Frontend. The primary advantage of the SAP GUI for HTML is the low installation cost for the Frontend; all you need is a browser. SAP GUI for Java receives the Standard DIAG Protocol (from the dispatcher) and places this on the Frontend in HTML or, if in use by Java Plug-Ins, in a graphical format, which can, for example, be displayed in a browser. In this case the installation costs for the Frontend are equally minimal. For more information, see SAP Note 146505. For information about implementation of the SAP GUI on a Windows Terminal Client, see SAP Note 138869.

SAP AG

TAW10

4-10

SAP Basis Database Layer


Application Server Database Server

ABAP Interpreter
SELECT * FROM ...

DB Interface

Data

Local Buffer

Database

OPEN SQL Data

Native SQL DB Data

EXEC SQL. SELECT ... END EXEC.

Native Native SQL SQL DB Data

SAP AG 1999

Relational Database Management Systems (RDBMS) are generally used to manage large sets of data. An RDBMS saves data and relationships between data in the form of two-dimensional tables. These are known for their logical simplicity. The data, tables, and table relationships are defined in the database catalog (the data dictionary) of the database system. Within the ABAP programming language, you can use SAP OPEN SQL to access data in the database regardless of your database management system. The mySAP.com database interface converts Open SQL statements from ABAP statements into corresponding database statements. This means that the application programs that are written in ABAP do not depend on the database used. Furthermore, Native SQL commands can be used directly in ABAP. When interpreting Open SQL statements, the SAP database interface checks the syntax of these statements and ensures the optimal utilization of the local SAP buffers in the shared memory of the application server. Data that is frequently required by the applications is stored in these buffers so that the system does not have to access the database to read this data. In particular, all technical data, such as ABAP programs, screens, and ABAP Dictionary information, as well as a number of business administration parameters, usually remain unchanged in a running system and are therefore ideally suited to buffering. The same is true of business application data, which is almost exclusively accessed as read-only and can therefore be buffered.

SAP AG

TAW10

4-11

mySAP.com Processes

Message Server V2 Dialog D Update V1


Disp. Disp. Disp.

MS
Disp.

Background
11 10 9 8 7 6 5

SAP Dispatcher
Spool S

Lock Administration E Gateway Server

12

1 2 3 4

R/2

GW

R/3

SAP AG 1999

The operating system views the SAP runtime system as a group of parallel, cooperating processes. On each application server these processes include the dispatcher as well as work processes; the number of work processes depends on the available resources. Special work processes may be installed for dialog processing, update, background processing and spooling. In addition to these work process types (dialog processing (D), update (V: for the German "Verbuchung"), lock management (E), background processing (B), spool (S), the runtime system provides two additional services for internal and external communication (below are the restrictions on the number of work processes): The message server (MS or M) communicates between the distributed dispatchers within a mySAP.com System and is therefore the prerequisite for scalability using several parallelprocessing application servers. The gateway server (GW or G) allows communication between mySAP.com components such as SAP R/3 and SAP R/2 and external application systems. There is only one gateway process for each dispatcher process. Dialog: Every dispatcher requires at least two dialog work processes Spool: At least one for each mySAP.com System (more than one allowed for each dispatcher) Update: At least one for each mySAP.com System (more than one allowed for each dispatcher) Background processing: At least two for each mySAP.com System (more than one allowed for each dispatcher) Enqueue: Only one enqueue work process is needed for each system

SAP AG

TAW10

4-12

The Instance Concept

Instance (a)

Instance (b)

Dispatcher D-WP B-WP

Dispatcher D-WP D-WP

...

...

"Central" Instance (c)

Dispatcher

MS
...
SAP AG 1999

D-WP

V-WP

E-WP

B-WP

S-WP

n n n

n n

An instance is an administrative unit that combines mySAP.com system components providing one or more services. The services offered by an instance are started or stopped together. You use a common instance profile to set parameters for all of the components of an instance. A central mySAP.com System consists of a single instance that provides all of the necessary services. Each instance has its own SAP buffer areas. The example illustrates how a background processing server (a) and dialog server (b) are set up. These instances, which provide specific services, generally run on separate servers, but can also run on the same server, if needed. The message server provides the application servers with a central message service for internal communication (for example: trigger update, request and remove locks, or trigger background requests). The dispatchers for the individual application servers communicate through the message server that is installed once in each mySAP.com System (it is configured in the system profile files). Presentation servers can also log on to an application server through the message server. This means that you can use the message server performance database for automatic load distribution (logon load balancing).

SAP AG

TAW10

4-13

The Dialog Work Process

Frontend: SAP GUI

LAN / WAN Network

Request Queues Work Process 1


Internal Memory Screen Processor ABAP Processor Database Interface

Dispatcher

Work Process n

Task Handler

...
Roll In
Roll Area

Buffer Access Shared Memory

Rollout

SAP AG 1999

Application Buffer Factory Calendar Screens ABAP Programs Tables Dictionary Objects...

User Context

Roll File

The following components on the application level are involved in processing a dialog request: The dispatcher as central control process Work process queues (administered by the dispatcher) for incoming requests. One of the diaog work processes Buffers in shared memory and also possibly the roll file The task handler coordinates activity within a dialog work process. It activates the screen processor or the the ABAP processor (which control the screen flow logic and process ABAP statements, respectively) and executes the roll-in and roll-out of the user context. The memory management system differentiates between main memory areas that are available exclusively to a work process, and memory areas that can be used by all work processes. The memory space used exclusively by a work process stores session-specific data that must be kept longer than the duration of a work step. This data is automatically made available to the process at the start of a dialog step (rolled-in) and saved at the end of the dialog step (rolled-out). This data characterizes users (user context), such as their authorizations, administration information and additional data for the ABAP and dialog processor. It also contains data collected by the system in the preceding dialog steps in the running transaction (see slide Work Process Multiplexing and SAP Transactions). There are also additional memory areas for all processes in the shared memory for the factory calendar, screen, table, program, and other buffers.

SAP AG

TAW10

4-14

Long-Running ABAP Programs


Two Users Are Blocking Seven Dialog Work Processes with Long-Running Transactions

Dispatcher D-WP
1 1 12 1 10 2 9 3 8 4 76 5

D-WP
11 12 1 10 2 9 3 8 4 7 6 5

D-WP
11 12 1 10 2 9 3 8 4 7 6 5

D-WP
11 1 2 1 10 2 9 3 8 4 7 6 5

D-WP
11121 10 2 9 3 8 4 76 5

D-WP
1 1 12 1 10 2 9 3 8 4 76 5

D-WP
11 12 1 10 2 9 3 8 4 7 6 5

D-WP

Dialog Work Processes for Dialog Transactions


SAP AG 1999

Dialog work processes should not be loaded down with long-running dialog steps, as these work processes would then not be available to other users. The remaining dialog work processes would have to handle many more users, thus considerably increasing response times. This is the reason for the parameter rdisp/max_wprun_time (default setting: 300 seconds), which sets the maximum time a dialog step is allowed to remain in a dialog work process. If this time is exceeded by more than double, the dialog step is terminated and the started transaction terminates with an error. This allows the administrator to ensure that users execute long-running actions only in the background work processes, which are designed for these types of long-running actions.

SAP AG

TAW10

4-15

Background Processing

Dialog Server Dispatcher

Background Processing Server


3

Dispatcher D-WP

...

D-WP

...

B-WP

B-WP

B-WP

1
11 10 9 8 7 6 5

12

1 2 3 4

2
Background Scheduler (every 60 s)

Job

Job1

...

...

DB

XXX xxxx xxxx xxx XXX xxxx UUU uuuu uuuu uuu

xxx uuu

xx uu UU uuuu uuu u

Scheduling Table
SAP AG 1999

Background work processes are used for dialog-free execution of programs. They are used, for example, for periodic tasks such as reorganization or the automatic transfer of data from an external system to a mySAP.com component system. Background processing is scheduled in the form of jobs. Each job consists of one or more steps (ABAP reports, external programs or other operating system calls) that are processed sequentially. You can also set priorities (from "C" to "A") so that certain jobs are prioritized. Job processing is not generally triggered immediately (immediate start). Instead you specify a start date and time when you schedule the job. It may also be necessary to start jobs periodically, for example, system control jobs repeated on a fixed cycle. You can trigger a job start at the operating system level using the SAPEVT program. The background scheduler is responsible for automatically triggering the job at the specified time. The background scheduler is an ABAP program that regularly looks in the scheduling table for jobs to be executed and then ensures that they are executed (RDISP/BTCTIME, default 60 s).

SAP AG

TAW10

4-16

Printing in mySAP.com Systems


ABC XYZ

Triggering of print process, for example from SAP GUI: Printing a List

Spool Server

Operating System Spool


1B ... 41 42 43 .... 0D 0A

Dispatcher

D-WP

...

S-W P

Spool Request

ABC XYZ

Output Request

LAN/WAN Printer server


1B ... 41 42 43 .... 0D 0A

Database/File System

TemSe
SAP AG 1999

Operating System Spool

n n

n n n

Spooling refers to the buffered transfer of data to output devices such as printers, fax devices and so on. In distributed systems, networked administration is necessary for this output. The spool mechanism in mySAP.com Systems can supply output requests to printers and external spoolers both within a local network as well as over WANs. The spool mechanism works with the local spool system on each server. Spool requests are generated in dialog mode or during background processing and are then set in the spool database with details about the output device and the print format. The data itself is stored in the TEMporary Sequential(TemSe) object database. When data is to be printed, an output request is generated for a spool request. This output request is processed by a spool work process. Once the spool work process has formatted the data for output, it returns the output request to the operating system spool system. The operating system spooler takes over the queue management and ensures that the required data is passed on to the output device.

SAP AG

TAW10

4-17

Lock Administration in mySAP.com Systems

D-WP

E-WP

B-WP

D-WP

Change Access

At Most Read Access

DB
SAP AG 1999

XXX xxxx xxxx xxx UUU uuuu uuuu uuu

xxx uuu

xx uu

UU uuuu

uuu u

The lock mechanisms present in the current rela tional database systems are not generally sufficient to handle business data objects (such as sales orders) that may affect several tables in the database. To coordinate several applications simultaneously accessing the same business object, the mySAP.com System provides its own lock management, controlled by the enqueue work process. In order for the system to execute lock requests, you must first define a lock object in the ABAP Dictionary. The lock object contains tables whose entries are to be locked. You can also have additional secondary tables using foreign key relationships (the name of a user-defined lock object must begin with "EY" or "EZ"). You can specify the lock mode ("S": shared lock or "E": exclusive lock) for a lock object. An exclusive lock (mode "E") can only be set if no other user has set a lock ("E" or "S") on the data record. The same user can request additional "E" or "S" locks within a transaction. If a lock object is activated, the system generates an ENQUEUE and a DEQUEUE function module. These function modules have the names ENQUEUE_<object_name> and DEQUEUE_<object_name>, and are used in ABAP coding to lock and unlock data.

SAP AG

TAW10

4-18

Requesting a Lock from the Enqueue WP

Dialog Server

Enqueue Server

Dispatcher

Dispatcher

...

D-WP

...

E-WP

...
Lock table in main memory

Call function 'ENQUEUE_E...'

MS

SAP AG 1999

When a lock is requested, the system checks to determine whether the requested lock conflicts with any entries in the lock table. If there are conflicts, the lock request is rejected. The application program can then inform the user that the requested operation cannot currently be executed. The locks (enqueues) are administered by the enqueue work process using the lock table. The lock table is stored in the main memory of the server where the enqueue work process is running. In the example shown above, the dialog work process and the enqueue work processes are not located on the same application server, they communicate through the message server. Locks set by an application program are either reset by the application program itself, or using a special update program (second part of the SAP Logical Unit of Work). Locks, which are inherited in this way by an update work process, are also written to a file at operating system level. In transaction SM12, the locks held by the update program are colored blue, while the locks held in the dialog work process are colored black.

SAP AG

TAW10

4-19

Work Process Multiplexing and SAP Transactions

Dialog WP 0

PBO 100
Screen 100

PAI

PBO

PAI

PBO

Screen

Dialog WP 1

PAI PBO 100 105


Screen 105

User Chooses:

Save / Cancel
Screen 110

Dialog WP 2

PAI

PBO

PAI PBO 105 110

PAI 110

SAP AG 1999

Business transactions are processing units with related functions; these transactions execute consistent database changes meaningful for the business. Typical examples are credit and debit postings, which only make sense together, or creating an order and reserving the material concerned. Accordingly, an SAP transaction is implemented as a series of consistent, connected dialog steps. A user dialog step is represented by a screen (or a dynpro, which is a dynamic program = mask and flow logic). SAP transactions are not necessarily executed within one single dialog work process. In fact, the individual dialog steps of a transaction can be processed by various dialog work processes (work process multiplexing, which only exists for dialog work processes). Using asynchronous update, the dialog part of the transaction and the associated database update can also be run in different work process types or even on different servers. From the systems point of view, a dialog step begins with the processing of a piece of data entered by the user (Process after Input (PAI) and the preparation and sending of the next screen template (Process before Output (PBO); after this, the screen that has been filled out by the user is once again accepted, and in turn the input data contained in the received screen is analyzed and processed. System and user dialog steps are processed alternately. The two parts of the dialog step from the systems point of view are called PBO and PAI.

SAP AG

TAW10

4-20

Technical Structure of an SAP System: Summary

You are now able to l Describe the data structure of SAP systems l Name various types of SAP GUI l Represent the basic structure of a mySAP.com system l Explain the relationships between the processes on the different client/server layers in SAP Systems (for example, R/3)

SAP AG 2003

SAP AG

TAW10

4-21

Cross-System Concepts

Contents:
l Organizational units and master data l Transactions and documents l Workflow

SAP AG 2003

SAP AG

TAW10

5-1

Enterprise Structure: Terminology


SAP SAP
Enterprise

Client Company Code Plant


Sales Organization

Company

Subsidiary

Factory

Sales Organization Division Storage Locations

Department

Division

Business Area

Warehouses
SAP AG 2003

n n

The structure of an enterprise is mapped to SAP applications by organizational units. Organizational units summarize specific corporate functions. Organizational units can belong to a single application (a sales organization can belong to Sales and Distribution, for example) or they be assigned to several applications (a factory can be assigned to Materials Management and Production Planning, for example).

SAP AG

TAW10

5-2

Enterprise Structures: Tiers


SAP
Ides Holding

Client

Germany

U.S.A.

Company Code

Plant
Hamburg 1000 Berlin 1100 Dresden 1200

0001
SAP AG 2003

0002

0003

Storage Location

The client is the superior element of all organizational units. A client corresponds to a group with several subsidiaries. All company data in an R/3 installation are differentiated at least by client, but usually also by deeper organizational structures. Flexible organizational elements in the R/3 System mean you also have the option of mapping complex enterprise structures. Many organizational units are used to represent the legal and organizational structure of an enterprise from different points of view. The various enterprise areas are joined by linking the organizational units together and the structure of the total enterprise is represented in the R/3 System.

SAP AG

TAW10

5-3

Master Data: Customer Master


General Data Name Address Language... Financial Accounting Data Data Payment Parameters G/L Account Dunning. Sales Data Data

Client

Company Code

Customer Master Record

Sales/Shipping Billing Parameter Partner

Sales Area

Storage Location
SAP AG 2003

n n n

Master data are data records that remain in the database for a long period of time. Master data include customers, suppliers, materials, accounts and so on. Master data are created centrally (for all applications) . Master data have an organizational aspect. They are assigned to organizational units. A customer master record can be assigned to the following organizational units: company code, sales organization, distribution channel and division. Master data can be used for all modules. For example, customer master data have common data for accounting and sales.

SAP AG

TAW10

5-4

Master Data: Material Master


Material Number Short Text, Volume, Weight Basic Unit of Measure ... Delivering Plant Control Types Sales Unit ... Valuation Forecast Planning Parameters Purchasing Parameters ... Requirements Planning Parameters Inventory Management Physical Inventory ...
SAP AG 2003

Client

Sales Organization Distribution Channel

Material Master Record

Plant

Storage Location

n n

The material master is the central source for a company to display material-specific data. It is used by all components of the SAP logistics system. The data in the material master can be used by all areas such as purchasing, inventory management, materials planning, invoice verification and so on.

SAP AG

TAW10

5-5

Material Master: Database Conversion

MARA

MAKT

MARM

MVKE

MLAN

MEAN

MBEW

MARC

MLGN MLGT

MARD

MVER

MAPR

SAP AG 2003

The individual tables contain the following data: MARA General data MAKT Short texts MARM Conversion factors MVKE Sales data for each sales organization MLAN Sales data for each country MEAN EAN data MBEW Valuation data MARC Material data for each plant MLGN Material data for each LVS warehouse MLGT Material data for each LVS storage type MARD Material data for each storage location MVER Consumption data MAPR Forecast data (indicators)

SAP AG

TAW10

5-6

Transaction: Using Master Data and Organizational Units

Company Code
Sales Document Customer Master Record
Customer: 1000

Sales Organization

Item 10

Material Quantity HD-1300 P-103 1 2

Distribution Channel

Material Master Record

20

Division

SAP AG 2003

n n

When a customer order is created, the transport agreements, terms of delivery and payment and so on agreed with the business partner must be considered. So that you don't have to enter this information for each activity connected with the business partner, the data that are relevant for the activity are copied from the business partner's material master. The information stored in the material master record (price per unit of measure, stock per storage location and so on) are processed in the order entry. This principle applies to processing the data from any master record involved in the activity. The relevant organization units must be assigned when a transaction is executed. This ensures that the assignments to the company structure are retained in the document that is created, in addition to the information stored for the customer and the material. A document is created for each transaction that is executed in the R/3 System. The document that is created from a transaction implicitly contains all of the default features for the master data and organizational units.

SAP AG

TAW10

5-7

Message Type

Invoice

Invoice

Invoice

Immediately (creating orders)

On request (printing activity)

With next selection run or at a specified time (scheduling)

Messages
Message type

SAP AG 2003

Online (screen output)

Printer

Telefax

E-mail

EDI

Whenever you save a query, an order, an outline agreement, a inquiry confirmation, a delivery note and so on, an output format is created from the document concerned. This output format is a message (message type). The message is then placed in the message queue, from where it can be released for printing, output via EDI and so on as required. The message is released either manually or automatically using a message control program. You can use the various send media to output individual messages during processing, provided that the corresponding message types and send media were assigned in Customizing. For each document type, you can define when and how the messages are sent. The message control can be stored as a default value in the business partner's master record.

SAP AG

TAW10

5-8

SAP Business Workflow


Leave form created Employee Employee

Decision

Leave form processed

Dates not approved

Form changed

Form rejected

Decision Supervisor Supervisor

Decision

Dates approved

Dates approved

Workflow completed
SAP AG 2003

n n n

The SAP Business Workflow is a tool that you can use to optimize the flow of business transactions. It can execute consecutive work steps automatically, or coordinate the flow of information. Workflows control processes according to a predefined model and are particularly suitable for organizations that are structured and based on the principle of division of labor. Workflow brings the "right" work in the "right" sequence to the "right" persons at the "right" time. This can be done using an automated mail or a workflow item.

SAP AG

TAW10

5-9

System-Wide Concepts: Unit Summary

You are now able to l Name the main elements in a business scenario l Describe the link between the main elements in a business scenario

SAP AG 2003

SAP AG

TAW10

5-10

Complex: ABAP Workbench Fundamentals

SAP AG 2003

SAP AG

TAW10

6-1

Course Content: ABAP Workbench Fundamentals (1)

Unit Unit Unit Unit

ABAP Program Process Introduction to the ABAP Workbench Introduction to the ABAP Dictionary Basic ABAP Language Elements

Unit Unit

Data Retrieval Program-internal Modularization with Subroutines The ABAP Runtime System User Dialog List

Unit Unit

SAP AG 2003

SAP AG

TAW10

6-2

Course Contents: ABAP Workbench Fundamentals (2)

Unit Unit Unit Unit

User Dialog Selection Screen User Dialog Screen Global Modularization Calling Programs and Transferring Data

Appendi x

SAP AG 2003

SAP AG

TAW10

6-3

Main Business Scenario

Departure airport

Destination airport In this course, you will develop several programs designed to assist travel agencies. Some of their typical needs include:
l

Departure city

Determining flight connections on specific dates Processing bookings for specific flights l Evaluating additional flight information, such as l Price l Capacity
l

Destination city
SAP AG 2001

SAP AG

TAW10

6-4

Important Database Tables for the Flight Data Model


SCARR CARRID : CARRNAME: CURRCODE: Airline ID Airline name Local currency of airline

SPFLI

CARRID : CONNID: COUNTRYFR: CITYFROM: AIRPFROM: COUNTRYTO: CITYTO: AIRPTO: CARRID : CONNID: FLDATE: PRICE: CURRENCY: SEATSMAX: SEATSOCC:

Airline ID Flight connection ID Country key for departure city Departure city Departure airport Country key for arrival city Destination city Destination airport Airline ID Flight connection ID Flight date Price Currency Maximum number of seats on flight Current number of occupied seats on flight

SFLIGHT

SAP AG 2001

You will refer to this information as you do the exercises throughout this course.

SAP AG

TAW10

6-5

ABAP Program Process

Contents:
l System Architecture and ABAP Program l Example Program with Selection Screen and List

SAP AG 2003

SAP AG

TAW10

7-1

Program Flow of an ABAP Program: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the architecture of the R/3 System l Describe how to execute a simple dialog program using the ABAP runtime system

SAP AG 2001

SAP AG

TAW10

7-2

System Architecture and ABAP Program

System System Architecture Architecture and and ABAP ABAP Program Program Example Example Program Program with with Selection Selection Screen Screen and and List List

SAP AG 2003

SAP AG

TAW10

7-3

Client/Server Architecture

Presentation Server Layer

SAPGUI

SAPGUI

SAPGUI

SAPGUI

SAPGUI

SAPGUI

Dispatcher

Dispatcher

Application Server Layer

Work Process

Work Process

Work Process

Work Process

Database

Work Process

Work Process

Work Process

Work Process

SAP AG 2001

n n n

The R/3 System has a modular software architecture that follows software -oriented client/server principles. The R/3 System allocates the presentation, application logic, and data storage to different computers. This serves as the basis for the scalability of the R/3 System. The lowest level is the database level. Here data is managed with a relational database management system (RDBMS). In addition to application data, the database contains the programs and the metadata that the R/3 System requires for self-management. ABAP programs (both the applications provided by SAP and the ones you develop yourself) run at the application server level. The ABAP programs read data from the database level, process the data, and possibly store data there. The presentation server level contains the user interface through which each user can access the program, enter new data, and display the results of a work process. The technical distribution of software is independent of its physical location on the hardware. All levels can be installed vertically (on top of each other on one computer) or each level can be installed on a separate computer. The presentation and application servers can be divided horizontally among any number of computers. The horizontal distribution of database components, however, depends on the type of database installed.

n n

SAP AG

TAW10

7-4

Excerpt for an ABAP Program

Presentation Server Layer

Work Process

Application Server Layer

ABAP Program

Database

SAP AG 2001

n n

This graphic can be simplified for most topics discussed during this course. The interaction between a single user and a single ABAP program will be of primary interest to us during this course. The exact processes involved in user dispatching on an application server are secondary to understanding how to write an ABAP program. Therefore, we will work with a simplified graphic that does not explicitly show the dispatcher and the work process. Certain slides will, however, include these details whenever they are relevant to ABAP programming. ABAP programs are processed on the application server. The design of user dialogs and database dialogs is, therefore, of particular importance when writing application programs.

SAP AG

TAW10

7-5

View for the User

Presentation Server Layer

Screen

Selection Screen

List

Application Server Layer

Black Box

Database

SAP AG 2001

Most users are only interested in how a business transaction flows and how to enter data into and display data from a transaction. The technical aspects of programming are less interesting. The user does not need to know the precise flow of the ABAP program on the application server. To the average user, the SAP system is like a "black box." Technically speaking, there are three different types of screens: dynamic screens or dynpros, selection screens, and lists. Each type of screen provides different services. The developers task is to select for each user dialog exactly those types that are most suitable for the accomplishment of the tasks concerned. For this reason, developers should have precise knowledge of the technical aspects.

SAP AG

TAW10

7-6

Interaction Between Server Layers

Program Start

ABAP Program ABAP Processing Block

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

n n n

Once the user performs a user action (selecting Enter, a function key, a menu function or a pushbutton, for example), control is passed from the presentation server to the application server. Only certain parts of the ABAP program are processed. If a further user dialog is triggered from within the ABAP program, the system transmits the screen and passes control once again to the presentation server.

SAP AG

TAW10

7-7

Example Program with Selection Screen and List

System System Architecture Architecture and and ABAP ABAP Program Program Example Example Program Program with with Selection Selection Screen Screen and and List List

SAP AG 2003

SAP AG

TAW10

7-8

Program Start

Program Start

Repository

Database Table

SAP AG 2001

Time

Whenever a user logs on to the system, a screen is displayed. From this screen, the user can start an ABAP program via a menu path or by entering a transaction code.

SAP AG

TAW10

7-9

System Loads Program Context

Program Start

ABAP Program Selection Screen Data Objects

Repository

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

The system first loads the program context onto the application server. The program context contains memory areas for variables and complex data objects, information on the screens for user dialogs, and ABAP processing blocks. The runtime system gets the program information from the Repository, which is a special part of the database. The sample program has a selection screen as the user dialog, a variable and a structure as data objects, and one ABAP processing block. The list that is used to display the data is created dynamically at run time. The ABAP runtime system controls the subsequent program flow.

SAP AG

TAW10

7-10

Runtime System Sends Selection Screen

Program Start

ABAP Program

Repository

Data Objects

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

Because the program contains a selection screen, the ABAP runtime system sends it to the presentation server. The presentation server controls the program flow for as long as the user enters data in the input fields. Selection screens allow users to enter selection criteria required by the program.

SAP AG

TAW10

7-11

Input Values Are Inserted into Data Objects

Program Start

ABAP Program

Repository

Data Objects

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

n n n n

As soon as the user has finished entering data on the selection screen, he or she can trigger further processing of the program by selecting Execute. The entered data is automatically placed in its corresponding data objects in the program and the ABAP runtime system resumes control of processing. In our simple program example, there is only one ABAP processing block. The ABAP runtime system triggers sequential processing of this ABAP processing block. If the entries made by the user do not have the correct type, an error message is triggered automatically. The user must correct the entries.

SAP AG

TAW10

7-12

Program Requests Data Record from Database

Program Start

ABAP Program

Repository

Data Objects

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

Within the ABAP processing block, a read access to the database is programmed. The program passes to the database information about which database table to access and which line in the table to read.

SAP AG

TAW10

7-13

Database Returns Data Record to Program

Program Start

ABAP Program

Repository

Data Objects

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

n n

The database returns the requested data record to the program and the runtime system ensures that this data is stored in the appropriate data objects. If a single record is accessed, this data object is usually a structure that contains components for all the required database fields.

SAP AG

TAW10

7-14

Runtime System Sends List

Program Start

ABAP Program

Repository

Data Objects

Database Table
ABAP Processing Block

ABAP Runtime System


SAP AG 2001

Time

The layout of the subsequent list display was also programmed into the processing block. After completion, the runtime program sends this list as a screen to the presentation server.

SAP AG

TAW10

7-15

Program Flow of an ABAP Program: Unit Summary

You are now able to: l Describe in basic terms the architecture of the R/3 System l Describe in basic terms the execution of a simple dialog program using the ABAP runtime system

SAP AG 2001

SAP AG

TAW10

7-16

Introduction to the ABAP Workbench

Contents:
l Introduction to the R/3 Repository l Working with the Object Navigator l Organizing Developments l Developing an ABAP Program

SAP AG 2001

SAP AG

TAW10

8-1

Introduction to the ABAP Workbench: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the structure of the R/3 Repository and its search tools l Use the Object Navigator for your development work l Name and use the utilities for orderly software development l Create development classes, ABAP programs, and transaction codes

SAP AG 2001

SAP AG

TAW10

8-2

Introduction to the R/3 Repository

Introduction Introduction to to the the R/3 R/3 Repository Repository Working Working with with the the Object Object Navigator Navigator Organizing Organizing Developments Developments Developing Developing ABAP ABAP Programs Programs

SAP AG 2001

SAP AG

TAW10

8-3

The R/3 Repository

Presentation Server Layer

Application Server Layer

ABAP Program

Cross-client

Client-specific Customizing tables Application tables

Database

Repository

SAP AG 2001

n n n

The database contains application and Customizing tables that are usually client-specific . The database also contains the R/3 Repository. The ABAP Dictionary is part of the R/3 Repository. The R/3 Repository contains all the development objects, for example, programs, definitions of database tables, or central data type definitions. Development objects are therefore also known as Repository objects. Repository objects are never client-specific ; therefore, they can be viewed and used in all clients.

SAP AG

TAW10

8-4

Structure of the R/3 Repository

Repository Objects
FI HR MM

SD MM

WM MM MM Cust.

Development Classes
Function Modules Programs Tables ...
SAP AG 2001

n n n n

The R/3 Repository is subdivided according to application components. Each application component is further divided into logical subdivisions called development classes. Repository objects are often made up of sub-objects that are themselves Repository objects. When you create a Repository object, you must assign it to a development class.

SAP AG

TAW10

8-5

SAP Application Hierarchy


SAP

0 + 0 + 0 +

CA AC FI

+ 0 + 0 0 +

Cross-Application Components Accounting - General Financial Accounting ... FBAS Financial Accounting Basis ... FI-GL General Ledger Acctg 0 + 0 + FI-LC Consolidation ... TR Treasury CO Controlling ...

Application component Development class Selected subtree

Information System

SAP AG 2001

n n

The structure of the application components is shown in the application hierarchy. From the SAP Easy Access menu, you access the application hierarchy by choosing Tools ABAP Workbench Overview Application Hierarchy . The application components are displayed in a tree structure in the application hierarchy. Expanding a component displays all the development classes that are assigned to that component. You can select a subtree or branch and navigate from the application hierarchy to the R/3 Repository Information System. The system then collects all development classes for the branch selected and passes them to the Repository Information System.

SAP AG

TAW10

8-6

R/3 Repository Information System


Repository Information System Business engineering ABAP Dictionary Basic objects Database tables Views Data elements Structures Table types ... Other objects Fields Programming Function Builder Program Library Prog. environment Program sub-objects ABAP objects Class library Components of classes Components of interfaces Environment
SAP AG 2001

n n

You can use the Repository Information System to search for specific Repository objects. Suitable search criteria are available for the various Repository objects. Which objects are to be found using the Repository Information System depends on how you get there: From within the application hierachy, select the Information system (double-click the selected application component or development class). This filters the the respective Repository objects. From the SAP Easy Access menu, choose Tools ABAP Workbench Overview Information system. The system lists all the Repository Objects available for searching.

SAP AG

TAW10

8-7

Working With the Object Navigator

Introduction Introduction to to the the R/3 R/3 Repository Repository Working Working with with the the Object Object Navigator Navigator Organizing Organizing Developments Developments Developing Developing ABAP ABAP Programs Programs

SAP AG 2001

SAP AG

TAW10

8-8

ABAP Workbench Tools

Screen Painter Menu Painter


FI SD

Debugger
MM

HR

WM MM Cust.

Object Navigator ABAP Dictionary

ABAP Editor Function Builder

Class Builder

SAP AG 2001

n n n n n n n

The ABAP Workbench contains different tools for editing Repository objects. These tools can be used throughout the entire software development cycle. The most important tools for creating and editing Repository objects are as follows: The ABAP Editor for editing source text The ABAP Dictionary for processing database table definitions, central data types, and more The Screen Painter for configuring screens (screens with functions for user dialogs) Menu Painter for designing the user interface (menu bar, standard toolbar, application toolbar) (see Interfaces) The Function Builder for processing function modules The Class Builder for processing central classes You can start these tools in three ways: Directly from the Easy Access menu. Using the Object Navigator. This has a tree diagram of all objects within a development class or program. Double -click on an object to start the respective tool. By double-clicking from one tool to the next, and back again.

SAP AG

TAW10

8-9

Screen Structure in the Object Navigator


Full screen on/off Tool area

Navigation area Right-click

Context menu

Right-click

Context menu

Size of display area can be changed

SAP AG 2001

n n

The Object Navigator screen is divided into two areas: A navigation area for displaying an object list as a hierarchy tree A tool area for displaying and editing a development object using the correct tool You can display or hide the hierarchy area. You can select functions from a context menu in both screen areas. You are given a choice of only those functions that are provided for displaying or editing the object to which you are pointing. Right-click on the object to open the context menu.

SAP AG

TAW10

8-10

Working with the Navigation Area


Application Hierarchy Development Class Program Function Group Class / Interface Internet Service Local Objects Refresh object list

Development Class BC400 Use of navigation history Display higher-level object list

BC400

Favorites

Dictionary objects Programs SAPBC400WBD_GETTING_STA SAPBC400WBT_GETTING_STA Function groups BC400 Classes CL_BC400
SAP AG 2001

Double-click on a Repository object with subobjects: List of subobjects

n n n n n

The Repository objects are organized in a hierarchy: An application component can have different development classes. A development class can contain different Repository objects: programs, function groups, ABAP Dictionary objects, and so on. Each Repository object can have different subobjects assigned to it: - Subobjects belonging to a program: global data, types, events, subprograms, and so on - Subobjects belonging to a function group: global data, function modules, and so on You can enter the type of object list and the object name in the upper part of the navigation area. The object list is then displayed in the navigation area. To display the subobjects, double -click an object within the object list. If an object is not in an object list, you can display it by using the respective tool in the tool area. You can navigate between object lists either by either history or hierarchy. You can add object lists that you edit frequently to your favorites.

SAP AG

TAW10

8-11

Navigation in the Tool Area

Functions of the current tool

Show navigation window

Use of navigation history Hide navigation window

Navigation stack

SAP AG 2001

n n

In the tool area, you can display a window showing your navigation history, that is, a list of the objects you have displayed since you started the Object Navigator in the tool area. The object currently displayed in the tool area is highlighted in a different color.

SAP AG

TAW10

8-12

Synchronization of Navigation and Tool Areas

Display object list

Double-click on a Repository object without subobjects or choose context menu: Display/change in tool area Display Change ...

SAP AG 2001

n n

Navigation in the navigation area is logically independent from navigation in the tool area. This allows for screens to be used in a flexible manner. If you wish, you can synchronize the two areas: You can display an object in the tool area by double -clicking it, or by selecting the context menu from within the navigation area. The system automatically selects the appropriate tool for processing the object you selected. To display the object list that belongs to an object you are currently processing in the tool area, choose Display object list. To create objects from an object list, you can use the context menu for that object type. If there is no entry in the object list for the required object type, you can create any number of objects using Edit object or Other object.

SAP AG

TAW10

8-13

Organizing Developments

Introduction Introduction to to the the R/3 R/3 Repository Repository Working Working with with the the Object Object Navigator Navigator Organizing Organizing Developments Developments Developing Developing ABAP ABAP Programs Programs

SAP AG 2001

SAP AG

TAW10

8-14

Transporting Repository Objects

Change Request

FI SD

HR

MM FI WM HR MM

MM Cust.

SD MM

WM Cust.

Development System
SAP AG 2001

Production System

n n n n

Development projects are always implemented in a development system and then transported to the next system. Repository objects are automatically assigned to a transport route based on their belonging to a particular development class and on their actual function. A decisive criterion for combining the development projects is, therefore, which Repository objects need to be transported together because of their dependencies. You schedule the group transport of the Repository objects using a change request.

SAP AG

TAW10

8-15

Scheduling a Development Project


Schedule: Monday ... Friday Request is released Locking Objects for for NonNon-Project Members Members Project Manager: FRY Team: FRY BC400-00 BC400-01 BC400-02 BC400-03 ...

SAP AG 2001

n n n n

Scheduling a development project using a change request covers the following aspects: All employees in the project start their work on a defined date. Employees have the chance to follow up and check their activities separately. The respective Repository objects can be processed by all employees involved in the project. For those developers who do not belong to the team, the Repository objects remain locked until the project is completed. The group triggers the transport of all the respective Repository objects.

SAP AG

TAW10

8-16

Project Representation in the Workbench Organizer

Project Manager: FRY Team: FRY BC400-00 BC400-01 BC400-02 BC400-03 ... Workbench Organizer: Change Requests
Change requests involving user BC400-00 Changeable

Request number Task number Repository objects created or corrected by employee

Transportable IT3K900051 CARSON

Project Manager User

IT3K900052 CARSON IT3K900053 BC400-00 Report source ZBC400_00_FLIGHTLIST ABAP program IT3K900054 BC400-01 IT3K900055 BC400-02 IT3K900056 BC400-03 IT3K900057 ...

SAP AG 2001

At the beginning of a development project, the project manager creates a change request in the Workbench Organizer. The project manager assigns all project team members to the change request. The Workbench Organizer then creates a task for each project developer. From now on, whenever an employee assigns a Repository object to this change request, the Repository object is automatically entered in the employee's task. Thus all Repository objects that an employee works on during a development project are collected within his or her task folder. The Repository objects are therefore locked for all developers who do not belong to this particular project. Unlike the logical functional divisions that separate Repository objects through the respective development class, change requests are project-related and, therefore, are limited to the time schedule involved. Thus, although a program always belongs to only one development class, it can belong to different change requests at different times.

SAP AG

TAW10

8-17

Example: Creating Development Classes

Create Development Class Development Class Short Text ZBC400_00

Comply with customer namespace

Exercises group 00 Where should the development objects be transported to?

Transport Layer Person Responsible Software Component Application Component

ZDEV BC400-00 HOME CA To which application component does the development class belong?

SAP AG 2001

You can create a development class in the Object Navigator. As of Release 4.6C, you can choose the object type Development Class and enter the name of the development class in the input field. Make sure you comply with the customer namespace conventions. If the development class does not already exist, the system displays the Create Development Class dialog box. For Release 4.6A and 4.6B, you must choose Edit object or Other object in the initial screen. Enter the name of the development class in the input field on Other tab page.

You should check the settings for the following attributes: Transport layer - If you carry out your own developments, you must set up a transport layer for customer developments. Person responsible - This person has full responsibility for the objects in this development class. The system automatically uses this user name as a default value. Software component - For customer developments you should enter HOME as the software component. To get detailed information on the field, select F1 help. Application component - Used to specify the location of the development class within the application hierarchy.

SAP AG

TAW10

8-18

Assignment to a Change Request


Prompt for transportable Workbench request Development class/p.. ZBC400_00

Request

IT3K90051

Workbench request

Exercises for participants of BC400

My requests

Prompt for transportable Workbench request


Change requests involving user BC400-00 Changeable Transportable IT3K900051 FRY IT3K900052 FRY IT3K900053 BC400-00 IT3K900054 BC400-01

Double-click request number

SAP AG 2001

n n

All Repository objects that are created or changed must be assigned to the change request of the respective project. For this course, the trainer has created a change request for the project called "Exercises for Participants of BC400". Each group has a task within this change request. To display all change requests in which you have a task, select Own requests. When you assign all Repository objects (development classes, programs, and so on) to this change request, the system takes care of the exact assignment for your task.

SAP AG

TAW10

8-19

Developing ABAP Programs

Introduction Introduction to to the the R/3 R/3 Repository Repository Working Working with with the the Object Object Navigator Navigator Organizing Organizing Developments Developments Developing Developing ABAP ABAP Programs Programs

SAP AG 2001

SAP AG

TAW10

8-20

Features of the ABAP Programming Language

The ABAP programming language ... l Has defined types l Enables multi-language applications l Has SQL embedded within it l Has been enhanced as an object-oriented language l Is platform-independent l Is downwards compatible

Therefore, it is designed for dialog-based, business applications.

SAP AG 2001

n n n n n n

To support data processing by types, ABAP contains a systematic type hierarchy. Type conversions and type casting are supported. Using translatable text elements, you can develop multi-language applications. The OPEN SQL standard embedded in ABAP allows direct database accesses. ABAP Objects is the object-oriented enhancement of the ABAP programming language. The ABAP runtime system is one of the R/3 Basis components and is platform-independent. ABAP continues to evolve from release to release. If an old syntax statement is replaced by a better one, you can still run the old statement.

SAP AG

TAW10

8-21

General ABAP Syntax I

ABAP keyword keyword

Additions and operands (dependent on keywords)

Period as symbol for closing the the ABAP statement

. DATA DATA wa_scarr TYPE scarr. START-OF-SELECTION. STARTSTART - OF OF-SELECTION. SELECT * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr. . NEW-LINE. NEWNEW -LINE. WRITE wa_scarr-carrid. WRITE . WRITE WRITE wa_scarr-carrname. . WRITE wa_scarr-url. WRITE . ENDSELECT. ENDSELECT.

SAP AG 2001

n n n n n n n n

ABAP programs consist up of individual statements. Each statement ends with a period. The first word in a statement is called a keyword. Words must always be separated by at least one space. Statements can be indented. Statements can take up more than one line. A single line can contain multiple statements. The ABAP runtime system is not case sensitive; that is, it does not distinguish between lowercase and uppercase letters for keywords, additions, and operands. To make it easier to separate them visually, in this course all keywords and their additions are in uppercase and all operands are in lowercase. For indentations and for converting uppercase and lowercase letters, use the Pretty Painter function. Choose Utilities Settings ABAP Editor Pretty Printer

SAP AG

TAW10

8-22

General ABAP Syntax II

* comments ... * * * comments ... * * comments ... DATA wa_scarr TYPE scarr. START-OF-SELECTION.

Comments

" comments ... SELECT * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr. NEW-LINE. WRITE : wa_scarr-carrid, , wa_scarr-carrname, , wa_scarr-url. . ENDSELECT.

Chained Statement

SAP AG 2001

n n

Use an asterisk (*) to introduce comment lines. The ABAP runtime system ignores the comment line. If you want to enter a comment in the middle of a started line, enter double quotes.You can combine consecutive statements with an identical beginning into a single chained statement: Close the identical beginning part with a colon. Separate individual elements that come after the colon by commas. Use blank spaces and line breaks before and after the separators (colons, commas, and periods). The ABAP runtime system considers the individual parts of a chained statement to be single statements.

SAP AG

TAW10

8-23

Return Value After ABAP Statements

PARAMETERS pa_carr TYPE scarr-carrid. DATA wa_scarr TYPE scarr. START-OF-SELECTION. SELECT SINGLE * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr WHERE carrid = pa_carr. IF sy sy-subrc - subrc EQ 0. NEW-LINE. WRITE: wa_scarr-carrid, wa_scarr-carrname, wa_scarr-url. ELSE. WRITE 'Sorry, no data found!'. ENDIF.

SAP AG 2001

n n n

With several ABAP statements, the ABAP runtime system writes a return code into the system field sy-subrc to indicate how successfully the statement was executed The return code zero (0) means that the statement was successful.. Read the documentation for the respective statements to find out whether and how this return code is set in individual cases.

SAP AG

TAW10

8-24

Creating an ABAP Program


Create Program Program ZBC400_00_GS Comply with customer namespace! ABAP: Program Attributes ... Title ...

With TOP Include

Attributes Type Status Application Fixed point arithmetic Executable program Test program

SAP AG 2001

n n n

From the Object Navigator, you can create a program using one of the following options: In the navigation area, choose Program as the object type and enter a program name. Be sure to comply with the customer namespace conventions. If the program does not exist, the system displays the dialog sequence that lets you create a program. (This procedure is possible only as of Release 4.6C.) Display the development class for which you want to create the program. Start the dialog sequence for creating a program using the development class context menu or the Program node. Select Other object... or Edit object. Select the Program objects tab and enter the name. Select Create. In this course, deselect With Top Include (by removing the check mark from the checkbox). (If you dont do this, your source text would be distributed to several programs.) Change the title to a meaningful short text. Choose Test program as the program status for all ABAP courses.

SAP AG

TAW10

8-25

Keyword Documentation in the ABAP Editor

i
Help START-OF-SELECTION. SELECT SINGLE * FROM scarr Editor Help INTO wa_scarr ABAP Overview WHERE carrid = pa_car. ABAP Term WRITE IF sy-subrc = 0. ABAP News MOVE-CORRESPONDING wa_scarr ABAP Docu and Examples TO sbc400_carrier. Keyword CALL SCREEN 100. Documentation MOVE-CORRESPONDING sbc400_carrier

WRITE WRITE:

F1 TO wa_scarr. wa_scarr-carrid, wa_scarr-carrname, wa_scarr-currcode.

ENDIF.
SAP AG 2001

You can locate keyword documentation for an ABAP statement by: Pointing to a statement and selecting F1 to go directly to the documentation for the statement Selecting Information to go to a selection window for the various views of the keyword documentation. Choose Help SAP Library BC Basis Components to access extensive online documentation on all the tools and topics that relate to the ABAP Workbench.

SAP AG

TAW10

8-26

Inactive and Active Development Objects


Saved, for development and testing Activate Program 1, inactive version

Actively integrated, for system-wide usage Program 1, active version Program 2, active version

Program 3, inactive version

Program 3, active version

SAP AG 2001

n n

n n

Whenever you create a development object, or change and then save it, the system stores an inactive version only in the R/3 Repository. Before a Repository object is available on a system-wide basis, it must first be available as an active version. This active version of your program will be used whenever a user wants to execute your program. If your program is available in both versions, you can switch from one version to the other in display mode. Whenever you activate a program, the system first displays a list of all inactive objects that you have processed. This is called the worklist. If you continue to activate the program, the following happens: The system saves the program, that is, it stores or overwrites the inactive version. The system performs a syntax check. The system stores the active version or overwrites it.

SAP AG

TAW10

8-27

Generating Runtime Objects

saved, for development/testing

actively integrated, for system-wide usage Program 1, active version Program 2, active version

Program 3, inactive version

Program 3, active version Generate (automatically) For system-wide usage

Generate (automatically)

Program 3, temporary generated version


SAP AG 2001

Program 3, generated version version

n n n n n

When you generate a development object, the system creates (compiles) a separate runtime object (LOAD) and stores it in the R/3 Repository. This generated version is then the version that is executed (interpreted). Generation takes place automatically, but it can be triggered explicitly. If, for example, a user wants to execute your program and there is still no generated version, the system will use the active version for generation. You can, however, determine which version you want to execute: To execute the active version, start your program from the navigation area. To execute the inactive version, test an executable program from the ABAP Editor. The system temporarily creates a generated version. In this way, development can continue without changing the current system status . All changes to the development object become visible system wide only when the program is activated again. With inactive versions, you have a local, separate view of the R/3 Repository, which provides the basis for a local runtime system.

SAP AG

TAW10

8-28

Creating Transaction Codes


System Help

Create Report Transaction


ZBC400_00_GS

Transaction code Development class Transaction text Program ... Classification

Z00GS ZBC400_00 ... ZBC400_00_GS

Professional User Transaction Easy Web transaction ... ...

SAP AG 2001

n n n n n n

If you want to include a program in role menus or in the Favorites in your SAP Easy Access menu, you must assign a transaction code to it. In the Object Navigator, display the object list for your program. Right-click the program name and choose Create Transaction. Comply with the customer namespace conventions. Choose Program and Selection Screen (Report Transaction) if the program is an executable program. On the next screen, enter the name of the program. Choose Professional User Transaction. Save the transaction code. Since each transaction code is a Repository object, you must assign it to a development class and to a change request on the following screens.

SAP AG

TAW10

8-29

Adding a Transaction Code to the SAP Easy Access Menu


System Help

SAP Easy Access


Favorites Object Navigator SAP Menu Add transaction

Enter Transaction Manually Transaction code Z00GS

SAP AG 2001

To include a transaction code in the your role menu favorites: Display the initial screen (SAP Easy Access menu). Choose Favorites Insert transaction. Enter a transaction code in the dialog box . The transaction code short text appears under the Favorites node. You can start the appropriate program from the context menu for this new node.

SAP AG

TAW10

8-30

Introduction to the ABAP Workbench: Unit Summary

You are now able to: l Describe the structure of the R/3 Repository and its search tools l Use the Object Navigator for your development work l Name and use the utilities for orderly software development l Create development classes, ABAP programs, and transaction codes

SAP AG 2001

SAP AG

TAW10

8-31

ABAP Workbench Exercises


Unit: Introduction to the ABAP Workbench Topic: Organizing Developments
At the conclusion of these exercises, you will be able to: Create a development class Assign changes in Repository objects to a change request

As a developer for an airline group, you are given the task of developing evaluation programs for several airline companies. To group the Repository objects together logically and transport them, you must create a development class. User name: Will be announced by the instructor. ZBC400_## Will be announced by the instructor.

Development class: Change request:

## stands for the two-digit group number. 1-1 Log on to the operating system and then to the specified SAP R/3 training system using the user name the instructor has given you. Enter a new personal password. Create the development class ZBC400_##. Assign it to the change request the instructor has given you. From now on, assign all your Repository objects in the following exercises to this development class and this change request.

1-2

1-3

SAP AG

TAW10

8-32

Exercises
Unit: Introduction to the ABAP Workbench Topic: Developing ABAP Programs
At the conclusion of these exercises, you will be able to: Create, edit, save, and process ABAP programs Check ABAP programs for correct syntax Test and activate ABAP programs Create an ABAP program that lists additional information on all existing flight departure times. Get the data from the database table SFLIGHT. Program: ZBC400_##_GS_LIST SAPBC400WBS_GS_LIST

Model solution:

## stands for the two-digit group number. 2-1 Create the executable program ZBC400_##_GS_LIST without TOP Include. Define a work area for the data retrieval and data display (name suggestion: wa_flight): DATA wa_flight TYPE sflight. Program a loop access to all the data records in the database table SFLIGHT: SELECT * FROM sflight INTO wa_flight. ... ENDSELECT. For each data record, display the contents of the fields carrid, connid, fldate, seatsocc, and seatsmax in the list: NEW-LINE. WRITE wa_flight-carrid. WRITE ... Check your program for syntax errors, test it, and activate it

2-2

2-3

2-4

2-5

SAP AG

TAW10

8-33

Exercises
Unit: Introduction to the ABAP Workbench Topic: Transaction Codes
At the conclusion of these exercises, you will be able to: Assign transaction codes to ABAP programs Add transaction codes to your Favorites list in the SAP Easy Access menu Give your first ABAP program a transaction code, in addition to its technical name, which you use to execute it.

Transaction code: ZBC400_##_GS Program: Model solution: ZBC400_##_GS_LIST SAPBC400WBS_GS LIST

## stands for the two-digit group number. 3-1 Create transaction code ZBC400_##_GS for the executable program ZBC400_##_GS_LIST. Initial object: program and selection screen (report transaction) Execute your program by entering the new transaction code. Include the transaction code ZBC400_##_GS in your favorites in the SAP-EasyAccess-menu. Execute your program by double-clicking the new favorite entry. From now on, it is best if you always work with the Object Navigator. It provides you with an overview of all Repository objects in your development class. From here, you can edit each object directly by selecting it from this list.

3-2

SAP AG

TAW10

8-34

ABAP Workbench Solutions


Unit: Introduction to the ABAP Workbench Topic: Organizing Developments

Follow the instructions as given in the notes and figures on page 3-18 and 3-19, Creating Development Classes and Assignment to a Change Request.

Unit: Introduction to the ABAP Workbench Topic: Developing ABAP Programs

Model solution:
REPORT sapbc400wbs_gs_list. DATA wa_flight TYPE sflight. SELECT * FROM sflight INTO wa_flight. NEW-LINE. WRITE: wa_flight-carrid, wa_flight-connid, wa_flight-fldate, wa_flight-seatsocc, wa_flight-seatsmax. ENDSELECT.

SAP AG

TAW10

8-35

Unit: Introduction to the ABAP Workbench Topic: Transaction Codes

3-1

Follow the instructions as given in the notes and figure on page 3-29, Creating Transaction Codes. Follow the instructions as given in the notes to the figure, Adding a Transaction Code to the SAP Easy Access Menu.

3-2

SAP AG

TAW10

8-36

Introduction to the ABAP Dictionary

Contents:
l SAP Flight Data Model l Transparent Tables l Structures l Using Transparent Tables and Structures in an ABAP Program

SAP AG 2001

SAP AG

TAW10

9-1

Introduction to the ABAP Dictionary: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the SAP flight data model l Describe the structure of a transparent table l Describe the structure of a structure l List the possible uses of transparent tables and structures in ABAP programs

SAP AG 2001

SAP AG

TAW10

9-2

Data Modeling

Real world

Data model

ABAP Dictionary

Relational database
SAP AG 2001

n n n n

In the development of business application software, the real world must be partly mapped in the form of data. An entity represents a business unit. Entities all relate to each other. The entities and relationships are contained in the data model or entity relationship model (ERM). The conversion of the table definitions and their relationships in the ABAP Dictionary are based on this data model. The actual application data is physically stored in the database itself.

SAP AG

TAW10

9-3

Flight Data Model for ABAP Training Courses

Departure city

Departure airport

Typical inquiries at the travel agency: l Suitable airports l Suitable flight connections l Suitable flight times l Additional flight information such as: price, availability

Destination airport

Destination city

SAP AG 2001

ABAP training courses, online documentation, and ABAP keyword documentation all use the same flight data model. All Repository objects in the flight data model are located in the development class BC_DATAMODEL. This training course demonstrates one simple excerpt from this data model, which the instructor can refine if necessary. If a person wants to travel from one place to another, she asks the travel agency the following questions: What connection offers me the best and most direct flight? At what times are flights offered on the date when I want to travel? How can I optimize the travel conditions to find the best solution? What is the cheapest flight, the fastest connection, the connection that gets me there closest to the time when I want to arrive? The passengers view differs from that of a travel agency. In the data model, which is tailored to suit management of the necessary data, all data is stored, organized by technical criteria, in tables on a central database. The amount of data stored far exceeds the demands of the passenger. As a programmer, you must be able to compile the data in programs to suit the requirements of the travel agent.

SAP AG

TAW10

9-4

Relational Data Model


BC_CARRIER T BC_AIRPORT T BC_GEOCITY T

Airline

Airport

City

H BC_PLANFLI T R R

A BC_CITAIRP

A T

Timetable

City-airport assignment

H BC_SFLIGHT T BC_CUSTOM T BC_COUNTER T BC_TRAVLAG T

Flight

Customer

Sales office

Travel agency

H BC_BOOKING T R CR CR

Flight booking

SAP AG 2001

The flight data model contains entities for all business information that is logically connected, such as: Cities Airports Airlines Flights These entities all relate to each other in certain ways: Each flight schedule contains exactly one airline, one departure airport, and one destination airport. Bookable flights always belong to exactly one existing flight schedule each. You can assign cities to nearby airports. You can manage all necessary data without redundancies, using these relationships. At the same time, the travel agency is able to obtain all data requested by the customer.

SAP AG

TAW10

9-5

Converting Using Transparent Tables


BC_CARRIER T

SCARR SCARR
MANDT CARRID CARRNAME CURRCODE URL

Airline

H BC_PLANFLI T

SPFLI
MANDT CARRID CONNID AIRPFROM AIRPTO DEPTIME ...

Timetable

H BC_SFLIGHT T

SFLIGHT
MANDT CARRID CONNID FLDATE SEATSMAX SEATSOCC ...

Flight

H BC_BOOKING T

SBOOK SBOOK
MANDT CARRID CONNID FLDATE BOOKID CUSTOMID COUNTER ...

Flight booking

SAP AG 2001

n n n n n

A transparent table contains different columns, to allow you to manage data records in a structured way. You define transparent tables in the ABAP Dictionary. In this context, the table key is especially significant. The table key of a table combines key fields, which are also called primary key fields . The values in the key fields allow the system to identify all data records uniquely. Fields that link to other tables are called foreign key fields . With these foreign key relationships you can manage the data hierarchically and consistently.

SAP AG

TAW10

9-6

Technical Structure of a Transparent Table


Transparent table Field uses Data element uses Domain

Table including data


SAP AG 2001

n n n n n

You normally use a data element to assign a type to a table field. Semantic properties, such as field labels, are stored in the data element. You normally use a domain for the technical properties. The data type, among other things, is stored in the domain. The ABAP Dictionary contains the platform-independent description of the relevant database table. The database table has the same name as the transparent table in the ABAP Dictionary. The fields also have the same names in both the database and the ABAP Dictionary.

SAP AG

TAW10

9-7

Transparent Tables in the ABAP Dictionary

Table

Edit

Goto

Utilities

Extras

Environment

System

Help

Dictionary: Display Table


Indexes Transparent table Short text Attributes Fields MANDT CARRID CONNID COUNTRYFR CITYFROM AIRPFROM COUNTRYTO CITYTO ...
SAP AG 2001

SPFLI Flight schedule Fields Key ! ! ! Field type S_MANDT S_CARR_ID S_CONN_ID LAND_1 S_FROM_CIT S_FROMAIRP LAND_1 S_TO_CITY ... Currency/Quantity Fields Data type CLNT CHAR NUMC CHAR CHAR CHAR CHAR CHAR ... Length 3 3 4 3 20 3 3 20 ...

Active

Dec. places 0 0 0 0 0 0 0 0 ...

Short text Client for training Airline Carrier Flight connection Country key City of departure Airport of departure Country key Arrival city ...

n n

The fields make up the columns of the transparent table. A check mark in the Key column indicates that the corresponding field is a key field. You normally assign a type to a field using a data element (under Field type). The Short text stored with the data element is listed here. The technical attributes of the field are listed again under Data type, Length , and Dec. places. (A data element normally uses a domain.) This is a logical view of the table. It is a purely technical description. When it is physically converted, the table is in the database, where you also find the table content or the actual application data.

SAP AG

TAW10

9-8

Structures in the ABAP Dictionary

Structure

Edit Goto Utilities Extras Environment System Help

Dictionary: Display Structure

Structure Short text Attributes Component CARRID CONNID FLDATE SEATSMAX SEATSOCC PERCENTAGE

SBC400FOCC Percentage Occupancy of Flights Components Entry help/check DTyp CHAR NUMC DATS INT4 INT4 DEC Length 3 4 8 10 10 5

Active

Currency/quantity fields Dec. places 0 0 0 0 0 2 Short text Airline Flight connection Flight date Maximum capacity Occupied seats Flight Occupancy

Component type S_CARR_ID S_CONN_ID S_DATE S_SEATSMAX S_SEATSMAX S_FLGHTOCC

SAP AG 2001

A flat structure is defined in almost the same way as a transparent table, except that you cannot convert fie lds to key fields. This would be pointless for structures. Structures do not represent a database table in the ABAP Dictionary, but are a pure type definition instead. When defining a flat structure, however, we refer to component and component type as opposed to field and field type, because, in contrast to transparent tables, you can define complex structures. This means that, it is possible to store a structure or substructure under a component name.

SAP AG

TAW10

9-9

Using Global Structures for Data Objects

DATA wa_focc TYPE sbc400focc sbc400focc. TABLES spfli spfli. PARAMETERS pa_carr TYPE spflispfli spfli-carrid. -carrid

carrid connid fldate wa_focc L H 400 20011231

seatsmax 450

seatsocc 180

percentage 40

mandt carrid connid countryfr cityfrom spfli 4 0 0 A A 64 US New York

airpfrom countryto ... JFK US ...

pa_carr L H

SAP AG 2001

n n n

n n n

A structure is used to centrally provide a data type in which fields from different tables are compiled. In the ABAP program, you can define data objects using the (Dictionary) structure. A transparent table merely represents a technical description in the ABAP Dictionary. Therefore you can use it as a central data type definition, as with a structure. This means that, similarly to the data object definitions listed above, the following variants are also possible: DATA wa_spfli TYPE spfli provides a data object, typed like the line in the transparent table SPFLI. TABLES sbc400focc provides a data object, typed like the structure SBC400FOCC. PARAMETERS pa_carr TYPE sbc400focc-carrid provides an input field, typed like the CARRID component of the structure SBC400FOCC.

SAP AG

TAW10

9-10

Using Global Structures for Dialogs


TABLES spfli. Screen Painter PARAMETERS pa_carr TYPE spfli-carrid.

Dict/Program fields

Airline Performance Assistant F1 Short description ...

Short description of the airline


The field contains the ID of the airline.

Documentation
SAP AG 2001

ID AA AB AC AF

Airline American Airlines Air Berlin Air Canada Air France

Input help

n n n n n

If you use an elementary structure to define an input field on a selection screen, you can use semantic attributes or technical attributes. On request, the system automatically generates a documentation dialog and an input help dialog for the user. The necessary information for this is taken from the ABAP Dictionary. The same applies to fields of transparent tables. If you use an elementary structure component to assign a type to an input/output field on a screen, you can use the same attributes as with selection screens. If you have defined a foreign key relationship, the resulting value combinations appear in the input help on the screen. If an error occurs, the system processes an automatic error dialog. The same applies to fields of transparent tables. Use the TABLES statement to define the data object for the data transport between screen and program.

SAP AG

TAW10

9-11

Introduction to the ABAP Dictionary: Unit Summary

You are now able to: l Describe the SAP flight data model l Describe the structure of a transparent table l Describe the structure of a structure l List the possible uses of transparent tables and structures in ABAP programs

SAP AG 2001

SAP AG

TAW10

9-12

ABAP Dictionary Exercises


Unit: Introduction to the ABAP Dictionary Topic: Using Global Structures for Data Objects and Dialogs
At the conclusion of these exercises, you will be able to: Establish the technical names of data types and data objects that are used in user dialogs. Run where-used lists within an ABAP program. You have to examine a specified ABAP program to see whether global data types are used in it, and if so, which ones.

Program:

SAPBC400WBT_GETTING_STARTED

1-1

Open the object list for development class BC400. Find the program SAPBC400WBT_GETTING_STARTED, and open its object list. Throughout the exercise, make sure that you remain in display mode . Run the program to find out how it works. There is an input field on the selection screen. 1-3-1 1-3-2 1-3-3 1-3-4 What information must you pass to the program? (Use <F1> for field help.) What values can you enter? (Use <F4> for input help.) What information does the program provide? What is the technical name of the input field? (Use the Technical information in <F1> field help.)

1-2 1-3

SAP AG

TAW10

9-13

1-4

Two display fields appear on the screen. 1-4-1 Find out the screen number. (Choose System Status.) 1-4-2 What information is displayed? (Use <F1>field help.) 1-4-3 What are the technical names of the display fields? Do the fields belong to a structure with a globally defined type? (Use the Technical information in <F1> field help.)

1-5

Use the object list to analyze the source code of the program. 1-5-1 What data objects are there? Where are they defined in the program? 1-5-2 Where in the program are they used? (Use the where-used list in the ABAP Editor.) 1-5-3 What data object corresponds to the input field on the selection screen? (Search the object list for a data object with the same name as the field that you found in step 1-3-4.)

SAP AG

TAW10

9-14

ABAP Dictionary Solutions


Unit: Introduction to the ABAP Dictionary Topic: Using Global Structures for Data Objects and Dialogs
1-3 Analyzing by executing a program: 1-3-1 You need to enter an airline code. 1-3-2 The values permitted here depend on the contents of database table SCARR. 1-3-3 The program displays detailed information on the airline selected. This information is first displayed on a screen and then as a list. 1-3-4 The technical name of the input field is pa_car. 1-4 Analyzing by executing a program: 1-4-1 The screen number is 100. 1-4-2 The system again displays the airline code and the currency code. 1-4-3 The output fields are sbc400_carrier-carrid and sbc400_carriercurrcode. Double-click in the Structure field to go to the ABAP Dictionary and analyze the global type more closely. 1-5 Analyzing using the program's object list: 1-5-1 The program has the structures sbc400_carrier and wa_scarr and the elementary data object pa_car. 1-5-2 The elementary data object pa_car belongs to the input field, with the same name, on the selection screen.

SAP AG

TAW10

9-15

Basic ABAP Language Elements

Contents:
l Data Types and Data Objects l Basic ABAP Statements l Using the ABAP Debugger l Working with Structures l Working with Internal Tables

SAP AG 2001

SAP AG

TAW10

10-1

Basic ABAP Language Elements: Unit Objectives

At the conclusion of this unit, you will be able to: l Define elementary and structured data objects l Use basic ABAP statements l Execute and analyze programs in debugging mode

SAP AG 2001

SAP AG

TAW10

10-2

Data Types and Data Objects

Data Data Types Types and and Data Data Objects Objects Basic Basic ABAP ABAP Statements Statements Using Using the the ABAP ABAP Debugger Debugger Working Working with with Structures Structures Working Working with with Internal Internal Tables Tables

SAP AG 2001

SAP AG

TAW10

10-3

Using Data Types


Data types describe the attributes of:

ABAP program

Input / output fields

Data objects Object Interface Method


ace ule erf d Int n mo o ti nc Fu

Interface Subroutine

... Interface parameters


SAP AG 2001

n n n

The type of a data object defines its technical attributes. The type of an interface parameter defines the type of the values (actual parameters) that are transferred when the modularization unit is called. In addition to the technical attributes, the type of an input or output field can provide further information; for example, you can use it to control the value or input help.

SAP AG

TAW10

10-4

Local and Global Data Types


Local data types: Technical attributes only ABAP program Central data types: Technical and semantic attributes ABAP Dictionary

Object Interface Method

ace ule erf d Int n mo o ti nc Fu

Interface Subroutine

SAP AG 2001

n n n n n n

You can define data types in an ABAP program (local, keyword TYPES) or in the ABAP Dictionary (global). Using global data types has several advantages: Global types are managed centrally and you can use them in all repository objects. This increases the consistency of the system and significantly reduces the amount of maintenance. In the ABAP Dictionary, you can perform an environment analysis (where-used list). Global data types can be linked to business variables by content, and therefore contain semantic and technical information. You can use global datat types to design screens. When searching for global data types, make sure you take both the technical and semantic attributes into account. Only then will you be able to make full use of the maintenance and robustness advantages of your program.

SAP AG

TAW10

10-5

Defining Data Objects

Local types TYPES type_name TYPE ... Predefined ABAP types d t i p

DATA do_name TYPE type_name. Global types

f n string c xstring x

DATA do_name_new LIKE do_name.


SAP AG 2001

n n

n n

You can use a predefined ABAP type, a local, or a global type to type a data object. The following predefined ABAP types are complete: d Date (format: YYYYMMDD) t Time (format: HHMMSS) i Integer f Floating point number string String (of variable length) xstring Byte sequence (he Xadecimal string, of variable length) You must define the length for these predefined types: c Character n Numeric character x Byte (he Xadecimal) p Packed number (= binary coded decimals). You must enter the number of decimal places. For more information on predefined ABAP types, refer to the keyword documentation on TYPES or DATA. You can use LIKE to refer to the type of a predefined data object.

SAP AG

TAW10

10-6

Defining Elementary Data Objects

TYPES t_percentage(3) TYPE p DECIMALS 2. DATA: number percentage carrid connid TYPE TYPE TYPE TYPE i VALUE 17, t_percentage, s_carr_id, sbc400focc-connid. Data element Structure SBC400FOCC

S_CARR_ID

number percentage carrid connid +

17

SAP AG 2001

n n n n

The predefined ABAP types (d, t, i, f, string, and xstring) are complete. This means they can define an elementary data object of these types as follows: DATA do_name TYPE predefined_ABAP_type. For the predefined ABAP types c, n, p, and x, you must define the length. This means you should first define an elementary type: TYPES type_name(length) TYPE predefined_ABAP_type. You use it to define the data object: DATA do_name TYPE type_name. For type p, you can also define the number of decimal places using the DECIMALS addition. You can use the VALUE addition to pre-assign the value of an elementary data object. For compatibility reasons, you can still construct data objects in the DATA statement without first having to define the type locally in the program with a TYPES statement. In the case of incompletely predefined ABAP types, the system adds standard values to make up the missing type information. If there is no type specification at all, the system defines a type c data object with a length of one.For the standard lengths and for more information, refer to the keyword documentation for TYPES and DATA. The same syntax applies to global types as to user-defined types: DATA do_ name TYPE global_type_name

SAP AG

TAW10

10-7

Fixed Data Objects


Literal: Fixed data object without ID code

Numeric Numeric literal: Type ii or p literal: Type Positive integers: 123 Negative integers: -123

Text literal literal: Type c Character string: 'aBcdE' Decimal numbers: '123.45' Floating point numbers: '123.45E01'

Constant:

Fixed data object with ID code

CONSTANTS CONSTANTS const_name TYPE type_name VALUE [ literal | IS INITIAL ].

SAP AG 2001

You assign a value to each fixed data object in the source code. Therefore, it cannot be changed at run time. n You can use literals to transfer fixed values to ABAP statements. There are numeric literals and text literals. The latter are always enclosed in inverted commas: You can display integers as numeric literals (in the case of negative numbers, with a preceding sign). The system then maps them onto the data type i, if they are within the value range of 4byte integers. Higher numeric literals are mapped onto data type p. You must display all other literals (such as character sets, numbers with decimal pla ces, floating point numbers) as text literals . They are mapped onto data type c and converted later, if necessary. If you want to include an inverted comma in a text literal, you must enter it twice.

n n

You define constants using the CONSTANTS statement. Their type is defined similarly to the type of an elementary data object with the DATA statement. The VALUE addition is required for constants Recommendation: Avoid literals when using statements. Create constants instead. This significantly improves program maintenance.

SAP AG

TAW10

10-8

Basic ABAP Statements

Data Data Types Types and and Data Data Objects Objects Basic Basic ABAP ABAP Statements Statements Using Using the the ABAP ABAP Debugger Debugger Working Working with with Structures Structures Working Working with with Internal Internal Tables Tables

SAP AG 2001

SAP AG

TAW10

10-9

Value Assignments
Data declarations 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 c_qf QF carrid1 carrid2 LH MOVE c_qf TO carrid1. carrid2 = carrid1. ADD 1 TO counter. CLEAR: carrid1, CLEAR carrid2, counter. ABAP program ABAP runtime system Time
SAP AG 2001

counter 0 0 0 1

QF QF QF

LH QF QF

When a program is started, the program context is loaded into a storage area of the application server and made available for all the data objects. n Every elementary data object is preassigned the type-related initial value, except if you preassigned a different value using the VALUE addition. n You can use the MOVE statement to copy the contents of data objects. Two statements are available for this purpose: MOVE source TO target. target = source. n If the two data objects have different types, the type is automatically converted if there is a conversion rule. n For detailed information about copying and the conversion rules, refer to the keyword documentation for the MOVE statement. n The CLEAR statement resets the contents of a data object to the type-related initial value. For detailed information about the initial values for a particular type, refer to the keyword documentation for the CLEAR statement.

SAP AG

TAW10

10-10

Calculations

Data declarations DATA: max TYPE sbc400focc-seatsmax, occ TYPE sbc400focc-seatsocc, percentage TYPE sbc400focc-percentage.

COMPUTE COMPUTE

percentage = occ * 100 / max.

The keyword is optional:

percentage = occ * 100 / max.

ABAP program
SAP AG 2001

n n

In ABAP you can program arithmetic expressions nested to any depth. Note that parentheses and operators are keywords and must be separated by at least one blank character. The following are valid operators: + Addition Subtraction * Multiplication / Division ** Power DIV Integer division without remainder MOD Integer division with remainder There are several functions for different data types in the ABAP runtime environment. For example, the following statement returns the current length of the contents of a character set: length = STRLEN( cityfrom ). With functions the opening parenthesis is part of the ID. The rest must again be separated by at least one space. In general, the usual algebraic rules apply for the processing sequence : expressions in parentheses come first, then powers, then multiplication/division, and finally addition/subtraction. For detailed information about the available operations and functions, refer to the keyword documentation for COMPUTE..

SAP AG

TAW10

10-11

Conditional Branching

CASE data_object_1. WHEN data_object_2.


Statements

WHEN data_object_3 OR OR data_object_4.


Statements

WHEN OTHERS. OTHERS


Statements

IF <logical_expression>.
Statements

ENDCASE ENDCASE.

ELSEIF <logical_expression>.
Statements

ELSE ELSE.
Statements

ENDIF ENDIF.

SAP AG 2001

n n

n n

In ABAP you have two ways to execute different sequences of statements, depending on certain conditions. With the CASE-ENDCASE construction the criterion for the execution of a statement block is the similarity of the data objects. If no comparison is successful, then the system executes the OTHERS branch, if it is available. Except for the first WHEN branch, all further additions are optional. With the IF-ENDIF construction, you can use any logical expressions. If the condition is met, the system executes the relevant statement sequence. If no comparison is successful, then the system executes the OTHERS branch, if it is available. Except for the first query, all further branches are optional. For both constructions, the system executes only one statement sequence and always for the first valid case. Recommendation: If, in every condition, you check that a variable is equal to a given value, use the CASE-ENDCASE construction. It is clearer and less runtime intensive. Outside of loops you can also use CHECK instead of IF. This query sets the execution of all statements up to the end of the current processing block under one condition. If this is unsuccessful, the system continues with the first statement in the next processing block.

SAP AG

TAW10

10-12

Loops
DO [ n TIMES ] [...].
Statements

ENDDO.
Loop Loop counter: sy-index sy-index

WHILE <logical_expression>.
Statements

ENDWHILE.

LOOP AT ...
Statements

ENDLOOP.

DO.
Statements

SELECT ...
Statements

ENDSELECT.

IF <abort_condition>. EXIT. ENDIF. ENDDO.

SAP AG 2001

In ABAP there are four loop constructions, whereby LOOP-ENDLOOP and SELECT-ENDSELECT represent special cases. In the DO and WHILE loops, the system stores the number of the current loop pass in the sy-index field. If these loops are nested, sy-index contains the number of the current (that is, inner) loop. Unconditional/index controlled loops The statements between DO and ENDDO are executed until the loop is left over other statements. You also have the option of specifying the maximum number of loop passes; otherwise, you may get an endless loop. Header controlled loops The statements between WHILE and ENDWHILE are executed only if the condition <logical_expression> has been met. You can use the statements CHECK and EXIT for different effects on the way the loop is processed. For example, you can construct a footer-controlled loop.

SAP AG

TAW10

10-13

Dialog Messages

MESSAGE tnnn(message_class) [ WITH v1 [ v2 ] [ v3 ] [ v4 ] ].

Type
t s

Meaning

Behavior

Message appears in

Status message

Program continues without interruption Program continues after interruption Context dependent Context dependent Program aborted Runtime error MESSAGE_TYPE_X is triggered

Status line in next screen

Information

Modal dialog box

w e a x

Warning Error Termination Short dump


SAP AG 2001

Status bar Status bar Modal dialog box Short dump

n n n

You can use the MESSAGE statement to send dialog messages. You must specify the three-digit message number and the message class. Furthermore, you can use the WITH addition to include up to four values. The system, depending on the message text, inserts these values into the message text. You control the dialog behavior using the type abbreviation t. There are six different types of message: a Abort The program is ended after a dialog box. x Ex it The program ends in a short dump. e Error Runtime behavior is context dependent. w Warning Runtime behavior is context dependent. i Information The program continues after a dialog box. s SuccessThe message appears in the status bar on the subsequent screen. For further information about the syntactic alternatives of the MESSAGE statement, refer to the keyword documentation.

SAP AG

TAW10

10-14

Runtime Behavior of Dialog Messages


Help

Editor Help ABAP Overview ABAP Term ABAP News ABAP Docu and Examples

ABAP Documentation and Examples ? BC - ABAP Programming ? ABAP Introduction ? ABAP Programming Language ? ABAP User Dialogs ? Screens ? Selection Screens ? Lists ? Messages Simple example for messages Demonstration for all message types ... ?
SAP AG 2001

n n

Depending on the context in which they appear, some message types show different dialog behavior. You can find a program for testing the resulting options in the ABAP documentation. To access these example programs, choose Utilities Help onABAP doc. and examples (in the following dialog box)

SAP AG

TAW10

10-15

Using the ABAP Debugger

Data Data Types Types and and Data Data Objects Objects Basic Basic ABAP ABAP Statements Statements Using Using the the ABAP ABAP Debugger Debugger Working Working with with Structures Structures Working Working with with Internal Internal Tables Tables

SAP AG 2001

SAP AG

TAW10

10-16

Executing a Program in Debugging Mode

Or: Set a breakpoint and execute the program Use the context menu
Program ZBC400_00_GS ZBC400_00_GS

REPORT sapbc400wbt_getting_started. TABLES sbc400_carrier. DATA wa_scarr TYPE scarr. PARAMETERS pa_car TYPE scarr-carrid. START-OF-SELECTION. SELECT SINGLE * FROM scarr Debugging INTO CORRESPONDING WHERE carrid = pa_car. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc4 CALL SCREEN 100. MOVE-CORRESPONDING sbc400_carrier T WRITE:/ wa_scarr-carrid, wa_scarr-carrname,

Execute

SAP AG 2001

You can start a program in Debugging mode from the Object Navigator, without having to change the program in two ways: In the navigation area, choose Execute Debugging for the selected program. In the editing area, select the desired program line and choose Set/delete breakpoint. Then start the program by choosing Execute Direct processing (F8)

SAP AG

TAW10

10-17

Switching to Debugging Mode at Runtime

System /h Utilities

Help Or: Choose menu System Debug screen Debug ABAP

Enter /h into the command field and then select <Enter>

SAP AG 2001

If you want to debug only certain parts of a program, start the program first and then switch to debugging mode before a screen change. You can do this in two ways: Choose System? Utilities? Debug ABAP or Debug screen. Enter /h in the command field and select Enter.

SAP AG

TAW10

10-18

Debugging Mode: Single Step and Field Contents


X ABAP Debugger
Watchpoint r

SAP a
chws chws

Single ZJJ_FORMS step

Fixed point arithmetic 15 30 5

SELECT SINGLE * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr Current statement WHERE carrid = pa_carr. 4 IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. Double-click the CALL SCREEN 100. data object MOVE-CORRESPONDING sbc400_carrier TO wa_scarr.
Field Name 1 - 4

pa_carr

6 LH

Field Value

SY-SUBRC SAP AG 2001

SY-TABIX

SY-DBCNT

n n

In debugging mode, you can choose Single step to execute the program statement by statement. You can display the contents of up to eight data objects. Enter the names in the left input field or double-click the name in the displayed source code.

SAP AG

TAW10

10-19

Debugging Mode: Breakpoints


X ABAP Debugger
Watchpoint

SAP a
chws chws

Continue

Fixed point arithmetic 15 30 5

4SELECT SINGLE * FROM scarr INTO CORRESPONDING FIELDS OF wa_scarr WHERE carrid = pa_carr. IF sy-subrc = 0. MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. CALL SCREEN 100. MOVE-CORRESPONDING sbc400_carrier TO wa_scarr.
Variant 1 - 4

Variant

SY-SUBRC SAP AG 2001

SY-TABIX

SY-DBCNT

n n n n n

To set a breakpoint, double -click in front of a line of source code. To set a breakpoint for a specific ABAP statement, choose: ? Breakpoint? ? Breakpoint at? Statement. If you choose Continue, the program is executed up to the next breakpoint. If you Save the breakpoints, they remain intact while you are logged on to the system. With breakpoints, the ABAP Workbench switches to debugging mode only for the developer who set the breakpoints. All other users can execute the program directly or set their own breakpoints

SAP AG

TAW10

10-20

Debugging Mode: Tracing Data Changes


Watchpoint Create/Change Watchpoint Local watchpoint (only in specified program) Program pa_carr Field name Relational operator = Comparison field (Comparison value if not selected) Comp. field/value LH

Watchpoints No. Local Program Field name pa_carr 1 2 3 ... 10 Logical operator between watchpoints
SAP AG 2001

Operator Field Comp. field/value = LH

OR

AND

Watchpoints are breakpoints that depend on the field content. You can create the following types of watchpoints: Field name: The program is executed until the content of the field has changed. Field name, relational operator, comparison value: The program is executed until the content of the field has changed so that the defined logical condition, relative to a value, is met. Field name, relational operator, comparison value: The program is executed until the content of the field has changed so that the defined logical condition, relative to the content of a field, is met. You can set up to 10 watchpoints and link them using the logical operators AND or OR.

SAP AG

TAW10

10-21

Working with Structures

Data Data Types Types and and Data Data Objects Objects Basic Basic ABAP ABAP Statements Statements Using Using the the ABAP ABAP Debugger Debugger Working Working with with Structures Structures Working Working with with Internal Internal Tables Tables

SAP AG 2001

SAP AG

TAW10

10-22

Definition of Structures with Global Types

Structure DATA wa_focc TYPE sbc400focc. DATA TABLES TABLES spfli. SPFLI SBC400FOCC Transparent table

carrid connid fldate wa_focc

seatsmax

seatsocc

percentage

mandt carrid connid countryfr cityfrom spfli

airpfrom countryto ...

SAP AG 2001

n n n

In ABAP, you can define structured data objects (simply called structures). This allows you to combine values that belong together logically into one object. Structures can be nested. This means that components can consist of more structures or even tables. There are two ways to define structures: For DATA struc_name TYPE struc_type, you can use local or global types struc_type. TABLES global_struc_type defines a structure that is technically managed in a special memory area. It has the same name as the global structure, global_struc_type. For this variant, the global structure must be flat, that is, all components must have an elementary type. Since Release 4.0, TABLES structures serve only as interfaces for screen fields..

SAP AG

TAW10

10-23

Definition of Structures with Local Types

TYPES: BEGIN BEGIN OF 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 END OF OF st_flightinfo . DATA wa_flightinfo TYPE st_flightinfo.

carrid connid fldate wa_flightinfo

seatsmax

seatsocc

percentage

SAP AG 2001

n n n

You can also define structure types locally using the TYPES statement. The components are enclosed by the following statements as shown in the graphic: BEGIN OF structure_type_name. ... END OF structure_type_name. Each individual component can in turn be assigned any type you wish. For more information, refer to the keyword documentation for TYPES. You define the data object itself in the usual way. For compatibility reasons, you can also directly define a structured data object: DATA: BEGIN OF structure_name ... END OF structure_type_name

SAP AG

TAW10

10-24

Addressing Structure Components

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.

mandt carrid carrname currcode url wa_scarr

SAP AG 2001

n n

Components of a structure are always addressed using a hyphen: structure_name-component_name. For this reason, do not use hyphens in names.

SAP AG

TAW10

10-25

Copying Structure Components with the Same Name

DATA: wa_sflight TYPE sflight, wa_focc TYPE sbc400focc. MOVE-CORRESPONDING MOVEMOVE -CORRESPONDING wa_sflight TO wa_focc.

mandt carrid connid fldate wa_sflight

...

seatsmax seatsocc ...

wa_focc carrid connid fldate seatsmax seatsocc percentage

SAP AG 2001

The statement MOVE-CORRESPONDING source_struc TO target_struc copies the contents of the structure source_struc into the structure target_struc component by component. The value assignment works only if the components have identical names. All other components remain unchanged.

SAP AG

TAW10

10-26

Structures in Debugging Mode


X ABAP Debugger
Watchpoint Fields Main program Source code of

SAP a
chws chws

Fixed point arithmetic 5

wa_sbc400 Structured field SELECT SINGLE * FROM scarr INTO CORRESPONDING Length (in bytes) 58 FIELDS OF wa_scarr WHERE carrid = pa_carr. 4 IF sy-subrc = No. 0. Component name Type Length Contents MOVE-CORRESPONDING wa_scarr TO sbc400_carrier. 1100. MANDT C 3 100 Double-click the CALL SCREEN 2 CARRID AA C 3 data object MOVE-CORRESPONDING sbc400_carrier TO wa_scarr. 3 CARRNAME C 20 American Airlines Variant 4 CURRCODE USD C 5 wa_sbc400 5 MARK C 1 6 UNAME C 12 7 UZEIT 000000 T 6 8 DATE D 8 00000000
SY-SUBRC SAP AG 2001 0

You can trace the field contents of a structure by entering the name of the structure in the left column. Double-click this entry to see the component display.

SAP AG

TAW10

10-27

Working with Internal Tables

Data Data Types Types and and Data Data Objects Objects Basic Basic ABAP ABAP Statements Statements Using Using the the ABAP ABAP Debugger Debugger Working Working with with Structures Structures Working Working with with Internal Internal Tables Tables

SAP AG 2001

SAP AG

TAW10

10-28

Internal Tables

Table can be extended dynamically

SAP AG 2001

Internal tables are data objects that allow you to retain several data records with the same structure in memory. In principle, the number of data records is unlimited. It is restricted only by the capacity limits of specific system installations. n The ABAP runtime system dynamically manages the length of internal tables. This eliminates any work concerning working memory management. n The individual data records in an internal table are known as table lines or table entries. For this reason, the individual components in a line are referred to as columns of the internal table. n The line type of an internal table can be any ABAP data type, elementary or structured, or it can be another internal table. n Internal tables are a simple way of processing large data records in a structured form within a program. Typical uses include: Temporarily storing data from database tables for future processing Structuring and formatting data for output Formatting data for use by other services

SAP AG

TAW10

10-29

Attributes of Internal Tables

CARRID CONNID DISTANCE Line index 1 2 3 4 5 6

Line Line type type Key definition definition Components Components Sequence Unique / nonnon- unique key key

AA LH LH QF SQ UA

0017 0400 0400 0005 0866 0007

2,572 6,162 7,273 10,000 1,625 2,572


5

Index Index access access Data access type UA 0007 Key access

SAP AG 2001

n n

The data type of an internal table is completely specified by the following attributes: Line type This is the source of the attributes of the individual columns. You normally specify a structure type but any data types are possible. n Key definition The key columns and their order define the criteria by which the tables are identified. Depending on the access type, the key can be defined as unique or non-unique . With unique keys there are no multiple entries with identical values in the key. n Data access type With a key access as with database tables you access using the field contents. Example : A read access using the search term 'UA 0007' to an internal table with the unique key CARRID CONNID and the data pictured above returns exactly one data record. Index access : Unlike database tables, with internal tables the system may number the lines and give the line an index. You can use this idex to access a specific table line. Example : A read access to a data record with index 5 returns the fifth data record of the internal table

SAP AG

TAW10

10-30

Connection Between Table Kind and Access Type

Index tables Table type Index access n

Hashed table

STANDARD STANDARD TABLE TABLE

SORTED TABLE TABLE

HASHED TABLE TABLE

Key access

Unique / NON- UNIQUE Non-Unique Key n Access Using


Mainly index

UNIQUE | NON-UNIQUE

UNIQUE

Mainly keys

Keys only

SAP AG 2001

Another internal table attribute is the table type . Internal tables can be divided into three table types according to the respective access types: With standard tables the line numbering is maintained internally. Both index and key accesses are possible. With sorted tables the data records are always sorted according to key and saved. Here too, the index is maintained internally. Both index and key accesses are possible. With hashed tables the data records are managed optimized at run time. A unique key is a requirement. With hashed tables only key accesses are possible. Which table type you use in each case, depends on how that table's entries are generally going to be accessed: For index accesses you should normally use standard tables. Sorted tables are best for unique keys and fixed sorting. With hashed tables the runtime optimization is noticeable only if the accesses are of the read type with a unique key. This course deals with standard tables only. Apart from a few special cases, the syntax is identical for all three table types.

SAP AG

TAW10

10-31

Definition of Internal Tables with Global Types


Table type Line type and access Line type Data access type Key Key definition Key category Key components SBC400_T_SBC400FOCC SBC400_T_SBC400FOCC SBC400FOCC Standard table Key components Non-unique CARRID CONNID FLDATE

DATA DATA itab_flightinfo TYPE sbc400_t_sbc400focc.

carrid connid fldate itab_flightinfo

seatsmax

seatsocc

percentage

SAP AG 2001

n n n

Table types can be defined locally in a program or globally in the ABAP Dictionary. For DATA itab_name TYPE itab_type you can use local or global types itab_type. For detailed information on the definition of global table types in the ABAP Dictionary, refer to the SAP Library under Basis ABAP Workbench BC-ABAP Dictionary Types Table types.

SAP AG

TAW10

10-32

Definition of Internal Tables with Local Types

TYPES: tt_flightinfo TYPE STANDARD TABLE OF sbc400focc NON WITH WITH NON-UNIQUE NON-UNIQUE KEY KEY carrid connid fldate. DATA itab_flightinfo TYPE tt_flightinfo.

carrid connid fldate itab_flightinfo

seatsmax

seatsocc

percentage

SAP AG 2001

n n n n n n n

You can also define internal table types locally using the TYPE statement. The table type is specified between TYPE and TABLE OF. The line type comes after TABLE OF. The key fields are listed after the WITH addition. Note that the order of the key fields plays a part here. For detailed information about defining local table types, refer to the keyword documentation on TYPES. You define the data object itself in the usual way. For compatibility reasons, you can also directly define an internal table as follows: DATA itab_name TYPE table_kind TABLE OF struc_type WITH key_def.

SAP AG

TAW10

10-33

Overview: Typing Structured Data Objects


ABAP program DATA wa TYPE spfli. SELECT ... FROM spfli INTO wa ... TABLES sbc400focc. ABAP Dictionary Transparent table SPFLI (Description) Database
AA AA ... LH LH 17 64 ... 400 402 ... ... ... ... ...

SPFLI

Structure Structure SBC400FOCC

DATA wa TYPE sbc400focc.

Structure Structure SBC400FOCC

DATA it TYPE sbc400_t_sbc400focc.


AA AA ... LH LH 17 64 ... 400 402 ... ... ... ... ...

Table type SBC400_T_SBC400FOCC

SAP AG 2001

SAP AG

TAW10

10-34

Overview: Accessing Single Records


Append APPEND wa TO itab. APPEND

Insert

INSERT INSERT

wa INTO TABLE itab <condition>.

Read

READ TABLE TABLE itab INTO wa <condition>. READ

Change

MODIFY TABLE itab FROM wa [ <condition> ]. MODIFY

Delete
SAP AG 2001

DELETE itab <condition>. DELETE

The following single record operations are available for internal tables: In each case wa represents a structure that must have the same type as the line type of the internal table itab. APPEND Appends the contents of a structure to an internal table. This operation should be used with standard tables only. INSERT Inserts the contents of a structure into an internal table. In a standard table it is appended, in a sorted table it is inserted in the right place, and in a hashed table it is inserted according to the hash algorithm. READ Copies the contents of a line in an internal table to a structure. MODIFY DELETE Overwrites a line in an internal table with the content of a structure. Deletes a line of an internal table.

COLLECT Accumulates the contents of a structure into an internal table. This statement may be used only for tables whose non-key fields are all numeric. The numeric values are summarized for identical keys

For detailed information about the ABAP statements described here, refer to the relevant keyword documentation.

SAP AG

TAW10

10-35

Overview: Processing Sets of Records


LOOP LOOP AT itab INTO wa <condition>. ENDLOOP.. ENDLOOP

Loop: For all single record operations

Delete

DELETE itab <condition>.

Inserting several lines from another internal table

INSERT LINES OF itab2 <condition2> INTO itab1 <condition1>.

Appending several lines from another internal table

APPEND INSERT LINES OF itab2 <condition1> TO itab1.

SAP AG 2001

The following set operations are available for internal tables: In each case wa represents a structure that must have the same type as the line type of the internal table itab. LOOP ... ENDLOOP The LOOP places the lines of an internal table one by one into the structure specified in the INTO clause. All single record operations can be executed within the loop. In this case, for the single record operations, the system identifies the line to be processed. DELETE Deletes the lines of the internal table that satisfy the condition <condition>. INSERT Copies the contents of several lines of an internal table to another internal table. APPEND Appends the contents of several lines of an internal table to another standard table.

For detailed information about the ABAP statements described here, refer to the relevant keyword documentation.

SAP AG

TAW10

10-36

Syntax Example: Filling Line by Line

* define internal table and workarea: DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF itab_flightinfo.

itab_flightinfo

wa_flightinfo * 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.
SAP AG 2001

n n

You can insert lines into an internal table by first filling a structure with the required values and then inserting it into the internal table using the INSERT statement. For standard tables, this means that the line is appended to the table. For sorted tables and hash tables, the system inserts the line after referring to the key.

SAP AG

TAW10

10-37

Syntax Example: Reading Contents Using a Loop

* define internal table and workarea: DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF itab_flightinfo.

itab_flightinfo

wa_flightinfo 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.
SAP AG 2001

n n n

You can read and process the contents of an internal table using a LOOP by accessing the structure component within the loop. In this example, the WRITE statement is used to create a list from the field contents. 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 of the internal table using the MODIFY statement.

SAP AG

TAW10

10-38

Operations on the Whole Internal Table

Sort

SORT SORT

itab <conditions>.

Delete the entire content of the internal table

REFRESH REFRESH

itab.

SAP AG 2001

n n

The following operations affect the whole internal table. SORT You can use this to sort any number of columns in a standard or hashed table in ascending or descending order. You may want to take culture-specific sort rules into account. REFRESH This deletes the entire contents of an internal table. A part of the previously used working memory remains available for future insertions. FREE This deletes the entire contents of the internal table and releases the previously used working memory. CLEAR Unlike all other data objects, this statement has the same effect as the REFRESH statement on internal tables with no header line.

SAP AG

TAW10

10-39

Syntax Example: Sorting a Standard Table

* define internal table and workarea: DATA: itab_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo LIKE LINE OF itab_flightinfo.

itab_flightinfo

wa_flightinfo

SORT itab_flightinfo BY percentage DESCENDING DESCENDING.

Name of column(s) by which to sort

Ascending or descending?

SAP AG 2001

n n

n n

You can sort standard tables by any column, simply by entering the column name after the BY addition to the SORT statement. SORT itab [ ASCENDING | DESCENDING ] [ BY f1 [ ASCENDING | DESCENDING ] ... fn [ ASCENDING | DESCENDING ] ] [ AS TEXT ] [ STABLE ]. Sorting the internal table by the table key or specified field order: Without an addition the system sorts in ascending order. If you use the AS TEXT addition, the system will, while sorting by character-type fields, take the culture-specific sort rule into account. Only if you use the STABLE addition will the relative order of data records, which are identical in the sort key, remain intact during sorting. In this example, the data records of the internal table are sorted in descending order by the percentage occupancy of flights. For more details, refer to the keyword documentation for SORT.

SAP AG

TAW10

10-40

Internal Tables in Debugging Mode


X ABAP Debugger
Watchpoint Table

SAP a
chws chws

Table
LOOP AT it_flightinfo INTO wa_flightinfo. 4 WRITE: / wa_flightinfo-carrid, wa_flightinfo-connid, it_flightinfo Internal table Double-click the data object
Variant

Fixed point arithmetic 15 30 5

Type STANDARD
... PERCENTAGE

CARRID

CONNID

FLDATE

it_flightinfo

SY-SUBRC SAP AG 2001

1 2 3 4 5 6 7 8

AA AA AA AA LH LH LH LH

0017 0017 0017 0017 0400 0400 0400 0400

20000512 20000724 20000828 20001224 20000626 20000715 20001113 20001212

... ... ... ... ... ... ... ...

66 120 560 470 240 123 273 280

You can trace the line contents of an internal table by entering the name in the left column. To see the table display, double -click this entry.

SAP AG

TAW10

10-41

Basic ABAP Language Elements: Unit Summary

You are now able to: l Define elementary and structured data objects l Use basic ABAP statements l Execute and analyze programs in debugging mode

SAP AG 2001

SAP AG

TAW10

10-42

ABAP Language Elements Exercises


Unit: Basic ABAP Language Elements Topic: Basic ABAP Statements
At the conclusion of these exercises, you will be able to: Define elementary data objects Assign values Implement conditional branching Perform calculations Create an ABAP program for the four basic calculation types. You must be able to enter the values and arithmetic operator on a selection screen. Display the result in a list.

Program:

ZBC400_##_COMPUTE SAPBC400TSS_COMPUTE

Model solution:

## stands for the two-digit group number. 1-1 Create the executable program ZBC400_##_COMPUTE without "TOP Include". Define the input parameters for two integers (name suggestion: pa_int1, pa_int2) and an arithmetic operator (name suggestion: pa_op). Additionally, define an elementary data object for the result type: packed number with two decimal places (name suggestion: result). Execute the calculation in connection with the specified arithmetic operator. Use the CASE statement to do this.

1-2

1-3

1-4 1-5

Display the result in a list. If the user has specified an invalid arithmetic operator on the selection screen, write an appropriate statement on the list screen.. Use the IF statement to do this.

SAP AG

TAW10

10-43

1-6

If the user tries to divide by zero, display an appropriate statement on the list screen. In a later unit you will learn how you can implement the error handling with a more elegant user dialog.

SAP AG

TAW10

10-44

Exercises
Unit: Basic ABAP Language Elements Topic: Working with Structures
At the conclusion of these exercises, you will be able to: Use the Debugger to trace the data flow and understand the connections between processing blocks. Use the MOVE-CORRESPONDING statement to assign values between structures. You have to examine a specified ABAP program to ascertain when and how certain data is transported between certain structured data objects.

Program:

SAPBC400WBS_GETTING_STARTED

2-1

Start the program SAPBC400WBS_GETTING_STARTED. On the selection screen, enter the airline code LH. In the command field, enter '/h' and then execute the program. You are now in debugging mode. Make sure that all of the data objects are initial. Transfer all of the data objects defined in the program to the field view. Find out about the structure and type of the individual components. Step through the program, one statement at a time, by choosing Single step (F5). Which fields of the structure wa_scarr does the SELECT statement fill? What is the value of system field sy-subrc after the statement? Now observe how fields are copied from the structure wa_scarr to the structure sbc400_carrier. Which field values are copied? The statement CALL SCREEN 100 processes screen 100. On the screen, enter appropriate values for the user name, date, and time, and continue with the program. Now observe how fields are copied from the structure sbc400_carrier to the structure wa_scarr. Finally, observe how the WRITE statement constructs the list.

2-2

2-3

2-4

2-5

2-6

SAP AG

TAW10

10-45

After the first WRITE statement, an extra button appears in the application toolbar, which allows you to display the current contents of the list buffer at any time.

2-7

Restart the program in Debugging mode. Set a breakpoint at the MOVECORRESPONDING statement. Before the screen is processed, assign a name to the structure component sbc400_carrier-uname in the Debugger. The button used to change the field values at runtime is next to the input/output field.

2-8

Repeat step 2-1. Now set a breakpoint at the CALL SCREEN statement. Additionally, set a field content-dependent watchpoint for the condition that a field value of the structure wa_scarr changes. Choose Continue (F8) to continue the program and check why the debugging of the program is stopped in each case.

SAP AG

TAW10

10-46

Exercises
Unit: Basic ABAP Language Elements Topic: Working with Internal Tables
At the conclusion of these exercises, you will be able to: Search for suitable table kinds in the ABAP Dictionary Define internal tables based on a global table kind Fill internal tables using array fetch Process the content of internal tables using a loop. Create an ABAP program that lists additional information on all existing flight departure times. Get the data from the database table SPFLI. Program: ZBC400_##_ITAB_LOOP SAPBC400TSS_ITAB_LOOP

Model solution:

## stands for the two-digit group number. 3-1 Create the executable program ZBC400_##_ITAB_LOOP without "TOP-Include". Buffer the data from the database table SPFLI in an internal table. Define an internal table with a line type that is compatible with the line structure of SPFLI. In the ABAP Dictionary, search for all internal table kinds that match this condition. (Use the Where-used list in the ABAP Editor.)

3-2

3-3

Define an internal table (name suggestion: it_spfli) based on one of the global table types you have found. Define a work area that corresponds to the internal table (name suggestion: wa_spfli). Program an array fetch access to all the data records in the database table SPFLI: SELECT * FROM spfli INTO TABLE it_spfli.

3-4

3-5

SAP AG

TAW10

10-47

3-6

Display the buffered data in a list. Use the LOOP statement to do this.

SAP AG

TAW10

10-48

ABAP Language Elements Solutions


Unit: Basic ABAP Language Elements Topic: Basic ABAP Statements

Model solution:

REPORT sapbc400tss_compute. PARAMETERS: pa_int1 TYPE i, pa_op(1) TYPE c, pa_int2 TYPE i. DATA result TYPE p DECIMALS 2.

IF NOT ( pa_op = '+' OR pa_op = '-' OR pa_op = '*' OR pa_op = '/' ). WRITE: 'Invalid operator!'(iop). ELSEIF pa_op = '/' AND pa_int2 = 0. WRITE: 'Division by zero!'(dbz). ELSE. CASE pa_op. WHEN '+'. result = pa_int1 + WHEN '-'. result = pa_int1 WHEN '*'. result = pa_int1 * WHEN '/'. result = pa_int1 / ENDCASE. WRITE: 'Result:'(res), ENDIF.

pa_int2. pa_int2. pa_int2. pa_int2. result.

SAP AG

TAW10

10-49

Solutions
Unit: Basic ABAP Language Elements Topic: Working with Structures

2-3

Which components are filled by the SELECT statement C? mandt, carrid, carrname, currcode, url. What is the value of the system field sy-subrc after the SELECT statement? Because there is a data record for the airline LH (Lufthansa) in the database table SCARR, sy-subrc is set to zero.

2-4

Which field values are copied? mandt, carrid, carrname, currcode.

SAP AG

TAW10

10-50

Solutions
Unit: Basic ABAP Language Elements Topic: Working with Internal Tables

Model solution:

REPORT sapbc400tss_itab_loop. DATA: it_spfli TYPE sbc400_t_spfli. DATA: wa_spfli TYPE spfli.

SELECT * FROM spfli INTO TABLE it_spfli. * at least one dataset selected IF sy-subrc = 0. * move each single dataset from internal table to * structure WA_SPFLI in order to write data on list LOOP AT it_spfli INTO wa_spfli. WRITE: / wa_spfli-carrid, wa_spfli-connid, wa_spfli-cityfrom, wa_spfli-cityto, wa_spfli-deptime, wa_spfli-arrtime. ENDLOOP. ENDIF.

SAP AG

TAW10

10-51

Data Retrieval

Contents:
l Data Retrieval for Database Tables l Querying the Database l Reading Database Tables l Authorization Checks l Preview

SAP AG 2001

SAP AG

TAW10

11-1

Data Retrieval: Unit Objectives

At the conclusion of this unit, you will be able to: l List various ways of finding database tables l Program read access to specific columns and lines within a particular database table l Implement authorization checks l List the read access options for multiple database tables

SAP AG 2001

SAP AG

TAW10

11-2

Querying the Database

ABAP program Data objects pa_car wa_scarr ABAP Processing block SELECT SELECT ... FROM scarr Open SQL DatabaseDatabasespecific conversion conversion Database interface ABAP runtime system Database SQL Database table SCARR

SAP AG 2001

n n

Open SQL statements are a subset of Standard SQL that is fully integrated in the ABAP language. (SQL stands for standard query language.) Open SQL statements allow you to access the database in a uniform way from your programs, regardless of the database system installed. The database interface converts Open SQL statements to database-specific SQL statements.

SAP AG

TAW10

11-3

Searching for Database Tables

Searching within a particular application component: Application hierarchy. Searching using a program : l Search in the ABAP Editor for the SELECT statement l Change to debugging mode during program execution and set breakpoint in the SELECT statement l If the program transmits a screen, display the structure field using F1 and technical information or navigate directly to the data element (double-click), or go directly to the data element (by double-clicking it) and open the where-used list in the tables

SAP AG 2001

n n

You can search for database tables via the Application Hierarchy or the Repository Information System. If you have the name of a program that accesses the database table you are searching for: Debugger: Start this program in debugging mode and set a breakpoint at the SELECT statement. ABAP Editor: Search for the SELECT statement in the source text. If you know a program that contains a screen with input fields connected to the table you are looking for, choose F1 Technical info. Double-click the technical name of the screen field to go to the ABAP Dictionary. This is often a structure field. Double -click the data element and then use the where-used list to search for transparent tables with the field type

SAP AG

TAW10

11-4

Reading Database Tables

Reading Reading Database Database Tables Tables Authorization Authorization Checks Checks Preview Preview

SAP AG 2001

SAP AG

TAW10

11-5

Programming Database Read Access

Which columns? SELECT <result>

FROM <table>

Which table(s)?

INTO <target> WHERE <condition>

Whereto? Which lines?

Single line

}
Particular column

Multiple lines

SAP AG 2001

n n

To program database read access, use the Open SQL statement SELECT. The SELECT statement contains a series of clauses, each of which has a different task: The SELECT clause describes, among other things, whether the result of the selection will be several lines or a single data record and which fields of the table are to be read. The FROM clause names the source (database table or view) from which the data is to be selected. The INTO clause determines the internal data objects into which the selected data is to be placed.

The WHERE clause specifies the conditions that the selection results must fulfill. It thus determines the lines to be selected from the table. For information about other clauses, refer to the keyword documentation for SELECT.

SAP AG

TAW10

11-6

Reading by Single Record Access

pa_car wa_scarr Database table SCARR

SINGLE * SELECT SINGLE FROM scarr INTO INTO wa_scarr WHERE WHERE carrid = pa_car. WHERE IF sy-subrc = 0. ... Database interface

SAP AG 2001

n n

n n

The SELECT SINGLE* statement allows you to read a single record from the database table. To ensure that you read a unique entry, all of the key fields must be filled by the WHERE clause. The asterisk * after SINGLE tells the database interface to read all columns in that line of the database table. If you want only a specific selection of columns, you can list the required fields instead. In the INTO clause, enter the destination where the database interface is to copy the data. The target area should be structured left justified just like the required columns of the database table. If you use the CORRESPONDING FIELDS OF addition in the INTO clause, you can fill the target area component by component. The system fills only those components that have identical names to columns in the database table. Note: If you do not use this addition, the system fills the target area left justified, irrespective of its structure. If the system finds a table entry matching your conditions, SY-SUBRC has the value zero (0). The SINGLE addition tells the database that only one line needs to be read. The database can then terminate the search as soon as it has found that line. Therefore, SELECT SINGLE produces better performance for single -record access than a SELECT loop if you supply values for all key fields

SAP AG

TAW10

11-7

Reading Several Lines Using a Loop

pa_car wa_sbc400focc

Database table SFLIGHT

SELECT SELECT carrid connid fldate seatsocc seatsmax FROM sflight INTO wa_sbc400focc WHERE carrid = pa_car.
Statements for every record read

ENDSELECT ENDSELECT. IF sy-subrc = 0. ...

Database interface

SAP AG 2001

n n n n

n n

If you do not use the addition SINGLE with the SELECT statement, the system reads multiple records from the database. The field list determines the columns whose data is to be read from the database. The number of requested lines to be read can be restricted using the WHERE clause. In the WHERE clause you may enter only the field names of the database table. The name of the database table you want to access is found in the FROM clause. Multiple logical conditions can be added to the WHERE clause using AND, NOT or OR statements. The database delivers data to the database interface in packages. The ABAP runtime system copies the data records to the target area line by line using a loop. It also enables sequential processing of all the statements between SELECT and ENDSELECT. After the ENDSELECT statement, you can check the return code for the SELECT loop. sy-subrc will have the value zero (0) if the database interface has found at least one record. After the ENDSELECT statement, sy-dbcnt contains the total number of lines read.

SAP AG

TAW10

11-8

Reading Several Lines Using an Array Fetch

pa_car itab_focc

Database table SFLIGHT

SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO TABLE itab_focc WHERE carrid = pa_car.

IF sy-subrc = 0. ...

Database interface

SAP AG 2001

n n n n

The addition INTO TABLE itab causes the ABAP runtime system to copy the contents of the database interface directly to the internal table itab. This is called an array fetch. Since the array fetch is not executed as a loop, do not program any ENDSELECT statement. If you want to add lines to the end of an internal table that is already filled, instead of overwriting it, use the APPENDING TABLE itab addition. sy-subrc has the value 0 if the system was able to read at least one record.

SAP AG

TAW10

11-9

INTO Clause: Target Structure Suitable for Field List


ABAP program DATA wa_sbc400focc TYPE sbc400focc. SELECT SINGLE carrid connid connid fldate fldate seatsmax seatsmax seatsocc seatsocc FROM sflight INTO wa_sbc400focc wa_sbc400focc WHERE carrid = pa_car AND connid = pa_con AND fldate = pa_date. Same type as column read wa_sbc400focc

SAP AG 2001

The program must contain a data object with a suitable type for each column that is required from a database table. For program maintenance reasons, you must use the corresponding Dictionary objects to assign types to the data objects. The INTO clause specifies the data object into which you want to place the data from the database table. You can use the INTO clause in two different ways: Using a flat structure You define a structure in your program that has the same fields in the same sequence as the field list in the SELECT clause. You can enter the name of the structure in the INTO clause. The contents are copied left justified. The field names of the structure are disregarded here. Using individual data objects You can enter a set of data objects in the INTO clause. For example: DATA: gd_carrid TYPE sflight-carrid, gd_connid TYPE sflight-connid, gd_fldate TYPE sflight-fldate, gd_seatsmax TYPE sflight-seatsmax, gd_seatsocc TYPE sflight-seatsocc. START-OF-SELECTION. SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO (gd_carrid, gd_connid, gd_fldate, gd_seatsmax, gd_seatsocc) WHERE ...

SAP AG

TAW10

11-10

INTO Clause: Same-Name Fields of Field List in the Target Structure


ABAP program DATA wa_sdyn_conn TYPE sdyn_conn. SELECT SINGLE carrid connid deptime FROM spfli wa_sdyn_conn INTO CORRESPONDING FIELDS OF wa_ wa _sdyn sdyn_ _conn WHERE carrid = pa_car AND connid = pa_con. Same type as column read mandt carrid connid ... deptime

MANDT CARRID CONNID


SAP AG 2001

...

DEPTIME

n n

If you use the INTO CORRESPONDING FIELDS clause, the data is placed in the fields with the same name in the target structure. Advantages of this construction: The target structure does not have to be structured left justified in the identical way as the field list. This construction is easy to maintain, because extending the field list does not require other changes to the program, as long as there is a field in the target structure that has the same name and type. To place data in internal table columns of the same name using an array fetch, use the INTO CORRESPONDING FIELDS OF TABLE itab statement.

SAP AG

TAW10

11-11

Selecting Data From Client-Specific Tables

Logged on in client 400:

SELECT * FROM spfli INTO ... WHERE carrid = 'AA'. ... ENDSELECT. SELECT * FROM spfli CLIENT SPECIFIED INTO ... WHERE mandt IN (401, 402) AND carrid EQ 'AA'. ... ENDSELECT.

Transparent table SPFLI MANDT 400 400 ... ... 401 401 ... ... 402 402 CARRID AA AA ... ... AA AA ... ... AA AA CONNID 0017 0064 ... ... 0017 0064 ... ... 0017 0064 CITYFROM NEW YORK FRANKFURT ... ... NEW YORK FRANKFURT ... ... NEW YORK FRANKFURT

SAP AG 2001

n n

n n

With client-specific database tables, the first keyword must always be MANDT or client (data type CLNT). If you select data from client-specific tables, the system always reads the data records of the logon client, unless otherwise specified. (The ABAP runtime system automatically converts the SELECT statement.) If you wish to explicitly include the client field in the WHERE clause, you must set the CLIENT SPECIFIED addition after the FROM clause. Since this special case is not relevant for this course, the client field is generally omitted from the graphics.

SAP AG

TAW10

11-12

Performance: Secondary Index


... SELECT * FROM spfli INTO ... WHERE cityfrom = 'FRANKFURT'. ...

Secondary index
CITYFROM BERLIN BERLIN ... FRANKFURT FRANKFURT FRANKFURT FRANKFURT ... NEW YORK NEW YORK ...
SAP AG 2001

Transparent table SPFLI


CARRID AA AA ... ... LH LH ... ... UA UA ... CONNID 0017 0064 ... ... 0400 0402 ... ... 0941 3504 ... CITYFROM NEW YORK FRANKFURT ... ... FRANKFURT FRANKFURT ... ... FRANKFURT SAN FRANCISCO ... CITYTO SAN FRANCISCO NEW YORK ... ... NEW YORK NEW YORK ... ... SAN FRANCISCO FRANKFURT ...

n n

When you go to the definition of a database table in the ABAP Dictionary, you will see information on all the technical attributes of the database table. The following information is useful for improving the performance of database accesses: Key fields If the lines requested from the database are retrieved according to key fields, the Database Optimizer can perform access using a primary index. Secondary index If the lines requested from the database are retrieved according to fields, the Database Optimizer can perform access using a secondary index. Secondary indexes are displayed in a dialog box whenever you select Indexes. You choose an index from the dialog box by double-clicking it. The system then displays a screen with additional information about that index.

SAP AG

TAW10

11-13

Authorization Checks

Reading Reading Database Database Tables Tables Authorization Authorization Checks Checks Preview Preview

SAP AG 2001

SAP AG

TAW10

11-14

Authorization Checks in ABAP Programs

User master records Selection screen AUTHORITY CHECK BC400-00 Profile 1 Profile 2

Note

No

SY-SUBRC = 0 ?

Yes
SELECT

Profile S_CARRID Authorization for authorization object S_CARRID Authorization for authorization object S_CARRID Profile 4 Authorization for authorization object S_TCODE

SAP AG 2001

You should program an authorization check before accessing the database. The AUTHORITYCHECK statement first checks whether the user has the authorization containing all the required values. After the authorization check is completed, check the return code. If it is 0, the user has the required authorization and the program can be continued. If the value is not 0, the user does not have the required authorization and you should issue an appropriate message. Later in this course, you will learn how to make fields on the selection screen ready for input again if you perform the authorization check right after the selection screen and how to send a message if the user does not have the required authorization

SAP AG

TAW10

11-15

Authorization Objects and Authorizations

"Display" authorization for object S_CARRID

*
Object S_CARRID
CARRID (Airline) ACTVT (Activity) "Change" authorization for object S_CARRID LH
= = = 01 02 03

03

Activities: Create Change Display

02

SAP AG 2001

n n

All data in the SAP system must be protected from unauthorized access by users who do not explicitly have permission to access it. The system administrator assigns user authorizations when maintaining user master data. During this process, you should determine exactly which data users are allowed to access and what kind of access should be allowed. For example, you might want to allow users to display data for all airlines, but allow them to change data for only certain ones. In this case, the system must look for a combination of the activity (ACTVT) and airline carrier (CARRID) fields each time it performs an authorization check. Both fields must be filled with values during authorization creation as well (in this example, activity Change and airline carrier LH or activity Display and airline carrier *). You can ensure this by creating an authorization object composed of the ACTVT and CARRID fields that must be accessed both during the authorization assignment process and whenever your program performs an authorization check. Authorization objects simply define the combination of fields that need to be addressed simultaneously and serve as templates for both authorizations and authorization checks. They are organized into object classes to make it easier to find and manage them. One or more object classes may be assigned to each application.

SAP AG

TAW10

11-16

Syntax: Authorization Check

Authorizations for object S_CARRID

AUTHORITY_CHECK OBJECT 'S_CARRID' 'S_CARRID' Check ID 'CARRID' FIELD FIELD 'LH' 'LH' ID 'ACTVT' FIELD '02'. IF sy-subrc NE 0.
Report results

ACTVT
03 02 01 x x x x x x

Context-dependent reaction to missing authorization

ENDIF.
AA AZ DL LH UA

CARRID

SAP AG 2001

n n

When you check authorizations in programs, you specify the object and values the user needs in a particular authorization to be able to access the object in question. In the above example, there is a check to determine whether the user has authorization for the object S_CARRID, which has the value 'LH' in the CARRID field and the value '02' (change) in the ACTVT field. The abbreviations for the possible activities are documented in the table TACT and also in the appropriate authorization objects. The AUTHORITY-CHECK statement executes the authorization check for the user master record and also issues the return code. When evaluating the return code, you can specify the consequences of lacking authorization (for example, program terminates or skips some input lines).

SAP AG

TAW10

11-17

Implementing Authorization Checks


Pattern
Insert pattern ... ... AUTHORITY_CHECK S_CARRID ... ...

AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD '__________' ID 'ACTVT' FIELD '__________'. IF SY-SUBRC sysy- subrc NE NE 0. 0. 0. IF ENDIF.
SAP AG 2001

Insert values

Evaluate return code

You must specify all fields of the object in an AUTHORITY-CHECK statement; otherwise you receive a return code not equal to zero. If you do not want to carry out a check for a particular field, enter DUMMY after the authorization field. Example: When a change transaction is called, it is a good idea to check whether the user may change the entries for a particular airline: AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' DUMMY ID 'ACTVT' FIELD '02'. The most important return codes for AUTHORITY-CHECK are: - 0: The user has authorization containing the required values. - 4: The user does not have the required authorization. - 8: The check was not successful because not all fields of the authorization object were specified. The keyword documentation for AUTHORITY-CHECK contains a complete list of The check was not successful because not all fields of the authorization object were specifiedreturn codes.

SAP AG

TAW10

11-18

Preview

Reading Reading Database Database Tables Tables Authorization Authorization Checks Checks Preview Preview

SAP AG 2001

SAP AG

TAW10

11-19

Reading Linkable Database Tables


Which database tables should be taken into account? Which Whick link condition should apply to a common line?

SPFLI and SCARR

spfli-mandt = scarr-mandt spfli-carrid = scarr-carrid

SPFLI
MANDT CARRID CONNID

SCARR
CITYFROM

... ... ... ...

... ... ... ...

MANDT CARRIDCARRNAME

... ... ... ...

Which Which columns columns are to be read, and from which database table? spfli-mandt spfli-carrid
SAP AG 2001

spfli-connid spfli-cityfrom scarr-carrname

You can access several database tables using one database query, if the databse tables are logically related. To do so, you must specify the following information: Which database tables should be accessed? What should the link condition look like? In the graphic, columns from both database tables are linked. If all the field values of the linked columns match, a record is placed in a common line in the results table. Which columns are to be read? If a column appears in more than one database table, you must specify the table from which this column is to be read.

SAP AG

TAW10

11-20

Dictionary View and ABAP Join


Link in the Dictionary

ABAP Dictionary View

Link in the Program ABAP program


Link in the ABAP program using ABAP Join

SELECT SELECT

...

FROM FROM spfli INNER JOIN scarr ON spfli~carrid = scarr~carrid WHERE ...
SAP AG 2001

You can define the link conditions either statically or dynamically. You define a static link or view in the ABAP Dictionary. There are several kinds of views. You can find information about views in the SAP Library under Basis Components ABAP Workbench BC ABAP Dictionary Views. You implement a dynamic link or an ABAP join using ABAP statements. The system generates an appropriate database query in the database interface at run time. For more information, see the keyword documentation for the SELECT statement.

SAP AG

TAW10

11-21

Preview: Reusable Components for Data Retrieval

Object

Global class methods

BAPIs

Business Object

ce rfa on e t In ncti le Fu odu m Function group

Logical Database

SAP AG 2001

n n

If reusable components that encapsulate complex data retrieval statements are available, you should use them. There are four techniques for reusing data retrieval components:. Calling methods of global classes Calling methods of business objects Calling function modules Including logical databases Logical databases are data retrieval programs that return logicallyconnected data in a hierarchical sequence. You can find information on these techniques in the appropriate units. For detailed information on how to include logic al databases, refer to the SAP Library under: Basis Components ABAP Programming and Runtime Environment ABAP Database Accesses Logical Databases.

SAP AG

TAW10

11-22

Preview: Database Accesses Initiating Changes

INSERT UPDATE SELECT DELETE MODIFY

SAP AG 2001

n n n n

In addition to the SELECT statement, Open SQL contains the UPDATE, INSERT, DELETE, and MODIFY statements. Do not use these data base accesses, which initiate changes in the database, unless you understand the SAP transaction concept. All Open SQL statements support the return code sy-subrc. If a database access was successful, the return code in the system field sy-subrc is 0; if it was not successful, the return code is not 0. For more information about Open SQL statements, refer to the respective keyword documentation.

SAP AG

TAW10

11-23

Data Retrieval: Summary

Now you are able to: l List various ways of finding database tables l Program read access to specific columns and lines within a particular database table l Implement authorization checks l List the read access options for multiple database tables

SAP AG 2001

SAP AG

TAW10

11-24

Data Retrieval Exercises


Unit: Data Retrieval Topic: Reading Several Records Using a Loop
At the conclusion of these exercises, you will be able to: Program loop database accesses Limit the quantity of selected data in accordance with an input parameter Enhance your ABAP program to issue flight schedules so that only the schedules of the airline carriers selected by the user are displayed. The list should also include the percentage occupancy of each flight scheduled. Template: ZBC400_##_GS_LIST or SAPBC400WBS_GS_LIST Program: ZBC400_##_SELECT_SFLIGHT SAPBC400DDS_SELECT_SFLIGHT

Model solution:

## stands for the two-digit group number.

1-1

Copy your executable program ZBC400_##_GS_LIST (solution for exercise 2 in unit 3, Introduction to the ABAP Workbench) or the template SAPBC400WBS_GS_LIST to the new name ZBC400_##_SELECT_SFLIGHT. Change the work area type name (name suggestion: wa_flight). Now use the global structure SBC400FOCC. Find out information on the components (fields) of this structure. Define an input parameter for the airline abbreviation. Now select only the flights from the database table SFLIGHT that belong to the selected airline. Select only those fields that have a target field in the work area. Within the loop statement, calculate the percentage occupancy for each flight. Assign the result to the PERCENTAGE field in your work area. Extend your list output to include the percentage occupancy.

1-2

1-3 1-4

1-5

1-6

SAP AG

TAW10

11-25

1-7

What is the first key field in the transparent table SFLIGHT? What is the first key field in your WHERE clause? Does the database interface still use the primary index?

SAP AG

TAW10

11-26

Exercises
Unit: Data Retrieval Topic: Filling and Sorting an Internal Table
At the conclusion of these exercises, you will be able to: Fill an internal table with data by appending data records Sort the content of an internal table Enhance your ABAP program for the output of flight departure times so that the flights appear in the list sorted by percentage occupancy. For this purpose, append the read data records for the selected airline carrier to an internal table. Template: ZBC400_##_SELECT_SFLIGHT or SAPBC400DDS_SELECT_SFLIGHT Program: ZBC400_##_SELECT_SFLIGHT_ITAB SAPBC400DDS_SELECT_SFLIGHT_TAB

Model solution:

## stands for the two-digit group number. 2-1 Copy your executable program ZBC400_##_SELECT_SFLIGHT (solution for exercise 1 in this unit) or the template SAPBC400DDS_SELECT_SFLIGHT to the new name ZBC400_##_SELECT_SFLIGHT_ITAB. Define an internal table (name proposal: it_flight) using a global table type as a basis that has the global structure SBC400FOCC as line type. Use the Where-used list in the ABAP Dictionary to find a suitable table type.

2-2

2-3

Fill this internal table line by line by using an INSERT statement in the SELECT loop. (Remove the statements for list output. You can use the source text again later.) Sort the internal table by percentage occupancy and display the contents of the internal table in a loop on a list.

2-4

SAP AG

TAW10

11-27

Exercises
Unit: Data Retrieval Topic: Authorization Check
At the conclusion of these exercises, you will be able to: Implement authorization checks Set up the program flow in a variable manner depending on the outcome of the authorization check Enhance your ABAP program so that the flights can be read and displayed only if the user has display authorization for the selected airline.

Templates: ZBC400_##_SELECT_SFLIGHT and ZBC400_##_SELECT_SFLIGHT_ITAB SAPBC400DDS_SELECT_SFLIGHT and SAPBC400DDS_SELECT_SFLIGHT_TAB Programs : ZBC400_##_AUTHORITY_CHECK and ZBC400_##_AUTHORITY_CHECK_2 Model solutions: SAPBC400DDS_AUTHORITY_CHECK and SAPBC400DDS_AUTHORITY_CHECK_2 ## stands for the two-digit group number. 3-1 Copy your executable programs ZBC400_##_SELECT_SFLIGHT (solution for exercise 1 in this unit) and ZBC400_##_SELECT_SFLIGHT_ITAB (solution for exercise 2 in this unit) or the templates SAPBC400DDS_SELECT_SFLIGHT and SAPBC400DDS_SELECT_SFLIGHT_TAB to the new names ZBC400_##_AUTHORITY_CHECK and ZBC400_##_AUTHORITY_CHECK_2. Program an authorization check for the authorization object S_CARRID . Check the combination of selected airline and activity Display. Use the respective Pattern statement in the ABAP Editor. Search for the correct abbreviation of the activity to be checked. 3-3 Define a constant for the abbreviation of the activity Display (name proposal actvt_display). Use ACTIV_AUTH for typing the data element and use this constant during the authorization check.
TAW10 11-28

3-2

SAP AG

3-4

Execute the database access only if the user has display authorization for the selected airline. If this is not the case, display an appropriate error message on the list. Execute your programs; select the airline abbreviations ."AA" and "UA".

3-5

SAP AG

TAW10

11-29

Data Retrival Solutions


Unit: Data Retrieval Topic: Reading Several Records Using a Loop

1-2

The global structure SBC400FOCC has the following components: CARRID with type S_CARR_ID CONNID with type S_CONN_ID FLDATE with type S_DATE SEATSMAX with type S_SEATSMAX SEATSOCC with type S_SEATSOCC PERCENTAGE with type S_FLGHTOCC. The MANDT field in SFLIGHT is marked as a key field. The WHERE condition does not need this field. Despite this fact, the database interface can use the primary index in this case for selecting the data records. Reason: When the ABAP runtime system accesses a client-specific table, it assumes that data should be taken into account only if it belongs to the client under which the user is logged on. Thus, by default, the database interface enhances the WHERE condition with a WHERE mandt = sy-mandt condition.

1-7

SAP AG

TAW10

11-30

Model solution:

REPORT

sapbc400dds_select_sflight

DATA: wa_flight TYPE sbc400focc, PARAMETERS: pa_car TYPE s_carr_id.

* Select all datasets from database table SFLIGHT * corresponding to carrier PA_CAR: SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. * Calculate occupation of each flight: wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. * Create List: WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate, wa_flight-seatsmax, wa_flight-seatsocc, wa_flight-percentage, '%'. ENDSELECT.

SAP AG

TAW10

11-31

Solutions
Unit: Data Retrieval Topic: Filling and sorting an internal table

Model solution:

REPORT sapbc400dds_select_sflight_tab. DATA: wa_flight TYPE sbc400focc, it_flight TYPE sbc400_t_sbc400focc. PARAMETERS: pa_car TYPE s_carr_id. * select all datasets from database table SFLIGHT * corresponding to carrier SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. * calculate occupation of each flight wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. * append single line into internal table INSERT wa_flight INTO TABLE it_flight. * alternatively, you could use the APPEND statement, * if you are using standard tables: * * APPEND wa_flight TO it_flight. ENDSELECT. * sort internal table SORT it_flight BY percentage. * create list from sorted internal table LOOP AT it_flight INTO wa_flight. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate, wa_flight-seatsocc, wa_flight-seatsmax, wa_flight-percentage,'%'. ENDLOOP.

SAP AG

TAW10

11-32

Solutions
Unit: Data Retrieval Topic: Authorization Checks

Model solution:

REPORT sapbc400dds_authority_check. CONSTANTS actvt_display TYPE activ_auth VALUE '03'. DATA wa_flight TYPE sbc400focc. PARAMETERS pa_car TYPE s_carr_id. * authority-check: * Is user authorized to display data for carrier PA_CAR? AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' FIELD actvt_display. CASE sy-subrc. * user is authorized WHEN 0. SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. WRITE: / wa_flight-carrid COLOR COL_KEY, wa_flight-connid COLOR COL_KEY, wa_flight-fldate COLOR COL_KEY, wa_flight-seatsocc, wa_flight-seatsmax, wa_flight-percentage,'%'. ENDSELECT. * user is not authorized or * other error of authority-check WHEN OTHERS. WRITE: / 'Authority-Check Error'(001). ENDCASE. (REPORT sapbc400dds_authority_check_2 analog).

SAP AG

TAW10

11-33

Internal Program Modularization with Subroutines

Contents:
l Defining Subroutines l Interface Parameters l Visibility l Calling Subroutines l Subroutines in Debugging Mode

SAP AG 2001

SAP AG

TAW10

12-1

Internal Program Modularization with Subroutines: Unit Objectives

At the conclusion of this unit, you will be able to: l Define subroutines l Call subroutines l Analyze the execution of subroutines in debugging mode

SAP AG 2001

SAP AG

TAW10

12-2

Calls and Interfaces


ABAP program Actual parameters Total seats 200 Occupied seats 60 Percentage occupied 30.00

PERFORM ...

PERFORM ...

Inquiries 1000

Bookings 555

Sales ratio 55.50

FORM ...

Interface Interface Formal parameters

* .................... calculate percentage ... ENDFORM.

Subroutine

SAP AG 2001

A subroutine is an internal module within a program. In a subroutine, you lift parts of a program out of the main programming block and put them somewhere else. This makes your program easier to read and allows you to use these code segments more than once. You can pass data to the subroutine and back through its interface. This allows you to call the same function for different data objects. The example in the graphic shows a subroutine that calculates a percentage. This subroutine is called several times, even though different data objects are passed to the interface in each case. Using subroutines makes your program more function oriented: it splits the program's task into subfunctions so that each subroutine is responsible for one subfunction. This generally makes programs easier to maintain. In the Debugger, you can execute the subroutines in background so that you see only the result. This usually makes it easier to find the source of the error. The structure of a subroutine includes the following: Each subroutine starts with FORM and ends with ENDFORM. The name of the subroutine is followed by the interface definition.

n n

The statements that the subroutine executes come between FORM and ENDFORM.

SAP AG

TAW10

12-3

Ways of Passing Interface Parameters

Call-by-value

Call-by-reference

Call-by-value-and-result

Passes a value Passes an address Passes and returns a value

SAP AG 2001

You specify how the data is passed from the main program (actual parameters ) to the subroutine (formal parameters ) in the interface of the subroutine. You can do this in three ways : Call-by-value A local copy of the actual parameter is passed to the subroutine. This means that value assignments to the formal parameter have absolutely no effect on the actual parameter. Call-by-reference A dereferenced address of the actual parameter is passed to the subroutine. This means that value assignments to the formal parameter directly affect the actual parameter. The value of the actual parameter is physically changed by the subroutine through the address. Call-by-value -and-result A local copy of the actual parameter is passed to the subroutine and a value is passed back to the main program only if the ENDFORM statement is executed. This means that value assignments to the formal parameter affect the actual parameter only after they have left the subroutine . Choose this option if you want to make sure that the actual parameter is not changed if the subroutine is terminated prematurely.

SAP AG

TAW10

12-4

Passing Interface Parameters: Syntax

PERFORM subroutine_name USING a1 CHANGING a2 a3. a1 a2 a3

f1

f2

f3

FORM subroutine_name USING value value(f1) ( ) ... CHANGING CHANGING f2 ... value( value ( ) ... . value(f3) ... ENDFORM.

SAP AG 2001

In the interface definition, you list the formal parameters of the different sorts and assign a type to each one. The sequence of parameters is fixed: first you name all the USING parameters, then you name all the CHANGING parameters. Within the subroutine, you address the data that has been passed using the formal parameters. The actual parameters are grouped by USING and CHANGING when the subroutine is called. You specify the way in which the parameters are to be passed in the interface definition: Call-by-value (f1) You list these parameters after the USING keyword and complete them with the value(f1) addition. Call-by-reference (f2) You list these parameters after the CHANGING keyword. (For documentation purposes, you can also list a pass-by-reference parameter after USING. Technically, USING and CHANGING have exactly the same effect. (However, if you change a parameter listed after USING in the subroutine, you receive a warning in the Extended Program Check.) Call-by-value -and-result (f3) You list these parameters after the CHANGING keyword and complete them with the value(f3) addition

n n

SAP AG

TAW10

12-5

Interface Parameters: Specified and Inherited Types


TYPES t_perc TYPE p DECIMALS 2. DATA: a1 TYPE ..., a2 TYPE ..., a3 TYPE ... . ... PERFORM calc_perc USING a1 a2 CHANGING a3. DATA: a1 TYPE ..., a2 TYPE ..., a3 TYPE ... . ... PERFORM calc_perc USING a1 a2 CHANGING a3.

Specified type FORM calc_perc USING value(f_part) TYPE i value(f_all) TYPE i CHANGING value(f_pc) TYPE TYPE t_perc. t_perc t_perc CHECK f_all <> 0. f_pc = f_part * 100 / f_all. ENDFORM.
SAP AG 2001

Inherited type FORM calc_perc USING value(f_part) TYPE ANY value(f_all) TYPE ANY CHANGING value(f_pc) TYPE ANY. CHECK f_all <> 0. f_pc = f_part * 100 / f_all. ENDFORM. Risk of type conflicts

The data objects passed to a subroutine (that is, the actual parameters) can be of any type . If you use elementary types, you can decide whether or not you want to specify the type of the formal parameters. By specifying the type of the formal parameters, you ensure that only actual parameters of that type can be passed to the subroutine. This makes your program more stable because the syntax check will find any type conflicts. If you use the TYPE ANY addition, you leave the type unspecified. (For compatibility reasons, you can also omit this addition.) In this case, the formal parameter inherits the type from the actual parameter at run time. If the statements in the subroutine are not suited to the inherited type, a runtime error may occur. If you assign the types p, n, c or x, the missing type attributes are similarly "inherited" at run time. If you want to specify a type completely, you must use a user-defined type. If you use string or xstring, the type is not fully specified until run time. Conversely, the types i, f, d, and t are fully typed.

SAP AG

TAW10

12-6

Interface Parameters: Specifying Types for Structures and Internal Tables


DATA wa_flightinfo TYPE sbc400focc. ... PERFORM fill_wa CHANGING wa_flightinfo. DATA it_flightinfo TYPE sbc400_t_sbc400focc. ... PERFORM fill_itab CHANGING it_flightinfo.

FORM fill_wa Structure type CHANGING f_wa TYPE sbc400focc sbc400focc.

Table type FORM fill_itab CHANGING f_itab TYPE sbc400_t_sbc400focc sbc400_t_sbc400focc.

f_wa-carrid = ... . f_wa-connid = ... . Address the structure components

ENDFORM.

LOOP AT f_itab ... . ... ENDLOOP. Address the parameter as an internal table ENDFORM.

SAP AG 2001

n n n n

If you use structures or internal tables as formal parameters, you must type them fully. This allows you to access these formal parameters within the subroutine. The components of structures are known in the subroutine, as a result of the assigned type, so that you can address these components with the usual syntax. If you use internal tables, the assigned type allows you to address the formal parameter as an internal table with the usual syntax. Note on performance : If you use internal tables as parameters, you should generally pass them using pass-by-reference . Otherwise, the system can use considerable resources simply copying them to the subroutine.

SAP AG

TAW10

12-7

Visibility of Global and Local Data Objects

DATA: it_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo TYPE sbc400focc, ... .

Visible globally

... PERFORM fill_itab CHANGING it_flightinfo. FORM fill_itab CHANGING f_itab TYPE sbc400_t_sbc400focc. Visible locally DATA l_wa LIKE LINE OF f_itab.

LOOP AT f_itab INTO l_wa. ... ENDLOOP. ENDFORM.


SAP AG 2001

n n

You can define local data within a subroutine. Both the formal parameters and the local data objects are active only at the run time of the subroutine. This means that memory is allocated only when the subroutine is called and is released as soon as the subroutine has been executed. Thus these parameters and data objects can be addressed only from within the subroutine. The global data objects from the main program can also be addressed from the subroutine. However, you should avoid doing this wherever possible. Otherwise, you bypass the interface, which makes the program more prone to errors. If a local data object or formal parameter has the same name as a global data object, the ABAP runtime system addresses the local data object in the subroutine and the global one outside it. These objects are then known as locally obscured objects. Summary of hints about gobal and local data objects: Address the global data objects in the main program and pass them to the subroutine using the interface. Address only formal parameters and local data objects in the subroutine. For clarity, avoid using identically named global and local variables. Instead, use a simple prefix, such as f_ for formal parameters and l_ for local data objects.

SAP AG

TAW10

12-8

Syntax Example: Passing an Internal Table


DATA: it_flightinfo TYPE sbc400_t_sbc400focc, wa_flightinfo TYPE sbc400focc, lines TYPE i. ... PERFORM count_lines USING it_flightinfo 'LH' CHANGING lines.

FORM count_lines USING

f_itab TYPE sbc400_t_sbc400focc f_carr TYPE sbc400focc-carrid CHANGING value(f_lines) TYPE i.

DATA l_wa LIKE LINE OF f_itab. CLEAR f_lines. LOOP AT f_itab INTO l_wa WHERE carrid = f_carr. ADD 1 TO f_lines. ENDLOOP. ENDFORM.
SAP AG 2001

n n n

The example in the graphic shows a main program calling a subroutine, which specifies the number of lines of an internal table needed to fulfill a specific criterion. The internal table, f_itab, and the comparison value, f_carr, are passed by reference to improve performance. The number of lines, f_lines, is passed by value-and-result. To loop through the internal table, you need a work area with a compatible line type, which you define locally in the subroutine, by making a reference to the formal parameter.

SAP AG

TAW10

12-9

Calling Subroutines
System Help

ABAP Editor: Changing the Report Z00_FORM


Z00_FORM

Subroutines COUNT_LINES

PERFORM count_lines USING f_itab + f_carr CHANGING f_lines. 2: Adapt the actual parameters FORM count_lines USING f_itab TYPE ... f_carr TYPE ... CHANGING value(f_lines) TYPE ... . ... ENDFORM.

1: "drag-and-drop"

SAP AG 2001

n n n

A subroutine is called using the PERFORM statement. When the subroutine is called, parameters are passed to it in strict sequence . For this reason, you should define the subroutine first and then call it. The Object Navigator supports you in this respect: You can generate the PERFORM statement by dragging the subroutine from the navigation area to the editor area. Alternatively, you can generate the call using the Pattern function in the ABAP Editor. This prevents you from mixing up or forgetting any parameters. However, you must remember to replace the formal parameters with actual parameters.

n n

SAP AG

TAW10

12-10

Subroutines in Debugging Mode


X ABAP Debugger
Watchpoint

SAP a
chws chws

ZJJ_KURS_000 ZJJ_FORMS

Return

Fixed point arithmetic 15 30 5

FORM count_lines USING

Execute

f_itab TYPE ... f_carr TYPE ... CHANGING value(f_lines) TYPE ... .

4 DATA l_wa LIKE LINE OF f_itab.

Variant

1 - 4

f_carr

6 LH

Variant

SY-SUBRC SAP AG 2001

SY-TABIX

SY-DBCNT

n n n

In debugging mode, you can make a subroutine run without stopping. The execution of the main program does not stop until after the subroutine has been executed. Alternatively, you can execute the subroutine statement by statement using Single Step. If the current statement is located in a subroutine, you can run the rest of the subroutine without it stopping by selecting Return (F7). Execution of the main program does not stop until after the subroutine is executed.

SAP AG

TAW10

12-11

Internal Program Modularization with Subroutines: Unit Summary

You are now able to: l Define subroutines l Call subroutines l Analyze the execution of subroutines in debugging mode

SAP AG 2001

SAP AG

TAW10

12-12

Modularization Exercises
Unit: Internal Program Modularization Topic: Subroutines

At the conclusion of these exercises, you will be able to: Create subroutines Use the subroutine interface to pass data

Change your program ZBC400_##_SELECT_SFLIGHT_ITAB (or the corresponding model solution) so that the display of the data in a list is encapsulated in a subroutine.

Template: Program:

ZBC400_##_AUTHORITY_CHECK_2 or SAPBC400DDS_AUTHORITY_CHECK_2 ZBC400_##_SUBROUTINE

Model solution: SAPBC400PBS_SUBROUTINE

1-1

Copy your program ZBC400_##_AUTHORITY_CHECK_2 or the corresponding model solution SAPBC400DDS_AUTHORITY_CHECK_2 to the new program ZBC400_##_SUBROUTINE. Encapsulate the display of data in a list in a subroutine. Call the subroutine (suggested name: WRITE_LIST) after the SELECT loop. Pass the internal table containing the data that has been read using the interface. Define the subroutine and specify types for the interface parameters. Display the data from the subroutine using a LOOP ENDLOOP structure. To do this, create the required table work area as a local data object in the subroutine. To specify the type of the local structure, use the ABAP statement DATA <wa> LIKE LINE OF <itab>.

1-2

1-3 1-4

SAP AG

TAW10

12-13

Modularization Solutions
Unit: Internal Program Modularization Topic: Subroutines

Model solution SAPBC400PBS_SUBROUTINE

*&--------------------------------------------------------------* *& Report *& SAPBC400PBS_SUBROUTINE * *

*&--------------------------------------------------------------* REPORT sapbc400pbs_subroutine.

CONSTANTS actvt_display TYPE activ_auth VALUE '03'. DATA: wa_flight TYPE sbc400focc, it_flight TYPE sbc400_t_sbc400focc. PARAMETERS: pa_car TYPE sflight-carrid.

START-OF-SELECTION. * Authority-Check: AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' CASE sy-subrc. * User is authorized WHEN 0. SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. APPEND wa_flight TO it_flight. ENDSELECT.
PERFORM write_list USING it_flight. SAP AG TAW10 12-14

FIELD actvt_display.

* User is not authorized or other error of authority-check WHEN OTHERS. WRITE: / 'Authority-Check Error'(001). ENDCASE. *&--------------------------------------------------------------* *& Form WRITE_LIST *&--------------------------------------------------------------* * * text -->P_IT_FLIGHT text *---------------------------------------------------------------* *---------------------------------------------------------------* FORM write_list USING p_it_flight TYPE sbc400_t_sbc400focc. DATA: wa LIKE LINE OF p_it_flight. LOOP AT p_it_flight INTO wa. WRITE: / wa-carrid COLOR COL_KEY, wa-connid COLOR COL_KEY, wa-fldate COLOR COL_KEY, wa-seatsocc, wa-seatsmax, wa-percentage,'%'. ENDLOOP. ENDFORM. " WRITE_LIST

SAP AG

TAW10

12-15

The ABAP Runtime System

Contents:
l Execution of Event Blocks by the ABAP Runtime System l Event Block LOAD-OF-PROGRAM (INITIALIZATION) l Event Block START-OF-SELECTION

SAP AG 2001

SAP AG

TAW10

13-1

The ABAP Runtime System: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the event-controlled processes for executing an ABAP program l Use the event block LOAD-OF-PROGRAM (INITIALIZATION) l Use the event block START-OF-SELECTION

SAP AG 2001

SAP AG

TAW10

13-2

Possible Elements in an ABAP Program

Event block Event block Selection screen

Local type and field definitions

Event block
Interface

Module

Process Before Output Process After Input

Event block

Module

Subroutine program

Screen

SAP AG 2001

An ABAP program is a collection of processing blocks. A processing block consists of passive source code sections that are processed sequentially when called. n Processing blocks are the smallest units in ABAP. They cannot be split, which also means that they cannot be nested. n There are various kinds of ABAP processing blocks: Event blocks are processing blocks that are called by the ABAP runtime system whenever the respective event is initiated. Such events can be initiated by the ABAP runtime system itself or by the user. Subroutines are processing blocks that are called by ABAP statements. The developer controls subroutines. Modules are special ABAP processing blocks that are called by screen statements. These are required for screen processing. n Whenever a program is started, all the global data objects of the program are created in the working memory first. Declarative ABAP statements are not components of ABAP processing blocks; instead, they are collected by the ABAP runtime system when the overall source code is generated. For the sake of clarity, however, you should place all declarative statements together at the beginning of the source code. Exceptions to this are local declarations within subroutines.

SAP AG

TAW10

13-3

Example: ABAP Program with Several Event Blocks and a Selection Screen

Local Type and Field Definitions PARAMETERS pa_date LIKE sy-datum [ DEFAULT sy-datum ].

Selection screen (generated by the runtime system)

LOAD-OF-PROGRAM. pa_date = sy-datum - 7. START-OF-SELECTION. WRITE pa_date.

Event block Default settings for selection screen Event block Start of list creation

SAP AG 2001

In all of the programs we have seen so far in this course, only one processing block has been programmed in addition to declarative statements. In this case, there is no need to declare the processing block explicitly. In more complex programs, however, several different processing blocks are required. The example in the graphic contains a selection screen with an input field for a date. The date of the same weekday in the previous week should appear as a default value. The PARAMETERS statement is a declarative language element. The system requires a calculation to preset the date dynamically. The DEFAULT addition to the PARAMETERS statement ensures that the data object is filled with a default value. The ABAP runtime system fills the sy-datum field with the current date at the start of the program. To change variables at run time , therefore, you must program a processing block. Because this should be processed before the standard selection screen is transmitted, use the respective event block called LOAD-OF-PROGRAM. Use the standard event block, START-OF-SELECTION, to create the list

SAP AG

TAW10

13-4

Sample Program Runtime Behavior

ABAP program Program start

pa_date

LOAD-OF-PROGRAM. pa_date = sy-datum - 7. 19991225

??? START-OF-SELECTION. WRITE pa_date.


List buffer for basic list

ABAP runtime system Time


SAP AG 2001

In the flow diagram in the graphic, you can easily follow the sequence of processing steps by the ABAP runtime system. Event blocks are called in a fixed sequence designed for list processing: The first event block to be called is LOAD-OF-PROGRAM. In the example, the date "A week ago" is calculated and placed into the pa_date input field. Next the system sends the selection screen with this new value to the presentation server. The user can change the value. Next the selection screen is sent to the presentation server. After the user leaves the selection screen, START-OF-SELECTION is called. If the START-OF-SELECTION event block contains the ABAP statements WRITE, SKIP or ULINE, a list buffer is filled. As soon as START-OF-SELECTION is processed completely, the list buffer is sent to the presentation server as a list.

Both events presented here are initiated by the ABAP runtime system exactly once each time a program is executed.

SAP AG

TAW10

13-5

Event Block Characteristics

l Introduced by an event keyword l Ended by the next processing block l Event block for different tasks l Processing sequence for event blocks is determined by the runtime system Event block sequence in source code unimportant l Standard event block in executable program:
ABAP program

PARAMETERS pa_date LIKE sy-datum [ DEFAULT sy-datum ].

LOAD-OF-PROGRAM. LOADLOAD-OFOF-PROGRAM. pa_date = sy-datum - 7.

START-OF-SELECTION. START-OF-SELECTION. WRITE pa_date.

SAP AG 2001

n n n n

An event block is introduced with an event keyword. It ends implicitly when the next processing block starts. Event blocks are called by the ABAP runtime system. Therefore, the sequence in which the event blocks are written in the program is unimportant. LOAD-OF-PROGRAM is the first event block called in all ABAP program types. This event block allows you to set default values that can only be determined at runtime. For compatibility reasons, the event block INITIALIZATION is available as an alternative. However, it is available for executable programs only. START-OF-SELECTION is the first event block for creating a list. It is called by the ABAP runtime system as soon as you leave the standard selection screen. It is available for executable programs only. In executable programs, additional event blocks are available for different tasks and are designed for creating lists. You can obtain a complete list of event blocks from the ABAP documentation: choose ABAP Overview ABAP - Overview Diagrams Classification of Keywords by Type Event keywords.

SAP AG

TAW10

13-6

The ABAP Runtime System: Unit Summary

You are now able to: l Describe the event-controlled processes for executing an ABAP program l Use the event block LOAD-OF-PROGRAM (INITIALIZATION) l Use the event block START-OF-SELECTION

SAP AG 2001

SAP AG

TAW10

13-7

User Dialog List

Contents:
l List attributes and strengths l Basic list l List events l Interactive lists l Example with syntax: Detail list

SAP AG 2001

SAP AG

TAW10

14-1

User Dialog List: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe list attributes and strengths l Write a program that displays the detail of a specific line from your basic list to an interactive list whenever the user double-clicks that particular line l Explain the runtime behavior of your program during the AT LINE-SELECTION event

SAP AG 2001

SAP AG

TAW10

14-2

List Attributes
Screen
CA ID PRICE AA 2602 2400 AA 2602 2500 Total 7800

Display languagelanguagespecific texts in logon logon language Formatted output: output: 20010821 Date Date
08/21/2001

According to fixed fixed user settings Print Formatted output: Amounts according to their currency Lengths according to their unit
SAP AG 2001

The main purpose of a list is to display data while involving a minimum amount of programming. Special business data requirements are taken into account: Lists are language-independent. Texts and headers appear in the logon language whenever a translation is available. Lists can display monetary values in numerous currencies.

The following options are available to the user for lists: Displaying on screens: you can add colors and icons Printing Publishing on Internet or intranet: The system automatically converts lists to HTML. Saving: You can save lists within the R/3 System as well as outside for further processing, for example, using spreadsheet programs

SAP AG

TAW10

14-3

Standard List Functions:

Back / Exit / Cancel Scroll Print Find (in list)


System ... : List :

Save

SAP AG 2001

The standard list interface offers the user several navigation features: Back Exit Cancel Print Find (in list) Save as a file, in the menu, or to a buffer Send the list in e-mail form You can use the Menu Painter to adjust the standard list interface to fit your individual needs.

SAP AG

TAW10

14-4

List Headers in the Default Page Header

From within the list: System ... : List :

From the ABAP Editor: Text elements Titles/headers

List header Column header

Save

SAP AG 2001

n n

Each list can have a list header and up to four lines of column headers . You can use these tools in two ways: From the ABAP Editor: Use the text element maintenance functions. A ruler is available. From the list: If you save your program, activate it, and then execute it to create the list, you can access the maintenance screen by choosing System List List header. The main advantage of using this method is that the list is still displayed on the screen. This makes it easier to position column headers. The next time you start the program, the new headers will appear in the list automatically. If no header text is entered, the program title is inserted in the header.

SAP AG

TAW10

14-5

Multilingual Capability of Lists

ABAP program Text elements


Titles/headers List header DE creation date EN creation date FR ...

WRITE: /15 texttext-001, text-001 35 sy-datum, /15 texttext-002, text-002 35 sy-uname.

Text symbols 001 DE Anlegen Datum EN Creation date FR ... : EN Created by

002

Creation date: 01/01/2001 Created by: WALTERS

SAP AG 2001

n n

Titles and headers are part of the program's text elements. You can translate all text elements into other languages. The logon language setting on the logon screen determines in which language text elements will be displayed. Text symbols are another kind of text element. Text symbols are text literals that can be translated and are assigned to the program. They are frequently used to create lists independent of language. You can write text symbols into your program in either of the following ways: TEXT-ccc (ccc is a three-byte character string) '...'(ccc)(... is any text, ccc is a three-digit character string) From the Editor, you can access the maintenance screen for the text symbols by choosing Goto Text elements Text symbols or by double-clicking the number of a text symbol.

SAP AG

TAW10

14-6

Lists in Executable Programs

Program start

ABAP program Data objects START-OF-SELECTION. SELECT ...


List buffer

Database tables

WRITE ...

ABAP runtime system


SAP AG 2001

Time

In executable programs, lists are automatically displayed after their corresponding event blocks have been processed. These processing blocks must, however, contain a statement that writes to the list buffer. These are WRITE, SKIP, and ULINE. Event blocks are called in a sequence designed for list processing: Before the selection screen: LOAD-OF-PROGRAM. After the user leaves the selection screen: START-OF-SELECTION. All output from the event blocks that create the lists (here only START-OF-SELECTION) and from the modularization units called there, which is processed before a list is sent, is temporarily stored in the list buffer. Once all list creation event blocks (here only START-OF-SELECTION) have been processed, all data from the list buffer is displayed in the form of a list.

SAP AG

TAW10

14-7

Creating Detail Lists

START-OF-SELECTION.
Basic list buffer

Database tables

AT LINE-SELECTION.
Detail list buffer

SAP AG 2001

Time

n n

In executable programs, you can use the event block AT LINE-SELECTION to create detail lists. The ABAP runtime system ensures that: The basic list is sent after the event blocks responsible for creating the basic list have been processed (for example, after START-OF-SELECTION). In this case, the system field sylsind contains the value 0. The event block AT LINE-SELECTION is processed using the function code PICK each time you double-click an entry or choose an action for the system to perform. If you are not using a user-defined status, this happens automatically every time you choose Detail list (icon looks like a magnifying glass), the menu function Choose, or the function key F2. The detail list is sent after the AT LINE-SELECTION event block is processed and the value contained in sy-lsind is increased by one. After every user action with the function code BACK, the system displays the list at the previous detail level (that is, it goes from level n to n-1 ).

SAP AG

TAW10

14-8

Detail Lists: Navigation


Basic list

Basic list sy-lsind

First detail list

Detail list sy-lsind

Detail list sy-lsind

2
Second detail list

SAP AG 2001

The lists in the example program should function as follows: The basic list should display the text Basic list and the system field sy-lsind. The user can navigate to a detail list by using any of the following: - Double-clicking on the basic list - Choosing Detail list (icon looks like a magnifying glass) in the application toolbar - Choosing a menu function - Using function key F2. The Detail list appears and the system field sy-lsind has the value 1. Repeating this action calls the second detail list, where system field sy-lsind contains the value 2 instead (representing the current detail list level). Repeating this action increases the sy-lsind value by one every time. This is possible up to the twentieth detail list. Choosing Back takes the user back one single detail list level at a time until the basic list is reached..

SAP AG

TAW10

14-9

Syntax Example: Simple Detail List

... START-OF-SELECTION. WRITE: / text-001 COLOR col_heading, / 'sy-lsind', sy-lsind color 2.

Text symbols: 001 002 Basic list Detail list

AT -SELECTION. AT LINE LINE-SELECTION. WRITE: / text-002 COLOR col_heading. ULINE. WRITE: / 'sy-lsind', sy-lsind color 4.

SAP AG 2001

A detail list is programmed as follows: You create a basic list by filling the basic list buffer at an appropriate event block (here STARTOF-SELECTION) using either WRITE, SKIP, or ULINE. Use the event block AT LINE-SELECTION when programming detail lists. Whenever you use WRITE, SKIP, or ULINE with this event block, you fill the detail list buffer for the next level (the detail list buffer with a level value one greater than the level on which the user performed the action). You can pre-determine navigation between detail lists by querying system field sy-lsind at the event block AT LINE-SELECTION.

SAP AG

TAW10

14-10

Example: Detail List

Timetable
Airl. LH LH ... SQ Flight From 0400 FRA Frankfurt 0400 FRA Frankfurt 0002 SIN JFK JFK To New York New York Departing at 10:10:00 13:30:00

Singapore SFO San Francisco 09:30:00

Detail: Flights
You have chosen LH Flight date 19.12.2001 20.12.2001 24.12.2001 0402 Max. 380 380 380 Occ. 240 270 380

SAP AG 2001

n n

You will now write a program using both basic lists and detail lists. The basic list in your program should contain flight data such as carrier ID and flight numbers, departure city and airport, destination city and airport, and departure and arrival times. This data can be found in the database table SPFLI. The user should be able to access information about any particular flight by double -clicking its carrier ID and flight number. Flight date and occupancy should be displayed. This data can be found in the database table SFLIGHT. You must use the SPFLI key fields in this detail list in order to read the appropriate data in SFLIGHT. The following graphics demonstrate how this is done. The example program is SAPBC400UDD_DETAIL_LIST and it is part of development class BC400.

SAP AG

TAW10

14-11

Buffering Global Data in the Hide Area


Current list buffer HIDE fieldname. SELECT carrid connid airpfrom airpto deptime FROM spfli INTO CORRESPONDING FIELDS OF wa_spfli.

1 2 3 4 5 5
:

CAR AA LH LH
:

ID

From

To SFO JFK JFK


:

Departing Departing at at 13:30:00 10:10:00 13:30:00


:

0017 JFK 0400 FRA 0402 FRA


: :

WRITE: /

wa_spfli-carrid, wa_spfli-connid, wa_spfli-airpfrom, wa_spfli-airpto, wa_spfli-deptime. wa_spfli-carrid, wa_spfli-connid.

Hide area Line 3 3 4 4 5 5 : Field name wa_spfli-carrid wa_spfli-connid wa_spfli-carrid wa_spfli-connid wa_spfli-carrid wa_spfli-connid : Value AA 0017 LH 0400 LH 0402 :

HIDE :

ENDSELECT. AT LINE-SELECTION.
SAP AG 2001

When the event AT LINE-SELECTION is processed, a program's data objects contain the same values as before basic list display. A detail list, however, often needs data selected within the basic list itself. You can use the HIDE area to store certain data from the line that you have selected and then automatically insert it where you need it in the corresponding data object for a detail list. To predetermine which information is classified by its line position when you create a basic list, use the ABAP keyword HIDE followed by a list of the data objects you require. The runtime system automatically records the name and contents of the data object in relation to its line position in the list currently being created. The HIDE global_field statement buffers the content of the global data field global_field with reference to the current display line. You do not have to display the field beforehand using the WRITE statement. You merely have to program the HIDE statements after the last WRITE statement in the current line. The data field can also be a flat structure.

SAP AG

TAW10

14-12

Line Selection
Hide area Line 3 3 4 4 5 5 : 14 14 Field name wa_spfli-carrid wa_spfli-connid wa_spfli-carrid wa_spfli-connid wa_spfli-carrid wa_spfli-connid : wa_spfli-carrid wa_spfli-connid Value AA 0017 LH 0400 LH 0402 : SQ 0002

CAR CAR ID ID From From AA 0017 JFK LH 0400 FRA LH 0402 FRA ... SQ 0002 SIN

To To SFO JFK JFK SFO

Departing Departing at at 13:30:00 10:10:00 13:30:00 09:30:00

?? LH 0400 ??

??

??

wa_spfli

... AT LINE LINE-SELECTION. LINE-SELECTION. WRITE: text-001, wa_spfli-carrid, wa_spfli-connid.


SAP AG 2001

Text symbols: 001 Flights for connection

n n n

When you select a line (by pointing to it followed by PICK or double -click), this triggers the event AT LINE-SELECTION. First the values for this line buffered in the HIDE area are inserted back into the corresponding global data objects . Then the system processes the relevant event block in the ABAP program.

SAP AG

TAW10

14-13

Syntax Example: Additional Data for Selected Line

... Text symbols: AT LINE LINE- SELECTION. LINE-SELECTION. IF sy-lsind = 1. WRITE: text-001, wa_spfli-carrid, wa_spfli-connid. 001 Flights for connection

SELECT fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_sflight WHERE carrid = wa_spfli-carrid AND connid = wa_spfli-connid. WRITE:/ wa_sflight-fldate, wa_sflight-seatsmax, wa_sflight-seatsocc. ENDSELECT. ENDIF.
SAP AG 2001

n n n

You create a detail list by filling the detail list buffer at the AT LINE-SELECTION event block using either WRITE, SKIP, or ULINE. In the example program, the key fields of the airline will be displayed. The flights available for this airline in the database table SFLIGHT are read using a SELECT loop. Note that the line-specific information on the airline is only available by double-clicking in the data objects if the relevant data objects have been placed in the HIDE area when the basic list was created.

SAP AG

TAW10

14-14

User Dialog List: Unit Summary

You are now able to: l Describe list attributes and strengths l Write a program that displays the details of a specific line from your basic list to an interactive list whenever the user double-clicks that particular line l Explain the runtime behavior of your program during the AT LINE-SELECTION event

SAP AG 2001

SAP AG

TAW10

14-15

User Dialog List Exercises


Unit: User Dialog List Topic: Detail Lists
At the conclusion of these exercises, you will be able to: Create a detail list in a program

Extend the program ZBC400_##_SELECT_SFLIGHT or the corresponding model solution as follows: Once the user has selected a flight on the basic list (double-click or F2 on the relevant list line), display a detail list containing all of the bookings for the selected flight. Template: Program: ZBC400_##_SELECT_SFLIGHT or SAPBC400DDS_AUTHORITY_CHECK ZBC400_##_DETAIL_LIST

Model solution: SAPBC400UDS_DETAIL_LIST

1-1

Copy your program ZBC400_##_SELECT_SFLIGHT or the corresponding template SAPBC400DDS_AUTHORITY_CHECK to the new program ZBC400_##_DETAIL_LIST. Make sure that the key fields of the database table SFLIGHT are available to you for creating the detail list when the user selects a flight from the basic list (doubleclick or F2 on the corresponding list line). Add the AT LINE-SELECTION event to your program to allow you to construct a detail list. In the first line of the detail list, display key information from the selected flight. Under this line, display a horizontal line and a blank line. Read all of the bookings from database table SBOOK for the selected flight. Make sure that you read only those fields from the database table that you want to display in the list. Display the following fields from the database table SBOOK on the detail list: BOOKID, CUSTOMID, CUSTTYPE

1-2

1-3

1-4

1-5

SAP AG

TAW10

14-16

CLASS, ORDER_DATE, SMOKER, CANCELLED.

1-6

Optional: Display the fields LOCCURAM and LOCCURKEY on the detail list: Ensure that the currency amount LOCCURAM is displayed with the appropriate formatting for the currency LOCCURKEY. Use the addition CURRENCY <currency_key> in the WRITE statement. Example : WRITE: wa_sflight-price CURRENCY wa_sflight-currency, wa_sflight-currency.

1-7

Optional: Display the BOOKID field in the color COL_KEY.

SAP AG

TAW10

14-17

User Dialog List Solutions


Unit: User Dialog List Topic: Detail Lists

Model solution without optional exercises: SAPBC400UDS_DETAIL_LIST

*&--------------------------------------------------------------* *& Report *& SAPBC400UDS_DETAIL_LIST * *

*&--------------------------------------------------------------* REPORT sapbc400uds_detail_list.

CONSTANTS: actvt_display TYPE activ_auth VALUE '03'.

DATA: wa_flight TYPE sbc400focc, wa_sbook TYPE sbook.

PARAMETERS: pa_car TYPE s_carr_id.

START-OF-SELECTION. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' CASE sy-subrc. WHEN 0. SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate,
SAP AG TAW10 14-18

FIELD actvt_display.

wa_flight-seatsocc, wa_flight-seatsmax, wa_flight-percentage,'%'. * Hide key field values corresponding to the actual line HIDE: wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ENDSELECT. WHEN OTHERS. WRITE: / 'Authority-Check Error'(001). ENDCASE. CLEAR wa_flight. * Program continues here, if a line is selected on basic list AT LINE-SELECTION. IF sy-lsind = 1. * Key fields transported back from hide area to ABAP data objects WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ULINE. SKIP. * Selection of bookings, which depend on selected flight SELECT bookid customid custtype class order_date smoker cancelled loccuram loccurkey FROM sbook INTO CORRESPONDING FIELDS OF wa_sbook WHERE carrid = wa_flight-carrid AND AND connid = wa_flight-connid fldate = wa_flight-fldate.

* Creation of detail list WRITE: / wa_sbook-bookid, wa_sbook-customid, wa_sbook-custtype, wa_sbook-class, wa_sbook-order_date, wa_sbook-smoker, wa_sbook-cancelled. ENDSELECT. ENDIF. CLEAR wa_flight.
SAP AG TAW10 14-19

Model solution with optional exercises: SAPBC400UDS_DETAIL_LIST1


*&--------------------------------------------------------------* *& Report *& REPORT sapbc400uds_detail_list1. SAPBC400UDS_DETAIL_LIST1 * *

*&--------------------------------------------------------------*

CONSTANTS: actvt_display TYPE activ_auth VALUE '03'. DATA: wa_flight TYPE sbc400focc, wa_sbook TYPE sbook.

PARAMETERS: pa_car TYPE s_carr_id. START-OF-SELECTION. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' CASE sy-subrc. WHEN 0. SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car. wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate, wa_flight-seatsocc, wa_flight-seatsmax, wa_flight-percentage,'%'. * Hide key field values corresponding to the actual line HIDE: wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ENDSELECT. WHEN OTHERS. WRITE: / 'Authority-Check Error'(001). ENDCASE.
SAP AG TAW10 14-20

FIELD actvt_display.

CLEAR wa_flight. * Program continues here, if a line is selected on basic list AT LINE-SELECTION. IF sy-lsind = 1. * Key fields transported back from hide area to ABAP data objects WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ULINE. SKIP. * Selection of bookings, which depend on selected flight SELECT bookid customid custtype class order_date smoker cancelled loccuram loccurkey FROM sbook INTO CORRESPONDING FIELDS OF wa_sbook WHERE carrid = wa_flight-carrid AND AND connid = wa_flight-connid fldate = wa_flight-fldate.

* Creation of detail list WRITE: / wa_sbook-bookid COLOR COL_KEY, wa_sbook-customid, wa_sbook-custtype, wa_sbook-class, wa_sbook-order_date, wa_sbook-smoker, wa_sbook-cancelled, wa_sbook-loccuram CURRENCY wa_sbook-loccurkey, wa_sbook-loccurkey. ENDSELECT. ENDIF. CLEAR wa_flight.

SAP AG

TAW10

14-21

User Dialog Selection Screen

Contents:
l Selection screen attributes and strengths l Defining selection screens l Evaluating user input to restrict database selection l Selection screen events l Syntax examples: Additional input checks with error dialog

SAP AG 2001

SAP AG

TAW10

15-1

User Dialog List: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe selection screen attributes and strengths l Write a program that allows you to enter intervals on a selection screen and that can be used to restrict the number of data records retrieved from the database l Write a program that contains additional input checks for the selection screen and returns to the selection screen if an error occurs

SAP AG 2001

SAP AG

TAW10

15-2

Use of Selection Screens

ABAP program

Selection criteria

Database table

ABAP processing block

ABAP runtime system


SAP AG 2001

n n

Selection screens allow users to enter selection criteria required by the program for it to continue. For example, if you create a list containing data from a very large database table, you can use a selection screen to restrict the amount of data that is selected. At runtime, the user can select intervals for one of the key fields, and only data that corresponds to this selection is read from the database and displayed in the list. This considerably reduces the load on the database and network.

SAP AG

TAW10

15-3

Overview: Selection Screen Attributes

Selection Selection Screen Screen Attributes Attributes Single Single Fields Fields (PARAMETERS) (PARAMETERS) Value Value Sets Sets (SELECT-OPTIONS) (SELECT-OPTIONS) Selection Selection Screen Screen Events Events

SAP AG 2001

SAP AG

TAW10

15-4

Selection Screen Attributes

Type checks Multilingual Capacity

Value Value entry

Variants Variants

Input help Possible entries help

SAP AG 2001

n n

Selection screens are input masks for value sets that restrict the amount of data read from the database. The following possibilities are available to the user: Entries in single fields Complex entries: Intervals, operations, patterns Saving filled selection fields as variants Input help and search helps are available by choosing the F4 function key or the possible entries pushbutton You can translate selection texts into other languages so that they are then displayed in the language in which the user is logged on. The system checks the type: If you enter a value with an incorrect type, the system displays an error message and makes the field ready for new input.

SAP AG

TAW10

15-5

Entering Value Sets

SELECT-OPTIONS ... PARAMETERS ...

Airline Departure city

LH

to

Maintain selection options


Airline Single value Greater than or equal Less than or equal Greater than Less than Not equal Select
Exclude from selection

Multiple single values Intervals Single value exclusion Interval exclusion

SAP AG 2001

Selection screens allow you to define selection options for complex entrie s as well as simple input fields. Setting selection options Entering multiple values or intervals Defining a value set that is not to be selected and is to be subtracted from the value set to be selected at the end. Every selection screen contains an information icon. Choose this icon to display additional information.

SAP AG

TAW10

15-6

Using the Semantic Information of Global Types

Airline Formatting rules Selection screen Semantic information Technical information:

Structure

Global types Data element element

[Search help]

Field label Input help Search help Technical type

ABAP program PARAMETERS pa_carr TYPE spfli-carrid.

SAP AG 2001

n n

If an input field is typed with a data element, the following additional semantic information is available: You can use a field name as a selection text Input help (F1 help) from the data element is available automatically Possible entries help (F4 help) is available automatically, provided the data element has been linked with a search help. A search help is a standalone object defined in the Dictionary, which controls the dialog with the user and data retrieval for the possible entries help. If an input field is typed with a structure field that uses a data element, the following semantic information is available: Field names and input help (F1 help) are copied from the data element that has been used to type the Dictionary structure field. If a structure field is coupled with a search help, then this is the search help that is used for the possible entries help (F4 help) - that is, it obscures the data element search help. If there is no search help coupled with the structure field, the system uses the data element search help. Bear in mind that the global type you choose to provide a type for an input field affects the semantic information available to the user. For more information, refer to the online documentation for the ABAP Dictionary.

SAP AG

TAW10

15-7

Selection Texts

Multilingual capacity
ABAP program Text elements ... Source code
Titles/headers Text symbols

SELECT-OPTIONS so_carr FOR ... PARAMETERS pa_city TYPE ...

Selection texts SO_CARR DE EN Airline DE EN Departure city

PA_CITY

Airline Departure city

LH

to Dictionary reference

SAP AG 2001

On the selection screen, the field names appear as text next to the input fields. However, you can replace these with selection texts, which you can then translate into any further languages you require. Selection texts are displayed in the user's logon language. If the input field is typed directly or indirectly with a data element, you can copy the field name from one of the texts stored in the Dictionary.

SAP AG

TAW10

15-8

Variants

Airline Departure city

LH

to

Createaavariant: variant: Create Fill out the selection screen Save as a variant Enter a variant name Meaning: Enter a descriptive short text You can also choose other attributes Use the variant: Create a variant: Start the program Choose the icon on the selection screen

Choose a variant by name The system copies the values to the input fields
SAP AG 2001

n n

n n n

If you want to save the values (or some of the values) on a selection screen that you have filled out, you can do so by creating a variant. When you start the program again later, you can get these values from the variant and display them in the selection screen. You can define and save variants for any program that contains a selection screen. You do this by starting the program and then creating a variant by choosing Goto Variants Save as variant. Variants allow you to tailor selection screens to suit your needs. You can: Preassign values for input fields Hide input fields A single variant can refer to more than one selection screen in the same program. Variants are client-specific. Every selection screen contains an information icon. Choose this icon to display additional information.

SAP AG

TAW10

15-9

Single Fields (PARAMETERS)

Selection Selection Screen Screen Attributes Attributes Single Single Fields Fields (PARAMETERS) (PARAMETERS) Value Value Sets Sets (SELECT-OPTIONS) (SELECT-OPTIONS) Selection Selection Screen Screen Events Events

SAP AG 2001

SAP AG

TAW10

15-10

Effect of the PARAMETERS Statement

ABAP program pa_car Declarative statements PARAMETERS PARAMETERS pa_car TYPE s_carr_id. Selection screen Reference to ABAP Dictionary

S_CARR_ID

SAP AG 2001

In an executable program, a single PARAMETERS statement is sufficient to generate a standard selection screen. The PARAMETERS <name> TYPE <typename> statement and the PARAMETERS <name> LIKE <data_object> statement both generate an elementary input field on the selection screen, and a data object with the same type. If the user enters a value and chooses Execute , that value is placed in the internal data object <name> in the program. The system permits only entries with the correct type.

SAP AG

TAW10

15-11

Runtime Behavior and Data Transport: Parameters

ABAP program Description of selection screen

pa_car
Selection screen

ABAP processing block

ABAP runtime system


SAP AG 2001

Time

Once the LOAD-OF-PROGRAM event block has been processed, the selection screen is sent to the presentation server. The runtime system transports the data object values that are defined using PARAMETERS to the selection screen input fields of the same name. The user can then change the values in the input fields. If the user then clicks on the Execute function, the input field values are transported to the program data objects with the same name and can be evaluated in the ABAP processing blocks.

SAP AG

TAW10

15-12

Using Parameters When Accessing the Database

REPORT ... DATA wa_spfli TYPE spfli. PARAMETERS pa_car TYPE s_carr_id. ... SELECT SELECT carrid connid cityfrom cityto ... FROM spfli INTO CORRESPONDING FIELDS OF wa_spfli pa_car . WHERE WHERE carrid carrid = = pa_car WRITE: / wa_spfli-carrid, wa_spfli-connid, wa_spfli-fldate, ... . ENDSELECT ENDSELECT .

SAP AG 2001

n n

If you have used the PARAMETERS statement to program an input field as a key field for a database table, you can use a WHERE clause at the SELECT statement to limit data selection to this value. In the example above only those data records are read from database table SPFLI whose key field CARRID has the same value as is contained in data object pa_car at runtime.

SAP AG

TAW10

15-13

Value Sets (SELECT-OPTIONS)

Selection Selection Screen Screen Attributes Attributes Single Single Fields Fields (PARAMETERS) (PARAMETERS) Value Value Sets Sets (SELECT-OPTIONS) (SELECT-OPTIONS) Selection Selection Screen Screen Events Events

SAP AG 2001

SAP AG

TAW10

15-14

Effect of the SELECT-OPTIONS Statement

Option sign low high so_carr

ABAP program Reference to ABAP Dictionary gd_carrid

Selection screen

Declarative statements DATA gd_carrid TYPE s_carr_id. SELECT-OPTIONS SELECT -OPTIONS so_carr FOR gd gd_carrid.

S_CARR_ID

SAP AG 2001

You use the SELECT-OPTIONS name FOR data_object statement to define selection options: Two input fields with the same type as the data object appear on the selection screen, allowing you to enter interval limits. Additionally, a button appears that allows you to realize complex set limits. The statement also declares an internal table name within the program, with the following four columns: sign: This field designates whether the value or interval should be included (I) in or excluded (E) from the selection. option for the operator (BT, ...): For a list of possible operators, refer to the keyword documentation for the SELECT-OPTIONS statement. low: This field contains the lower limit of an interval or single value. high: This field contains the upper limit of an interval. This selection table name always refers to a data object that has already been defined. The data object is used as a target field during database selection, while the selection table is a set of possible values. For this reason a special version of the WHERE clause exists for database selection. It determines whether or not the database contains the corresponding field within the value set. Note: Similarly, an inclusion test is also defined for the IF statement.

SAP AG

TAW10

15-15

Runtime Behavior and Data Transport: Selection Options

ABAP program Description of selection screen gd_carrid

so_carr
Selection screen

ABAP processing block

ABAP runtime system


SAP AG 2001

Time

If the user enters several values or intervals for a selection option and chooses Execute , the system places them in the internal table.

SAP AG

TAW10

15-16

Using Selection Options When Accessing the Database

REPORT ... DATA wa_spfli TYPE spfli. SELECT-OPTIONS so_carr FOR wa_spfli-carrid. ... SELECT carrid connid cityfrom cityto ... FROM spfli INTO CORRESPONDING FIELDS OF wa_spfli WHERE carrid IN so_carr. so_carr WRITE: / wa_spfli-carrid, wa_spfli-connid, wa_spfli-cityfrom, wa_spfli-cityto, ... ENDSELECT. ENDSELECT ENDSELECT

SAP AG 2001

n n

The above example shows how you can restrict database selection to a certain range using a selection table. Conditions in an internal table declared using SELECT-OPTIONS are interpreted as follows: If the internal table is empty, the condition field IN selname is always true. If the internal table only contains inclusive elementary conditions, such as i_1, or i_n, the result is the composite condition (i_1 OR ... OR i_n ). If the internal table only contains exclusive elementary conditions such as e1 or em, the result is the composite condition ( NOT e_1) AND ... AND (NOT e_m) If the internal table contains inclusive elementary conditions, such as i_1 or i_n, and exclusive elementary conditions, such as e_1 or e_m, the result is the composite condition ( i_1 OR ... OR i_n ) AND ( NOT e_1 ) AND ... AND ( NOT e_m ).

SAP AG

TAW10

15-17

Selection Screen Events

Selection Selection Screen Screen Attributes Attributes Single Single Fields Fields (PARAMETERS) (PARAMETERS) Value Value Sets Sets (SELECT-OPTIONS) (SELECT-OPTIONS) Selection Selection Screen Screen Events Events

SAP AG 2001

SAP AG

TAW10

15-18

Selection Screen Events


Program start

LOAD-OF-PROGRAM.

AT SELECTION-SCREEN.

No
Yes

START-OF-SELECTION.

SAP AG 2001

Time

n n

In an executable program, the ABAP runtime system generates a standard selection screen as long as you have written at least one PARAMETERS or SELECT-OPTIONS statement. The event block AT SELECTION-SCREEN belongs to the selection screen. The selection screen is sent after the event block LOAD-OF-PROGRAM. Each time the user presses <Enter>, a pushbutton, a function key, or chooses a menu function, the system initially carries out a type check. If the entries do not have the correct type, the system displays an error message, and makes the fields ready for input again. When the entries have the correct type, the system processes the event block AT SELECTION-SCREEN. Subsequent program flow depends on the user action: If the user chooses <F8> or Execute the next event block is called: in this case START-OFSELECTION. If the user chose any other function, the selection screen is displayed again.

SAP AG

TAW10

15-19

Error Dialogs in AT SELECTION-SCREEN


Program start

LOAD-OF-PROGRAM.

No authorization...

Message text

AT SELECTION-SCREEN. IF ... Error check


Error message

START-OF-SELECTION.

SAP AG 2001

Time

n n

n n

Use the event block AT SELECTION-SCREEN if you want to program additional input checks for a standard selection screen. The event block AT SELECTION-SCREEN is triggered by each user action. If an error dialog is triggered by the MESSAGE statement, the system resends the selection screen and automatically resets all input fields to ready for input. For more detailed information on the MESSAGE statement, refer to the keyword documentation. Additional information can be found in the keyword documentation for AT SELECTION-SCREEN.

SAP AG

TAW10

15-20

Syntax Example: Selection Screen Authorization Check

PARAMETERS pa_car TYPE s_carr_id.

* event processed after leaving the selection screen AT SELECTION-SCREEN. SELECTION SELECTION-SCREEN. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' FIELD actvt_display. IF sy-subrc NE 0. * show selection screen again with message in status bar MESSAGE MESSAGE e e045(bc400) WITH pa_car. ENDIF.

SAP AG 2001

n n

As an example of an additional input check with error dialog, an input field for the airline ID needs to be added to the program. An authorization check is to be carried out on the selection screen. If the user has authorization to display the specified airline, the program continues. If the user does not have display authorization, then the selection screen is displayed again and an error message appears in the status bar.

SAP AG

TAW10

15-21

User Dialog List: Unit Summary

You are now able to: l Describe selection screen attributes and strengths l Write a program that allows you to enter intervals on a selection screen and that can be used to restrict the number of data records retrieved from the database l Write a program that contains additional input checks for the selection screen and returns to the selection screen if an error occurs

SAP AG 2001

SAP AG

TAW10

15-22

Selection Screen Exercises


Unit: Selection Screen

At the conclusion of these exercises, you will be able to: Use the ABAP statement SELECT-OPTIONS to enter complex values on a standard selection screen. Take account of complex values in a database selection. Program an error message for a standard selection screen Extend your program ZBC400_##_DETAIL_LIST or the corresponding model solution as follows: Extend the standard selection screen to allow you to define a complex value set for limiting the connecting flight number. The value set is to be taken into account when selecting flights. Additionally, change your program so that the user can only progress from the selection screen if the authorization check for the desired airline is successful. Program: ZBC400_##_SEL_SCREEN

Model solution: SAPBC400UDS_SEL_SCREEN Template: 1-1 SAPBC400UDS_DETAIL_LIST

Copy your program ZBC400_##_DETAIL_LIST or the corresponding template SAPBC400UDS_DETAIL_LIST to the new program ZBC400_##_SEL_SCREEN. Extend your selection screen to allow the user to enter a complex value range for the flight number CONNID. When you are typing the airline and flight number, make sure you refer to the same structure so that the search helps are context-dependent.

1-2

1-3 1-4

Use the complex value set to restrict the amount of data selected from the database table SFLIGHT. Change your program so that the user cannot progress from the selection screen if the authorization check against the authorization object S_CARRID fails. If the authorization check fails, display a suitable error message from message class BC400, and allow the user to enter a different value on the selection screen.
TAW10 15-23

SAP AG

Selection Screen Solutions


Unit: Selection Screen

Model solution: Program SAPBC400UDS_SEL_SCREEN

*&--------------------------------------------------------------* *& Report *& SAPBC400UDS_SEL_SCREEN * *

*&--------------------------------------------------------------* REPORT sapbc400uds_sel_screen.

CONSTANTS: actvt_display TYPE activ_auth VALUE '03'.

DATA: wa_flight TYPE sbc400focc, wa_sbook TYPE sbook.

PARAMETERS: pa_car LIKE wa_flight-carrid. * Data field for complex restrictions applied to connection id SELECT-OPTIONS: so_con FOR wa_flight-connid.

* First event processed after leaving the selection screen AT SELECTION-SCREEN. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD pa_car ID 'ACTVT' FIELD actvt_display.

IF sy-subrc <> 0. * Return to selection screen again and display message in status * bar MESSAGE ID 'BC400' TYPE 'E' NUMBER '045' WITH pa_car. ENDIF.

START-OF-SELECTION.
SAP AG TAW10 15-24

SELECT carrid connid fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING FIELDS OF wa_flight WHERE carrid = pa_car AND connid IN so_con. wa_flight-percentage = 100 * wa_flight-seatsocc / wa_flight-seatsmax.

WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate, wa_flight-seatsocc, wa_flight-seatsmax, wa_flight-percentage,'%'. HIDE: wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ENDSELECT. AT LINE-SELECTION. IF sy-lsind = 1. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate. ULINE. SKIP. SELECT bookid customid custtype class order_date smoker cancelled loccuram loccurkey FROM sbook INTO CORRESPONDING FIELDS OF wa_sbook WHERE carrid = wa_flight-carrid AND AND connid = wa_flight-connid fldate = wa_flight-fldate.

WRITE: / wa_sbook-bookid, wa_sbook-customid, wa_sbook-custtype, wa_sbook-class, wa_sbook-order_date, wa_sbook-smoker, wa_sbook-cancelled, wa_sbook-loccuram CURRENCY wa_sbook-loccurkey, wa_sbook-loccurkey. ENDSELECT. ENDIF.

SAP AG

TAW10

15-25

User Dialogs: Screens

Contents:
l Screen Attributes and Strengths l Creating Screens l Layout l Field Attributes l Flow Logic l Data Transport l Using Pushbuttons and Evaluating User Actions

SAP AG 2001

SAP AG

TAW10

16-1

User Dialog Screen: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe screen attributes and strengths l Write a program that: l Displays data on a screen l Allows the user to change some of that data l Allows the user to influence further program processing using pushbuttons

SAP AG 2001

SAP AG

TAW10

16-2

Screen Attributes

Editing options options Flexible program flow


100 120

Input help Possible entries help

200 300

140

Consistency check during data entry Type checks

SAP AG 2001

n n

Screens are made up of more than just a screen layout with input and output fields. They also have their own processing logic. The fact that the ABAP Dictionary is integrated in the system means that automatic consistency checks for screen input fields are provided. These checks include type checks, foreign key checks, and fixed value checks. All of these checks are automatically supplied with information from the ABAP Dictionary. Checks like the ones above can be complemented by other program-specific checks. With the techniques available for screens , you can control the order in which checks are performed and, if errors occur, make the fields input ready again, where appropriate. You can also set up screen layout in a very flexible way. Input fields, output fields, radio buttons, checkboxes, and even pushbuttons can be placed on screens. These features allow users to determine the direction in which the program will proceed. The same editing options are available for the screen as for list display and the selection screen: the fixed point numbers and the date are set according to the user default values, the time in format hh:mm:ss, amounts according to the setting in a currency field, and lengths and weights according to the content of a unit-of-measure field.

SAP AG

TAW10

16-3

Options for Calling Screens

Transaction code
100 120

200

140

CALL SCREEN 100.


300

SAP AG 2001

To start a screen sequence: Specify the first screen as the start screen of a transaction code of the type dialog transaction Call a screen from any one ABAP processing block in the program

This unit concentrates on the latter option.

SAP AG

TAW10

16-4

Application Example: Destination

Timetable
Flgt LH LH ... SQ Conn Dept Conn. Dept 0400 FRA Frankfurt 0400 FRA Frankfurt 0002 SIN Dest. New York New York

JFK JFK

Singapore SFO San Francisco Change flight data Airline Flight number
LH 0400

Screen

Departure airport FRA Destination airport JFK Change in database Flight duration Departure time
Save
SAP AG 2001

8:24 10:10:00 Back

In the following units, you will develop a program, in several steps, that enables the user to change the master data of the flight timetable. Double-clicking on an entry in the basic list containing the flight timetable calls a screen, which displays data from the line you selected, and additional information about the flight connection. You can change the flight duration and the departure time. Choosing Back takes the user back to the basic list without changing any data. Choosing Save changes the data in the database.

There is a function module for database changes that is implemented later on (see the unit about Cross-Program Modularization).

SAP AG

TAW10

16-5

Components for Screen Processing

Screen Painter

Attributes
Screen number Short text Screen type Next screen ...

Layout
Departure City

Element list
Attributes: CHAR20 Required entry field ...

Flow control
PROCESS BEFORE OUTPUT. MODULE clear_ok_code. PROCESS AFTER INPUT. MODULE user_command.

SAP AG 2001

Each screen has the following information: Attributes: Include a four-digit number as the screen name, designation, and a short text information on the screen type (for example, normal for full size screen). Layout: Includes elements you can place on the screen. Elements that are displayed on the screen are called screen elements . Element list: Contains the attributes of the screen elements, such as the position, size, and data type.

Flow control: Contains the processing logic that is to be processed before the screen is sent to the presentation server (PBO) and the processing logic that is to be processed after a user action has taken place.

SAP AG

TAW10

16-6

Editing Window in the Graphical Layout Editor

Graphical Layout Editor Element attributes

Toolbar

Layout area

Create fields with reference to the Dictionary

Element list

SAP AG 2001

From the Graphical Layout Editor, you can start other functions: Element attributes: All the attributes of a screen element are displayed in this dialog box. You can change some of the attributes in the box. Example: you can specify whether or not an input/output field is to be input ready. Get from ABAP Dictionary / Get from program: This dialog box allows you to generate fields that have either a global type or the same type as a data object in the program. Element list: Shows all the elements displayed on the screen with their attributes. You can also change attributes here..

SAP AG

TAW10

16-7

Example of Level 1: Create Screen

Timetable
Flgt LH LH ... SQ Conn Dept Conn. Dept 0400 FRA Frankfurt 0400 FRA Frankfurt 0002 SIN Dest. New York New York

JFK JFK

Singapore SFO San Francisco Change flight data Airline Flight number Departure airport Destination airport Flight duration Departure time

Screen

SAP AG 2001

Your first step is to create a screen, specify its layout, and define its field attributes. The fields Airline, Flight number, Departure airport, and Destination airport are to appear as output fields. The fields Flight duration and Departure time are available as input-ready fields. The user should be able to call the screen by double -clicking a line within the basic list and return to the basic list by choosing the appropriate function on the screen.

SAP AG

TAW10

16-8

Creating a Screen: Screen Attributes

ABAP : AT LINE-SELECTION. : CALL SCREEN 100 100. Double-click :

Create object Screen 100 does not exist. Do you want to create the object? Yes No Cancel

Screen Painter

Screen Attributes Short text Screen type Normal Subscreen Modal dialog box Next screen 0 Supplemental data display

SAP AG 2001

There are several ways to create screens: Through forward navigation: You can create screens from within the ABAP Editor by double clicking on the screen number. This transfers you to Screen Painter automatically. Using Object Navigator: You can create a new program object screen for your program directly from the object list in the navigation area.

n n

When you create a screen, the system will ask you to enter screen attributes. Enter a short description of the screen, select screen type Normal, and enter the number of the subsequent screen. If you enter 0 for the subsequent screen, the system first processes your screen completely and then returns to processing at the point where the screen call is set. (Note that "0" in the entry field for the subsequent dynpro is not displayed because this is actually the inital value.) In the example in the graphic, the screen the user creates is called from within the basic list. Therefore, CALL SCREEN 100 must belong to the AT LINE-SELECTION event block.

SAP AG

TAW10

16-9

Input Fields with Reference to Fields of a Dictionary Structure

Airline Flight number Departure airport Destination airport Flight duration Departure time

SDYN_CONN

SAP AG 2001

There are two ways of assigning field attributes to the required screen fields: l Copying data from the Dictionary: You can copy types and field attributes from existing ABAP Dictionary structures. This makes all information about the object available to you, including semantic information about its data elements and foreign key dependencies. The name of the Dictionary field is automatically adopted as a field name. l Copying data from the program: You can copy field attributes from data objects already defined within your program to the screen. In order to do this, however, an activated copy of the program must already exist. The name of the data object is automatically taken as the field name. The Graphical Screen Painter allows you to define different screen elements (for example, input and output fields, keyword texts, borders, and so on) with relative ease. Choose the desired screen element and then place it on the screen using the mouse. You can delete screen elements simply by pointing to them and choosing Delete . You can move screen elements by selecting them and dragging them to a new position.

n n

SAP AG

TAW10

16-10

Changing the Element Attributes of a Field: Attribute Window

Attributes Attributes
T

Airline Flight number


X

Name Text Line

SDYN_CONN-CARRID

Departure airport Destination airport Flight duration Departure time

Colu mn

FCode

FTyp e Dict Prog Disp

Input field Output field Required field ...

SAP AG 2001

n n n

To maintain the attributes of a screen field, select the field and choose Attributes. You can assign the attribute mandatory (Required field ) to a screen field. At run time, the field will be marked accordingly if it is set to initial value. If not all required fields have been filled at run time and a user action is performed, an error dialog is triggered by the ABAP run time system and all input fields are once again displayed ready for input.

SAP AG

TAW10

16-11

Example Level 2: Displaying Data

Timetable
Flgt LH LH ... SQ Conn Dept Conn. Dept 0400 FRA Frankfurt 0400 FRA Frankfurt 0002 SIN JFK JFK Dest. New York New York

Singapore SFO San Francisco Change flight data Airline Flight number
LH 0400

Screen

Departure airport FRA Destination airport JFK Flight duration Departure time
8:24 10:10:00

SAP AG 2001

n n

In step two you learn how to display data on a screen by programming data transport from the basic list to the screen. For the user, the program works in the following manner: By double-clicking on a line in the basic list, the user branches to the screen where the most important items of information for the flight connection he or she has chosen are displayed. The flight duration and departure time are displayed in a field that is ready for input and hence can be changed. The user returns to the basic list in one of several ways.

With this in mind, this part of the unit will deal with: Setting up prerequisites for automatic data transport between the program and screen fields Defining the screen interface and programming data transport to the data objects of the interface

SAP AG

TAW10

16-12

Screen Interface

Data objects

ABAP program wa_spfli sdyn_conn Declarative statements DATA wa_spfli TYPE spfli. TABLES TABLES sdyn_conn. SDYN_CONN

Process Before Output Process After Input

ABAP processing block Screen

SAP AG 2001

The TABLES statement defines an internal data object that serves as an interface for the screen. The TABLES statement always refers to an ABAP Dictionary object (for example, transparent table or structure). If the screen fields and the TABLES statement refer to the same ABAP Dictionary object, this data object's data is automatically transported to the screen fields every time the screen is transmitted. Any new entries or changes that the user makes on the screen are then transferred back into this data object. As a rule, structures that contain fields of the same type for the different tables are created in the ABAP Dictionary. The flight data programs being created in this course use one structure for master data maintenance (sdyn_conn) and another for bookings data (sdyn_book). Using your own structures as interfaces usually helps make a program easier to understand and helps to avoid errors as well.

SAP AG

TAW10

16-13

Data Transport from the Program to the Screen

ABAP program wa_spfli sdyn_conn

DATA wa_spfli TYPE spfli. TABLES sdyn_conn.

Process Before Output Process After Input

CALL SCREEN 100.

Screen 100 ABAP runtime system


SAP AG 2001

Time

Data transport between program data objects and screen fields with the same name takes place automatically: Immediately before the screen is sent to the presentation server, that is, after the PBO event has been fully processed, the contents from fields with the same names are copied from the ABAP work area into the screen fields. ABAP statements facilitate data transport between ABAP program data objects and the work area designated as the screen interface.

SAP AG

TAW10

16-14

Data Transport from the Screen to the Program

wa_spfli sdyn_conn

Process Before Output Process After Input

CALL SCREEN 100.

Screen 100

SAP AG 2001

Time

Data transport between screen fields and program data objects with the same name takes place automatically: Immediately after a user performs an action on the screen, that is, before the PAI event is fully processed, the contents of the fields with the same name are copied from the screen fields into the ABAP work area. ABAP statements facilitate data transport between jects the work area designated as the screen interface and program data objects..

SAP AG

TAW10

16-15

Data Transport in the Program Example

Automatic data transport HIDE area in data objects AT LINE-SELECTION. Fill the TABLES structure with current data for selected line TABLES structure in screen fields CALL SCREEN 100.

Screen fields in TABLES structure ABAP runtime system


SAP AG 2001

Time

n n n

The sample program should display screen data that matches the line selected in the basic list. If data objects and their values were stored in the HIDE area when the basic list was created, the data belonging to the selected line will be placed in the corresponding data objects. You must copy the data to be displa yed on the screen to a TABLES structure. You can do this in any ABAP processing block that is processed before the screen is sent to the presentation server. There are various ways of doing this: You start by reading all the data to be displayed on the screen before retrieving the basic list from the database. You then place all the necessary data in the HIDE area. Then, at the AT LINESELECTION event, you have to copy the data into the TABLES structure only. Disadvantage: You have to read data from the database that the user may not even look at. If detailed data has changed between creating the basic list and displaying the screen, the system will display the wrong data. Before the screen is called using the SELECT SINGLE statement, you read the additional data for the selected key (HIDE area) from the database. Advantage: You reduce the volume of data you need to read from the database when you create the basic list. The detailed list is up-to-date. Disadvantage: The system sends a query to the database every time the user double -clicks the list.

SAP AG

TAW10

16-16

Implementing the Sample Program


Structure: Fields: MANDT CARRID CONNID COUNTRYFR CITYFROM AIRPFROM COUNTRYTO CITYTO AIRPTO FLTIME DEPTIME ARRTIME DISTANCE DISTID FLTYPE wa_spfli Basic List HIDE Area
! ! ! !

sdyn_conn Screen: Output Field Input Field


! !

! ! !

! !

Before calling the screen: SELECT SINGLE * FROM spfli ...


SAP AG 2001

On the last development level, the program should allow the user to change data in the database. The user should be able to change the fields FLTIME and DEPTIME. To enable the user to change data for several airlines, a basic list of the airlines for which the user is allowed to change data should be displayed. The user reaches the change screen by double -clicking in the basic list. Once the changes are made successfully, the user returns to the basic list. However, a new basic list is not created. Therefore, the data that can be changed should not appear on the basic list. To ensure that the database data displayed on the screen is up-to-date, the record is read again from the database at the beginning of AT LINE-SELECTION. Advantages of this method: For the basic list, only those columns of the database table that are displayed on the list need to be read. This can improve performance with large lists. The data that is displayed on the screen is always up-to-date, even if the data record selected has just been changed using this program. Changes made to the database using the screen do not lead to incorrect values in the basic list because the modifiable fields are not contained in the basic list.

SAP AG

TAW10

16-17

Syntax: Sample Program with Data Transport


START-OF-SELECTION. SELECT carrid connid airpfrom cityfrom airpto cityto INTO CORRESPONDING FIELDS OF wa_spfli FROM spfli. WRITE: / wa_spfli-carrid COLOR COL_KEY, wa_spfli-connid COLOR COL_KEY, ... * buffering key fields HIDE: HIDE: wa_spfli-carrid, wa_ wa _spflispfli-carrid, carrid, wa_spfli-connid. wa_ wa _spflispfli- connid connid. . ENDSELECT. AT LINE-SELECTION. SELECT SELECT SINGLE SINGLE * * FROM FROM spfli spfli INTO wa_spfli wa_spfli INTO WHERE WHERE carrid carrid = = wa_spfli-carrid wa_ wa _ spfli spfli- carrid AND AND connid connid = = wa_spfli-connid. wa_ wa _ spfli spfli- connid connid. . MOVE-CORRESPONDING wa_spfli spfli to sdyn_conn. CALL SCREEN 100.
SAP AG 2001

n n

To display data on the screen, the TABLES structure must be filled with current data before the screen is sent to the presentation server. The example in the graphic shows one way of doing this. The HIDE statement is used to place key fields of database table s with reference to the list line in the HIDE area. Then the current data for the line selected is available in fields wa_spfli-carrid and wa_spfli-connid at event AT LINE-SELECTION. The data record is read from the database using SELECT SINGLE. This ensures that the data is upto-date. The corresponding fields of the wa_spfli work area are copied to the TABLES structure sdyn_conn using MOVE-CORRESPONDING. The system transports the structure data to the screen fields automatically. Alternatively, you can place the data into the TABLES structure directly when the database is accessed, using the INTO CORRESPONDING FIELDS addition.

SAP AG

TAW10

16-18

Example Level 3: Assigning Pushbuttons

Timetable
Flgt LH LH ... SQ Conn Dept Conn. Dept 0400 FRA Frankfurt 0400 FRA Frankfurt 0002 SIN Dest. New York New York
Message 1 in status line

JFK JFK

Singapore SFO San Francisco Change flight data Airline Flight number
LH 0400

Screen

Message 2in status line

Departure airport FRA Destination airport JFK Flight duration Departure time
Save
SAP AG 2001

8:24 10:10:00 Back

n n

n n

In step three you learn how to assign pushbutton functions. These functions allow different kinds of program logic to be processed according to user choice. For the user, the program works in the following manner: By double-clicking on a line, the user branches to a screen where the most important items of information for the connection the user chose are displayed. The flight duration and departure time can be changed. By choosing the Back pushbutton, the user returns to the basic list without writing any changes to the database. The message "Screen was left without any changes being made" is displayed in the status bar of the basic list. Choose Save to write all of your changes to the database. The changes take effect in the program only at a later time. The pushbutton is already prepared in the following section. The user returns to the basic list after choosing the pushbutton and a message is displayed in the status bar. . After each other user activity, the screen is displayed once again. With this in mind, this part of the unit deals with: Flow logic in PBO and PAI event blocks Using PBO and PAI modules as ABAP processing blocks for screen programming Evaluating information on which pushbutton was selected at the time of PAI

SAP AG

TAW10

16-19

Runtime Behavior When User Chooses a Pushbutton

ABAP program Global data object Back BACK Function code BACK CASE ok_code. WHEN 'BACK'. ... ok_code

ENDCASE.

ABAP runtime system


SAP AG 2001

Time

n n

If the user chooses a pushbutton, the run time system copies the associated function code to a special screen field. This screen field is usually called the ok_code. The content of this screen field is then automatically transported if there is an ABAP data object of the same name. The content of this ok_code field can then be evaluated in an ABAP processing block. This mechanism allows you to create a program flow that depends on the user's actions. The following slides deal with how you declare the ok_code field, how you create pushbuttons and assign function codes to them, and how you can change the screen sequence.

n n

SAP AG

TAW10

16-20

Defining Pushbuttons / Assigning Function Codes

Attributes
T

Airline Flight number


X

Name Text Line

Departure airport Destination airport Flight time Departure time Save Back

BUTTON2 Back Colum n

FCode BACK FType Dict Prog Disp

Input field Output field ...

SAP AG 2001

To be able to transport information as to which pushbutton was chosen, you must assign a function code to each pushbutton. You can do this either in the Graphical Layout Editor using the maintenance function for field attributes or from the element list.

SAP AG

TAW10

16-21

Making the Command Field Usable

ABAP Editor 2 TABLES sdyn_conn. DATA: ok_code like sysy-ucomm. DATA ok ok_ _ code LIKE sy -ucomm ucomm. .

Screen Painter

Screen Painter: List of Elements


General attributes Field name Field text
...

Function code
...

OK 1

BUTTON1 BUTTON2 OK_CODE

Save Back

SAVE BACK

SAP AG 2001

n n n

The command field serves as a special field into which corresponding function codes are placed after every user action. This field must be given a name in the last line of the list of elements on each screen. Generally, you use the name OK_CODE. In the declaration part of the program, define a corresponding data object with the same name. At run time, whenever a user action is triggered, the function code of the pushbutton chosen is placed into the data object. You can use the system field sy-ucomm as a reference field for the type.

SAP AG

TAW10

16-22

Calling Modules

100
PBO

CALL SCREEN 100.

MODULE name.

MODULE name OUTPUT. ENDMODULE.

PAI

MODULE name.

MODULE name INPUT. ENDMODULE.

SAP AG 2001 Time

n n

The ABAP statement CALL SCREEN <nnnn> interrupts the processing of the processing block and calls a screen. Each screen has two event blocks: PROCESS BEFORE OUTPUT (PBO) is processed immediately before a screen is displayed. At this time, modules are called that take care of tasks such as presetting values in screen fields. PROCESS AFTER INPUT (PAI) is processed immediately after a user action. All program logic that is influenced by user action must be processed at PAI. Note: The code for the events PBO and PAI is written using the Screen Painter, not with the ABAP Editor. These two event blocks make up the flow logic of a screen. A special small set of commands (not ABAP statements) is available for programming flow logic. The most important statement here is called: MODULE module_name . This calls the module_name ABAP processing block. Within this block you can code in ABAP as usual. Modules are ABAP processing blocks with no interface that can be called only from within the flow logic. Modules are enclosed within the ABAP statements MODULE and ENDMODULE.

SAP AG

TAW10

16-23

Evaluating the Function Code for PAI

Screen Painter PROCESS BEFORE OUTPUT.

ABAP Editor

Save

Back

MODULE MODULE user_ user_command_0100 user_command_0100 command_0100 INPUT. CASE CASE ok_code. WHEN 'BACK'. ... WHEN 'SAVE'. ... ENDCASE. ENDMODULE.

PROCESS AFTER INPUT. MODULE user_ _ command command_0100. _0100. MODULE user user_command_0100.

SAP AG 2001

You can evaluate user actions in a PAI module. Usually, this PAI module is called user_command_nnnn, where nnnn stands for the screen number. In this module, evaluate the function code in the ok_code field. Note: For historical reasons, modules have no interface and no local variables. You can access all the ABAP program's global data in modules.

SAP AG

TAW10

16-24

Creating Modules Using Forward Navigation


Screen Painter PROCESS AFTER INPUT. MODULE user_command_100. Double -c lick Create object
PAI module USER_COMMAND_100 does not exist. Do you want to create the object?

Yes

No

Cancel

Create PAI module PAI module Include selection ZBC400_00_DYNPRO ABAP Editor New include Main program USER_COMMAND_0100

MODULE user_command_100 INPUT.

ENDMODULE.
SAP AG 2001

As a rule, you implement MODULE calls within a screen's flow control (PBO and PAI events). The modules themselves are created using ABAP. n There are two ways to create a module: Forward navigation: To create a module, double -click on the module name in the flow logic from within the Screen Painter. Navigation area: If you want to create a module from within the object list of the program, choose a new program object PBO module or PAI module. n A module can be called from more than one screen (reusability). n Make sure that modules called at PBO events are defined using the statement MODULE ... OUTPUT, whereas modules defined using the statement MODULE ... INPUT can be called only at PAI events.

SAP AG

TAW10

16-25

Next Screen: CALL SCREEN Statement

100
PBO

CALL SCREEN 100.

PAI

Screen attributes Next screen

Next screen 0

SAP AG 2001 Time

If you enter 0 for the next screen, the system first processes your screen completely and then continues processing the program from the point where the screen was called.

SAP AG

TAW10

16-26

Next Screen: Set Statically

100
PBO

CALL SCREEN 100. ...

PAI

Screen attributes Next screen

100

Next screen 100

SAP AG 2001 Time

If you set the next screen for screen 100 to 100, the system processes the screen again after it has finished processing the PAI module.

SAP AG

TAW10

16-27

Next Screen: Set Dynamically

100
PBO

CALL SCREEN 100. ...

PAI

SET SCREEN 0. SET SCREEN 0. 0 Next screen 0

Screen attributes Next screen

100

SAP AG 2001 Time

n n

Using the ABAP statement SET SCREEN nnnn from within a PAI module, you can have the next screen set dynamically. The static entry is then suppressed. The number of the current screen is entered by the system as the standard entry for the next screen. This ensures that the Enter key or the green checkmark lead to a field check only; afterwards the screen is transmitted once again, possibly with a respective error message. To leave the screen, an appropriate pushbutton must be defined that triggers a screen change within the PAI module. Note: If the system processes the same screen again, it also runs through all the PBO modules again. If you decide to fill the TABLES structure in a PBO module, make sure that data changes made by the user are not overwritten on the screen if the module gets called twice

SAP AG

TAW10

16-28

Syntax Example: Evaluating the Function Codes

DATA ok_code LIKE sy-ucomm.

. . MODULE user_command_0100 INPUT. CASE ok ok_ _ code code. . ok_code. WHEN 'BACK'. WHEN 'BACK'. SET SCREEN 0. MESSAGE s057(BC400). WHEN WHEN 'SAVE'. 'SAVE'. * calling a function module to save changes * is left out for didactical reasons SET SCREEN 0. MESSAGE s057(BC400). ENDCASE. ENDMODULE.

SAP AG 2001

For the example for evaluating function codes, two pushbuttons are discussed: Choosing BACK dynamically sets this value to 0. This sends the user back to the callpoint. In our case, this means the user returns to the basic list. Message 057 appears in the status bar of the next screen. With SAVE, the program behaves in the same way as BACK. The user returns to the basic list; however, there is a new message in the status bar. In the unit about Cross-Program Modularization, the program is enhanced with a data record change.

SAP AG

TAW10

16-29

Runtime Behavior for Special Situation: No Function Code Is Assigned to the ENTER Key
Basic list Screen 100
Screen field Data object

OK_CODE Double-click

ok_code
Transmit screen 100

BACK

BACK

Back to basic list

Double-click BACK BACK

Transmit screen 100

BACK
SAP AG 2001

BACK

Back to basic list?

Time

n n

This section walks through a particular scenario to point out the necessity of an additional program step. The user starts the program and double -clicks to display detailed information on the screen. After determining that all the data is correct the user returns to the basic list by choosing the green arrow. In this way, the function code BACK, which is assigned to this standard pushbutton, is placed in the command field and then it is transported automatically to the global data object ok_code of the ABAP program. This function code is then evaluated in a PAI module. The next screen is set to 0. Then AT LINE-SELECTION is processed further. If there is no WRITE statement there, the system displays the basic list again. The user then displays details for another record by double-clicking it. Through automatic field transport, the content of the global data object ok_code is transported into the screen field with the same name and the screen is displayed. If the user now chooses Enter, the screen is displayed once again, provided no function code has been assigned to the Enter key. (Standard case!) Therefore, the command field is not overwritten. The function code BACK remains in the command field and is copied to the global data object ok_code at the beginning of the PAI event. This function code is then evaluated in a PAI module. Consequently, as described above, the system goes back to the basic list, instead of displaying the screen again.

n n

SAP AG

TAW10

16-30

Solution Option: Deleting the Command Field for PBO

Screen Painter PROCESS BEFORE OUTPUT. MODULE MODULE clear clear_ clear_ok_code. _ok ok_ _ code code. .

ABAP Editor MODULE MODULE clear_ clear_ok_code clear_ ok ok_ _code OUTPUT. CLEAR ok_code. CLEAR ok_code. ENDMODULE. ENDMODULE.

Save

Back

PROCESS AFTER INPUT. MODULE user_command_0100. MODULE user_command_0100 INPUT. CASE ok_code. ... ENDMODULE.

SAP AG 2001

If the command field is not initialized, errors can occur since not every pushbutton must have a function code assigned to it. There are two ways to initialize a command field: Initialize the ok_code field in a PBO module. Then it is set to the initial value at PAI, unless the user has carried out a user action to which a function code is assigned. In this case, the ok_code field contains the current function code. Use an auxiliary field and copy the content of the ok_code field into the auxiliary field in a PAI module, then initialize the ok_code field. In this case, the auxiliary field must be queried in the PAI module for the function code evaluation.

SAP AG

TAW10

16-31

User Dialog Screen: Unit Summary

You are now able to: l Describe screen attributes and strengths l Write a program that: l Displays data on a screen l Allows the user to change some of that data l Allows the user to influence further program processing using pushbuttons

SAP AG 2001

SAP AG

TAW10

16-32

Screen
Unit: Screen Topic: Creating Screens
At the conclusion of these exercises, you will be able to: Create screens Call existing screens from the program

Exercises

The program SAPBC400UDT_DYNPRO_A enables you to display all bookings made by one travel agency as a list. As a first step, change the program as follows: A screen is to be called whenever the user double-clicks a line in the basic list. This screen should contain input fields for specific booking data that is not displayed on the list. This screen should also contain output fields for booking information that is already displayed on the list. Any user action should result in the basic list being displayed again Program: ZBC400_##_DYNPRO

Model solution: SAPBC400UDS_DYNPRO_A Template: SAPBC400UDT_DYNPRO_A

1-1

Copy the template SAPBC400UDT_DYNPRO_A to your new program ZBC400_##_DYNPRO. Become familiar with the program. Test the program using the travel agency number 1## (## is your group number). Selecting a line on the basic list (by double-clicking or using F2) should call a screen. Create this screen (screen number 100) using forward navigation. For the attributes, assign screen number 0 as the number of the next screen, so that after any user action on screen 100, the user returns to the basic list. Create input/output fields on the screen. When you are assigning field types, refer to ABAP ABAP Dictionary structure SDYN_BOOK. Copy booking table key fields CARRID, CONNID, FLDATE, and BOOKID with their field labels.

1-2

1-3

1-4

1-5

SAP AG

TAW10

16-33

The customer name NAME should be copied without a field label and should be displayed next to the customer number. The fields CUSTOMID, CUSTTYPE, SMOKER, CLASS, LOCCURAM, and LOCCURKEY should be copied with field labels.

1-6

Maintain the screen field attributes: Fields CARRID, CONNID, FLDATE, BOOKID, and CUSTOMID should be displayed as output fields (Output field attribute). The customer name NAME should be displayed next to the customer number without text (Output only attribute). The fields CUSTTYPE, SMOKER, CLASS, LOCCURAM, and LOCCURKEY are input/output fields (Input field/Output field attributes).

SAP AG

TAW10

16-34

Exercises
Unit: Screen Topic: Data Transport
At the conclusion of these exercises, you will be able to: Fill the screen fields with data from the program

Change your program ZBC400_##_DYNPRO: Double-clicking on a line of the basic list displays details of the selected booking on the screen. If the user changes data on the screen, then these changes should be available in the program once the user has left the screen. Program: ZBC400_##_DYNPRO

Model solution: SAPBC400UDS_DYNPRO_B

2-1 2-2 2-3

2-4

2-5

Change your program ZBC400_##_DYNPRO or copy the template SAPBC400UDS_DYNPRO_A to the new program ZBC400_##_DYNPRO_B. In your program, use the TABLES statement to create a work area with the same name. This work area will then serve as the screen interface. Ensure that the key fields of the SBOOK database table and the customer name are still available (HIDE: ...) in the AT LINE-SELECTION event block after a line has been selected on the basic list (double click or F2). Change your program accordingly so that data in the database can be changed. Make sure that the screen can be processed only if the user has change authorization for the airline selected. Before the screen is called, retrieve the data of the selected posting from the SBOOK database table into a suitable work area (name proposal: wa_sbook) To make sure that the data is up-to-date. If the data record cannot be read, the system must display information message 176 from message class BC400. If the data is read successfully, call the screen. Immediately before the screen is called, copy the relevant data into the TABLES work area.

SAP AG

TAW10

16-35

Exercises
Unit: Screen Topic: Field Transports and Subsequent Screen Processing
At the conclusion of these exercises, you will be able to: Create pushbuttons on screens Process the system code triggered when the user clicks on a pushbutton and thus control the program flow Set the next screen dynamically Change your program ZBC400_##_DYNPRO: On the screen, the user should be able to control program flow through two pushbuttons.

Program:

ZBC400_##_DYNPRO

Model solution: SAPBC400UDS_DYNPRO_C

3-1

Change your program ZBC400_##_DYNPRO or copy the template SAPBC400UDS_DYNPRO_B to the new program ZBC400_##_DYNPRO_C. Define two pushbuttons on the screen that allow the user to either return to the basic list (PUSH_BACK) or to save the changed data (PUSH_SAVE):

3-2

Name of pushbutton
PUSH_BACK PUSH_SAVE Back Save or icon

Text

Function code
BACK SAVE

ICON_SYSTEM_SAVE 3-3 3-4 Name the OK_CODE field on the screen and define a data object of the same name (and corresponding type) in the program. Navigate in the flow logic. Create a module for function code processing (using forward navigation) at PROCESS AFTER INPUT:

Function code
SAP AG

Action
TAW10

Next screen
16-36

Function code
BACK SAVE None First:

Action
List List

Next screen

Information message no. 060(BC400) All others None Screen 100

3-5

Ensure that pressing Enter always displays screen 100, regardless of the navigation history. Initialize the OK_CODE field in a PBO module.

SAP AG

TAW10

16-37

Screens
Unit: Screens Topic: Creating Screens

Solutions

Model Solution: Program SAPBC400UDS_DYNPRO_A

*&--------------------------------------------------------------* *& Report *& *& SAPBC400UDS_DYNPRO_A * * *

*&--------------------------------------------------------------* REPORT sapbc400uds_dynpro_a.

CONSTANTS actvt_display TYPE activ_auth VALUE '03'. * Definition of selection screen PARAMETERS pa_anum TYPE sbook-agencynum.

* workarea for select DATA: wa_booking TYPE sbc400_booking.

START-OF-SELECTION. * selecting data using an ABAP dictionary view to get the data from * sbook and the customer name from scustom SELECT carrid connid fldate bookid customid name FROM sbc400_booking INTO CORRESPONDING FIELDS OF wa_booking WHERE agencynum = pa_anum. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD wa_booking-carrid ID 'ACTVT' IF sy-subrc = 0.
SAP AG TAW10 16-38

FIELD actvt_display.

* Output WRITE: / wa_booking-carrid COLOR col_key, wa_booking-connid COLOR col_key, wa_booking-fldate COLOR col_key, wa_booking-bookid COLOR col_key, wa_booking-name.

ENDIF. ENDSELECT. AT LINE-SELECTION. CALL SCREEN 100.

1-3

Create a screen using forward navigation (double-click 100 in the CALL SCREEN 100 statement). Maintain screen attributes - Enter a descriptive short text - Set the next screen to 0

1-4

1-5

Layout - Navigate to the Graphical Layout Editor - Choose the Dict/Program fields icon - Enter SDYN_BOOK - Choose the Get from Dictionary icon - Select the fields you want choose Enter to confirm, and drag these fields to the screen - 1st Block:
Copy key fields : CARRID, CONNID, FLDATE, and BOOKID with field names - 2nd Block: Copy customer name NAME without a field name (choose the Without text radio button) - 3rd Block: Copy the fields : CUSTOMID, CUSTTYPE, SMOKER, CLASS, LOCCURAM, and LOCCURKEY with field names

1-6
SAP AG

Change the field attributes TAW10 16-39

for example, by double -clicking the input field - Change the attributes: - The fields CARRID, CONNID, FLDATE, BOOKID, and CUSTOMID should be displayed as output fields (Output field attribute). - The customer name NAME should be displayed next to the customer number without text (Output only attribute). - The fields CUSTTYPE, SMOKER, CLASS, LOCCURAM , and LOCCURKEY should be both input-ready and output-ready (the Input/Output field attribute).
.

SAP AG

TAW10

16-40

Solutions
Unit: Screens Topic: Data Transport

Model Solution: Program SAPBC400UDS_DYNPRO_B


*&--------------------------------------------------------------* *& Report *& *& SAPBC400UDS_DYNPRO_B * * *

*&--------------------------------------------------------------* REPORT sapbc400uds_dynpro_b.

CONSTANTS: actvt_display TYPE activ_auth VALUE '03', actvt_change TYPE activ_auth VALUE '02'. * Definition of selection screen PARAMETERS pa_anum TYPE sbook-agencynum.

* workarea for list DATA wa_booking TYPE sbc400_booking. * workarea for single booking to be changed DATA wa_sbook TYPE sbook. * workarea for dynpro TABLES sdyn_book.

START-OF-SELECTION. * selecting data using an Adictionary view to get the data from * sbook and the customer name from scustom SELECT carrid connid fldate bookid customid name FROM sbc400_booking INTO CORRESPONDING FIELDS OF wa_booking WHERE agencynum = pa_anum. AUTHORITY-CHECK OBJECT 'S_CARRID'
SAP AG TAW10 16-41

ID 'CARRID' FIELD wa_booking-carrid ID 'ACTVT' IF sy-subrc = 0. * Output WRITE: / wa_booking-carrid COLOR col_key, wa_booking-connid COLOR col_key, wa_booking-fldate COLOR col_key, wa_booking-bookid COLOR col_key, wa_booking-name. HIDE: wa_booking-carrid, wa_booking-connid, wa_booking-fldate, wa_booking-bookid, wa_booking-name. ENDIF. ENDSELECT. AT LINE-SELECTION. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD wa_booking-carrid ID 'ACTVT' IF sy-subrc = 0. SELECT SINGLE * FROM sbook INTO wa_sbook WHERE carrid = wa_booking-carrid AND connid = wa_booking-connid AND fldate = wa_booking-fldate AND bookid IF sy-subrc = 0. MOVE-CORRESPONDING wa_sbook TO sdyn_book. MOVE wa_booking-name TO sdyn_book-name. CALL SCREEN 100. ENDIF. ELSE . MESSAGE ID 'BC400' TYPE 'S' NUMBER '047' WITH wa_booking-carrid. ENDIF.
SAP AG TAW10 16-42

FIELD actvt_display.

FIELD actvt_change.

= wa_booking-bookid.

Unit: Screens Topic: Field Transports and Subsequent Screen Processing

Model Solution: Program SAPBC400UDS_DYNPRO_C

*&--------------------------------------------------------------* *& Report *& *& SAPBC400UDS_DYNPRO_C * * *

*&--------------------------------------------------------------* REPORT sapbc400uds_dynpro_c. actvt_change TYPE activ_auth VALUE '02'. * Definition of selection screen PARAMETERS pa_anum TYPE sbook-agencynum.

CONSTANTS: actvt_display TYPE activ_auth VALUE '03',

* workarea for list DATA wa_booking TYPE sbc400_booking. * workarea for single booking to be changed DATA wa_sbook TYPE sbook. * workarea for dynpro TABLES sdyn_book. * variable for function code of user action DATA ok_code LIKE sy-ucomm.

START-OF-SELECTION. * selecting data using a dictionary view to get the data from * sbook and the customer name from scustom SELECT carrid connid fldate bookid customid name FROM sbc400_booking INTO CORRESPONDING FIELDS OF wa_booking
SAP AG TAW10 16-43

WHERE agencynum = pa_anum.

AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD wa_booking-carrid ID 'ACTVT' IF sy-subrc = 0. * Output WRITE: / wa_booking-carrid COLOR col_key, wa_booking-connid COLOR col_key, wa_booking-fldate COLOR col_key, wa_booking-bookid COLOR col_key, wa_booking-name. HIDE: wa_booking-carrid, wa_booking-connid, wa_booking-fldate, wa_booking-bookid, wa_booking-name. FIELD actvt_display.

ENDIF. ENDSELECT. CLEAR wa_booking. AT LINE-SELECTION. AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD wa_booking-carrid ID 'ACTVT' IF sy-subrc = 0. SELECT SINGLE * FROM sbook INTO wa_sbook WHERE carrid = wa_booking-carrid AND connid = wa_booking-connid AND fldate = wa_booking-fldate AND bookid IF sy-subrc = 0. MOVE-CORRESPONDING wa_sbook TO sdyn_book.
SAP AG TAW10 16-44

FIELD actvt_change.

= wa_booking-bookid.

MOVE wa_booking-name TO sdyn_book-name. CALL SCREEN 100. ENDIF. ELSE . MESSAGE ID 'BC400' TYPE 'S' NUMBER '047' WITH wa_booking-carrid. ENDIF. CLEAR: wa_sbook, wa_booking. *&--------------------------------------------------------------* *& *& Module text CLEAR_OK_CODE OUTPUT * *

*&--------------------------------------------------------------* *&--------------------------------------------------------------* MODULE clear_ok_code OUTPUT. CLEAR ok_code. ENDMODULE. " CLEAR_OK_CODE OUTPUT

*&--------------------------------------------------------------* *& *& Module text USER_COMMAND_0100 INPUT * * *&--------------------------------------------------------------* *&--------------------------------------------------------------* MODULE user_command_0100 INPUT. CASE ok_code. WHEN 'BACK'. LEAVE TO SCREEN 0. WHEN 'SAVE'. MOVE-CORRESPONDING sdyn_book TO wa_sbook. MESSAGE ID 'BC400' TYPE 'I' NUMBER '060'. LEAVE TO SCREEN 0. ENDCASE. ENDMODULE. " USER_COMMAND_0100 INPUT

SAP AG

TAW10

16-45

Global Modularization

Contents:
l Function Groups and Function Modules l Working with Methods l Working with BAPIs

SAP AG 2003

SAP AG

TAW10

17-1

Global Modularization: Unit Objectives

At the conclusion of this unit, you will be able to: l Create function groups and function modules l Add function module calls to your program l Add object instantiations and method calls to your program l Add the ALV grid control to display data in a fixed screen area l Create information using BAPIs l Add BAPI calls to your program.

SAP AG 2003

SAP AG

TAW10

17-2

Working with Function Modules

Function Function Groups Groups and and Function Function Modules Modules Working Working with with Methods Methods Working Working with with BAPIs BAPIs

SAP AG 2003

SAP AG

TAW10

17-3

Function Module

Function Module
Attributes Local data objects Source code Interface
Import Import parameters Import parameters parameters Export parameters Export Changing parameters Exceptions

sy-subrc
SAP AG 2001

n n n

Function modules are actively integrated modularization units with an interface. Function modules can, therefore, be called specifically from within programs or function modules. The interface of a function module can contain the following elements: Import parameters are passed to the function module. In general, these parameters are assigned standard ABAP Dictionary types. Import parameters can also be optional. Export parameters are received from the function modules. Export parameters are always optional. Changing parameters are passed to the function module and can be changed by it. Exceptions provide information about error situations. If a function module initiates an exception, processing of the function module is interrupted. It is possible to set a return code, if necessary, in the calling program. As is the case with subroutines, a function module can contain local type and data object definitions.

SAP AG

TAW10

17-4

Function Group

ti nc u F

e le ac odu f r e M Int on 1
FM

Global data objects Subroutine Interface

Fu Int nc erf tion ac e FM Mo 2 dul e


Fun ction M FM3 odule I

ule Mod tion Func M5

Screen

Function Module FM4

Interface Interface

SAP AG 2001

n n

A function group represents the main program for function modules. Several function modules that operate on the same data content are combined to form a function group. The function group remains active for as long as the calling program is active. For example, if an executable program calls a function module, its entire function group is loaded as well. It remains active until the executable program is completed. A function group can contain the same components as an executable program. These include: Data Objects These are then global in relation to the function group, that is, they are visible to and changeable by all function modules within the group. The validity period is the same as for the function group. Subroutines These can be called from all function modules in the group. Screens These can be called from all function modules in the group.

SAP AG

TAW10

nter face

F face Inter

17-5

Data Flow Within a Function Group

tion 1 nc FM u F

e dule ce a ac f f r r e Mo Int

Fu Int nc erf tion ac e FM Mo 2 dul e


Fun ction M FM3 odule I

ule Mod tion Func M5

Function Module FM4

Interface Interface
SAP AG 2001

n n n n

The global data of a function module is retained until the program that contained the first call of a function module in the function group is finished. Thus, if a function module that writes values to the global data is called, other function modules in the same function group can access this data when the program calls them. Seen from the outside, the global data is encapsulated, that is, it is not possible to access it directly. Therefore, you must have function modules that allow orderly access from the outside. The same applies to all the other components of the function group (screens, subroutines).

SAP AG

TAW10

Inter face

F face Inter

17-6

Attributes
Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Function module documentation Function module BC402_FMDD_GET_FREE_SEATS active

Attributes
Classification

Import

Export

Changing

Tables

Exceptions

Source code

Function group Short text


Processing type

BC402_FMDD_FLIGHT

Function modules demonstration

Calculates number of free seats


General data

Normal function module Remote-enabled module Update module


Development class BC402

SAP AG 2002

In the Attributes of a function module, you specify its general administrative data and the processing type : nRemote-enabled function modules can be called asynchronously in the same system and can be called from other systems (not just R/3 Systems). To call a function module in another system, there must be a valid system connection. For further information, refer to the course BC415 Communications Interfaces in ABAP or the online documentation. nUpdate function modules contain additional functions for bundling database changes. For further information, refer to the course BC414 - Programming Database Updates or the online documentation.

The online documentation also details the interface restrictions that apply to remote-enabled and update function modules.

SAP AG

TAW10

17-7

Interface
Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Function module documentation Function module BC402_FMDD_GET_FREE_SEATS active

Attributes

Import

Export

Changing

Tables

Exceptions

Source code

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Parameter name Type Reference type Default value IP_PLANETYPE TYPE S_PLANETYE IP_SEATSOCC TYPE S_SEATSMAX 0 Funktionsbaustein BC402_FMDD_GET_FREE_SEATS Optional Pass value Short text Function module documentation Plane type ! ! Occupied seats aktiv

Attributes Parameter name EP_SEATSFREE

Import Type TYPE

Export

Changing

Tables Short text Seats free

Exceptions

Source code

Reference type Pass value S_SEATSMAX !

SAP AG 2002

Three kinds of parameters can be used to exchange data with function modules: Importing parameters, which are received by the function module Exporting parameters, which are returned by the function module Changing parameters, which are both received and returned By default, all parameters are passed by reference . You can change exporting and changing parameters only in the function module. This rule ensures that you avoid unwanted side effects. If you want to pass parameters by value , you must select the relevant option when you define the interface. You can also declare importing and changing parameters as optional. You do not have to pass values to these parameters when you call the function module. Where possible, use this option when you add new parameters to function modules that are already in use. You can assign a default value to an optional parameter. If you do not pass a value of your own when you call the function module, the system then uses the default value instead. Exporting parameters are always optional. You may specify the type of an elementary parameter. You must specify the type of a structured or table parameter. You can use either ABAP Dictionary types, ABAP Dictionary objects, predefined ABAP type (i,f,p,n,c,string,x,xstring,d,t) or user-defined types. Any type conflicts show up in the extended program check. You can also assign a reference type. Table parameters are obsolete for normal function modules but have been retained to ensure compatibility for function modules with other execution modes.

SAP AG

TAW10

17-8

Processing Logic
Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Function module documentation Function module BC402_FMDD_GET_FREE_SEATS active

Attributes

Import

Export

Changing

Tables

Exceptions

Source code

FUNCTION bc402_fmdd_get_free_seats. *"--------------------------------*"*"Local Interface: *" IMPORTING *" EXPORTING *" EXCEPTIONS *"--------------------------------... ENDFUNCTION.

SAP AG 2002

When you save the interface, the system generates the statement framework together with the comment block that lists the interface parameters:
FUNCTION name. *"-------------*" ... *"-------------... ENDFUNCTION.

The comment block is updated automatically if you make changes to the function module later on. This means that you can always see the interface definition when you are coding the function module. You program the statements exactly as you would in any other ABAP program in the ABAP Editor. In the function module, you can create your own local types and data objects and call subroutines or other function modules.

SAP AG

TAW10

17-9

Exceptions
Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Function module documentation Function module BC402_FMDD_GET_FREE_SEATS active

Attributes Exception NO_SEATS OVERLOAD DB_FAILURE

Import

Export

Changing Short text Cargo plane Overbooked No data

Tables

Exceptions

Source code

RAISE <exception>. *** with default message: MESSAGE <kind><num>(<id>) RAISING <exception>.
SAP AG 2002

You can make a function module raise exceptions . To do this, you must first declare the exceptions in the interface definition, that is, assign each one a unique name. In the source code of your function module, you program the statements that

raise an exception under the required condition. At runtime, the function module is terminated when an exception is triggered. The changes to exporting and changing parameters are the same as in subroutines. You can use two statements to raise an exception. In the forms given below, exception stands for the name of an exception that you declared in the interface. The system reacts differently according to whether or not the exception was listed in the function module call:
RAISE exception.

If the exception is listed in the calling program, the system returns control to it directly.
If the exception is not listed, a runtime error occurs. MESSAGE <kind><num>(<id>) RAISING <exception>. NOTE: If the exception is listed in the calling program, the statement has the same effect as RAISE <exception>. If it is not listed, the system sends message <num> from message

class <id> with type <kind>, and no runtime error occurs.

SAP AG

TAW10

17-10

Documenting, Activating, and Testing


l Function module documentation
n

Short text and long text

w w
n

Parameters Exceptions

Functions, notes, and so on

l Worklist
n n n

Revised version Inactive version Active version

l Function testing, debugging


n n n

Supplying values for parameters Exceptions Messages

SAP AG 2002

Function modules differ from subroutines in that you must assume that other programmers will use them. For this reason, you should ensure that you complete the steps listed here:

Documentation (can be translated)


You should document all your parameters and exceptions, along with your entire function module, with short text (and long text if necessary). The system provides a text editor for you

to do this, containing predefined sections for Functions, Example Call, Hints, and Further Information. Work list When you change an active function module, it acquires the status active (revised). When you save it, another version is created with the status inactive . When you are working on a function module, you can switch between the inactive version and the last version that you activated. When you activate the inactive version, the previous active version is overwritten.

Function test
Note: Once you have activated your function module, you can test it using the built-in

test environment in the Function Builder. If an exception is triggered, the test environment displays it, along with any message that you may have specified for it. You can also switch into the Debugger and the Runtime Analysis. You can save test data and compare sets of results.

SAP AG

TAW10

17-11

Call
DATA: result TYPE s_seatsmax. PARAMETERS: pa_type TYPE s_planetye, pa_occ

TYPE s_seatsmax.

CALL ' CALL FUNCTION FUNCTION ' 'BC402_FMDD_GET_FREE_SEATS' EXPORTING EXPORTING ip_planetype = pa_type ip_seatsocc = pa_occ " default: 0 IMPORTING IMPORTING IMPORTING Insert pattern ep_seatsfree = result CALL FUNCTION BC402_ FMDD_GET_FREE_SEATS EXCEPTIONS ... no_seats = 1 1 ... overload = 2 2 ... OTHERS = 3. ... ... CASE sysy-subrc. sy-subrc. WHEN 0. WRITE: / result COLOR 5. WHEN 1. WRITE: / 'You''ll have to stand, it''s a freighter!'(frt). WHEN 2. WRITE: / 'The plane has already been overloaded!'(nos). WHEN 3. WRITE: / 'Please contact your system administrator!'(adm). ENDCASE.
SAP AG 2002

When you insert a function module call in your program, you should use the Pattern function. Then, you only need to enter the name of the function module (input help is available). The system then inserts the call and the exception handling (MESSAGE statement) into your program. You assign parameters by name. The formal parameters are always on the left side of the expressions: Exporting parameters are passed by the program. If a parameter is optional, you do not need to pass it. Default values are displayed if they exist.
optional.

Importing parameters are received by the function module. Importing parameters are always
Changing parameters are both passed and received. You do not have to list optional parameters. Default values are displayed if they exist. The system assigns a value to each exception, beginning at one and continuing to number them sequentially in the order they are declared in the function module definition. You can assign a value to all other exceptions that you have not specifically listed using the special exception OTHERS. If you list the exceptions and one is triggered in the function module, the corresponding value is placed in the return code field sy-subrc. If you did not list the exception in the function call, a runtime error or a message occurs, depending on the statement you used in the function module to trigger the exception.

SAP AG

TAW10

17-12

Organization of a Function Group


Object list Edit Goto Utilities Environment System Help

Object Navigator

Workbench Edit

Goto

Extras

Environment System Help

Object list
Development class program Function group Class Local objects

Object Navigator

Object name
BC402_FMDD_WAITLIST

> < < < < < >

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

Display

PBO modules Global declarations Function modules

Add waiting customer Remove waiting customer Display waiting list Shift waiting list Return position in waiting list Change position in list

Include modules in program


SAP AG 2002

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<rem_name>. The system then creates a type F program called SAPLY|Z<rem_name>, which contains automatically generated INCLUDE statements. The include programs are also named automatically: LY|Z<rem_name><abbrev><num>. The system also inserts the include program, LY|Z<rem_name>UXX, which contains an include statement in the form LY|Z<rem_name>U<num> for each function module.

SAP AG

TAW10

17-13

Working with Methods

Function Function Groups Groups and and Function Function Modules Modules Working Working with with Methods Methods Working Working with with BAPIs BAPIs

SAP AG 2003

SAP AG

TAW10

17-14

Classes and Objects

Name Attributes (data objects): attr1 attr2 ... Methods (functions): meth1 meth2 ... meth1 123 attr1 attr2 ... meth2 meth1 8 attr1 attr2 ... meth2

meth1 Class: technical description of objects


SAP AG 2001

4711 attr1 attr2 ... meth2

Objects: Runtime instances in a class

At first glance, a class is very much like a function group since it contains data objects (attributes) and functions (methods). These components can be protected from access by components of other programs. Then they can be accessed only by methods belonging to the class. In contrast to function groups, classes can have multiple instances, that is, more than one runtime object can be created for each program in a class. In other words, a class contains the technical description of objects (instances). All these objects, therefore, have the same attributes and provide the same methods. However, they can be distinguished physically. Their attributes can have different features. Classes can be defined either locally within an executable program or globally in the Class Builder. The ABAP runtime system provides support for standard object-oriented syntax elements as of Release 4.6A. For more details, refer to the SAP online library.

n n

SAP AG

TAW10

17-15

Creating Objects and Calling Methods


ref1 DATA ref1 TYPE REF TO class. DATA ref2 TYPE REF TO class. CREATE OBJECT ref1 ... meth1 ref2

CREATE OBJECT ref2 ... CALL METHOD ref1->meth1 EXPORTING ... IMPORTING ... EXCEPTIONS ... CALL METHOD ref2->meth1 EXPORTING ... IMPORTING ... EXCEPTIONS ... ...
SAP AG 2001

meth1

ABAP program

To create instances of classes and to be able to access them, you need reference variables, which are pointers to these instances. You define these reference variables using DATA reference_name TYPE REF TO class_name. At program start, the data objects are created in memory. However, since no instances have been created yet, the reference variables are still empty. At runtime, you can create as many instances of classes as you wish using CREATE OBJECT reference_name. If necessary, the import parameters of the special method CONSTRUCTOR must be filled with values. This special method is executed immediately after the instance is created. As a rule, basic settings for the actual instance are thus created. You can call methods of an instance using CALL METHOD reference_name->method_name. In contrast to a function module call, the method name is not sufficient here because, generally, several instances of a class exist for each program. Using the reference variable, followed by the object component selector -> , you instruct a particular instance to execute its method.

n n

SAP AG

TAW10

17-16

Examples of Standard Classes: EnjoySAP Controls

Picture Control

Airlines AA 0017 0064 LH 0400 0402 Tree Control


SAP AG 2001

http://www.sap.com

HTML Viewer Control

As of Release 4.6A, the ABAP Workbench offers several new EnjoySAP controls in order to move dialog functions from the application server to the presentation server. These controls are called on an object-oriented basis using classes, that is, the SAP Control Framework . For each method call, you select the controls from your ABAP program. The Control Framework sends your requests to the presentation server where they are converted on a platform-specific basis. You can give the user the option of triggering events on the presentation server. The Control Framework then converts these events and you can react to them in your ABAP program. For more details on the EnjoySAP controls and the Control Framework, refer to the SAP online library.

n n n

SAP AG

TAW10

17-17

Working with BAPIs

Function Function Groups Groups and and Function Function Modules Modules Working Working with with Methods Methods Working Working with with BAPIs BAPIs

SAP AG 2003

SAP AG

TAW10

17-18

Business Application Programming Interface

A BAPI is a well-defined interface to processes and data of a business application system, implemented as a business object method in the Business Object Repository (BOR).

BAPI

SAP AG 2001

n n n

A BAPI can be viewed as the door to the SAP system; this interface provides access to business data and processes in the SAP system from the outside. Each object in the BOR can have several methods, one or more of which can be implemented as BAPIs. BAPIs usually exist for basic functions of a business object, such as: Creating objects Querying the attributes of an object Changing the attributes of an object

SAP AG

TAW10

17-19

BAPI Usage

Distributed scenarios (ALE)

Customers and partner's own code

JAVA, C, ...

Internet / Intranet

Business Component

Business B Component

R/3 Component Creation


SAP AG 2001

Business Component

Business Workflow

A BAPI can be used for various applications. For example: Internet application components: Depiction of individual SAP R/3 functions in the Internet or intranet - for example, for users who do not have SAP R/3 experience. R/3 component creation: Communication between the business objects of different SAP R/3 components (solutions). Customers or partners code: External clients (for example, alternative GUIs) directly access business data and processes of the SAP R/3 System. In particular, BAPI calls (as calls of RPCenabled function modules also) can be implemented in other programming languages.

SAP AG

TAW10

17-20

Standardized BAPIs

l GetList Supplies a list of object key fields that satisfy selected criteria (search function) l GetDetail Supplies detailed information (attributes) on an object (the full key must be specified) l Create, Change, Delete, Cancel Creating, changing, and deleting objects l AddItem, RemoveItem Creating and removing subobjects (for example, item in an order)

SAP AG 2001

n n

There are standard methods for BAPIs with standardized names. Some of the most important standard method names are listed here.

SAP AG

TAW10

17-21

Finding BAPI Function Modules

Hierarchy

Alphabetical

Detail

Documentation

Tools

Project

Method (BAPI) FlightBooking FlightCustomer FlightConnection AirlineCarrier ConnectionNumber DateOfFlight GetDetail Return FlightData GetList Method Business object Short text New as of release Function module GetDetail FlightBooking Flight details 40C BAPI_SFLIGHT_GETDETAIL

Double-click: Navigation in Function Builder

SAP AG 2001

n n

In Release 4.6C, BAPIs are implemented using function modules. From the SAP Easy Access menu, you call the BAPI Explorer by choosing Tools Business Framework BAPI Browser. Using the BAPI Explorer, you can navigate to the function module display for the selected BAPI in the Function Builder. Select the BAPI in the hierarchy section. In the detailed display window, choose the Detail tab. By double-clicking on the name of the function module, you can display it in the Function Builder.

SAP AG

TAW10

17-22

Characteristics of a BAPI Function Module


Error messages through EXPORT parameter RETURN (structure or internal table)

Interface parameters typed with a Dictionary structure that is compiled for the BAPI

No CHANGING parameters No exceptions

Structure of BAPI_name

Interface
Remote capability

Source code

SAP System
SAP AG 2001

Function group

No user dialogs

Function modules for BAPIs must fulfill the following requirements: Naming convention BAPI_<business_object_name>_<method_name> must be used Remote capability No user dialogs, neither screens nor messages, allowed Interface parameters must be typed with a Dictionary structure that was created for this BAPI Structures must comply with the naming convention BAPI_<structure_name> and are changed only on a compatible basis No CHANGING parameters allowed No exceptions allowed. Errors are reported to the user through the special export parameter RETURN.

SAP AG

TAW10

17-23

Calling a BAPI Function Module from an ABAP Program


ABAP program BOR

BACV

For currency and quantity fields: Possible conversion to "external format" CALL FUNCTION 'BAPI_...' EXPORTING ... IMPORTING ... return = ... For currency and quantity fields: Possible conversion to "external format"

SAP AG 2001

n n n

If you would like to use a BAPI in the SAP R/3 System, you can call the function module containing it. Pay attention to the limitations already mentioned. BAPI interfaces are created according to the needs for the "external" call, that is, from a non-R/3 System. Quantities are expected in an external format with 4 or 9 decimal places. The quantities must be transferred to the interface in converted format, even if the corresponding currency has no decimal places. For this conversion you can use function modules from the BACV function group (development class SBF_BAPI).

SAP AG

TAW10

17-24

Global Modularization: Unit Summary

You are now able to: l Create function groups and function modules l Add function module calls to your program l Add object instantiations and method calls to your program l Add the ALV grid control to display data in a fixed screen area l Create information using BAPIs l Add BAPI calls to your program.

SAP AG 2003

SAP AG

TAW10

17-25

Function Groups and Function Modules Exercises


Unit: Global Modularization Topic: Creating and Calling Function Groups and Function Modules
At the conclusion of these exercises, you will be able to: Create and implement function groups Implement function modules Call function modules You are a developer for an airline consortium. Your task is to develop evaluation programs for several airlines.

1. All plane types that are available for each airline should be stored in a function group in an internal table. For simplicity, these should have a flat line structure and not a nested structure. ## is your two-digit group number Model solution: TAW10_BASICS_FLIGHT

1-1 1-2

Create function group Z##_TAW10_FLIGHT. Assign it to message class TAW10. You can find the program ID in the "TOP include" (LTAW10_BASICS_FLIGHTTOP).

1-3

Document your function group.

SAP AG

TAW10

17-26

2. A function module should fill internal tables for plane types. Only the available replacement types for the airline with sufficient seats should be written to the table. From the total prices that are transferred, the average price for each seat should also be calculated. The plane list should then be sorted in descending order before it is returned. ## is your two-digit group number Model solutions: TAW10_BASICS_FLIGHT TAW10_BASICS_CREATE_PLANELIST

2-1

Create function module Z_##_TAW10_CREATE_PLANELIST within your function group Z##_TAW10_FLIGHT. Declare the line type t_carr_plane as your function groups global data type. It should be structured as follows: Component carrid planetype seatsmax Type scarplan-carrid scarplan-planetype saplane-seatsmax

2-2

The line type assigns the airline to the plane type. 2-3 Declare the internal table it_carr_planes with line type t_carr_plane as the global data object of your function group. It should be in the form of a sorted table with the unique key carrid and planetype. Fill the internal table it_carr_planes for each array fetch using view TAW10_CARPLAN. Choose an appropriate time for the event to occur. Remember that a function group cannot be executed directly. Implement the corresponding event block in a suitable include program that you have added to the main program at a suitable location. Adhere to the naming conventions for function group include programs. 2-5 Now declare the import parameter with pass by value for your function module: ip_seatsocc as an optional parameter with the default value 0, ip_carrid, ip_paymentsum, ip_currency. Declare the export parameter ep_planelist with pass by value. Assign a type using the global table type TAW10_TYPS_PLANETAB. Declare the exception no_planes and document it.

2-4

2-6

2-7

SAP AG

TAW10

17-27

2-8

In the function module, create local structure l_wa_carr_plane of type t_carr_plane. From the global internal table, read those plane types that are available to the airline and which have sufficient seats for the booking that was transferred. In this loop calculate the average price for each seat for each plane type. Also declare work area l_wa_plane as a local data object within the function module. Assign a type using the global structure TAW10_TYPS_PLANE. Attach the completely filled work area to the internal table to be exported. Before exporting, sort the internal table by the average price per seat. Trigger the exception if no suitable plane types could be found. Implement the trigger using error message 040, specifying the airline. Document your function module. Test your function module.

2-9

2-10 2-11

2-12 2-13

SAP AG

TAW10

17-28

3. If a plane breaks down that is already scheduled for a flight and already has bookings, a replacement plane must be used. Write a program that outputs all the available replacement plane types for each airline in a list. You can obtain the data for the list using the function module you created in Task 2. Model solution: TAW10_BASICS_CALL_FUNCTION

3-1 3-2

Create a new program Z##_TAW10_SUBSTITUTE_PLANES. In the program, define an internal table it_planelist that stores the replacement plane types. The type of this internal table results from the function module interface. The user should query the IMPORTING parameters of the function module using a selection screen, where the field for the airline must be a mandatory field. Call your function module Z_##_TAW10_CREATE_PLANELIST (use Sample) and populate the interface. Catch the exceptions with appropriate error messages (error messages 40 and 41 of message class TAW10). Ensure that users return to the selection screen when an exception occurs. Display the table it_planelist filled by the function module in a list. Use a field symbol for this.

3-3

3-4

3-5

SAP AG

TAW10

17-29

Function Groups and Function Modules Solutions


Unit: Global Modularization Topic: Creating and Calling Function Groups and Function Modules

1-1, 2-4

Model solution SAPLTAW10_BASICS_FLIGHT

************************************************************** * System-defined Include-files. ************************************************************** INCLUDE ltaw10_basics_flighttop. " Global Data INCLUDE ltaw10_basics_flightuxx. " Function Modules ************************************************************** * User-defined Include-files (if necessary). ************************************************************** INCLUDE ltaw10_basics_flighttop. " Subprograms * INCLUDE LTAW10_BASICS_FLIGHTO... " PBO-Modules * INCLUDE LTAW10_BASICS_FLIGHTI... " PAI-Modules INCLUDE ltaw10_basics_flighte01. " Events

1-2, 2-2, 2-3

Model solution LTAW10_BASICS_FLIGHTTOP

FUNCTION-POOL TAW10_BASICS_FLIGHT MESSAGE-ID taw10.

TYPES: BEGIN OF t_carr_plane, carrid TYPE scarplan-carrid, planetype TYPE scarplan-planetype, seatsmax TYPE saplane-seatsmax, END OF t_carr_plane.

DATA: it_carr_planes TYPE SORTED TABLE OF t_carr_plane WITH UNIQUE KEY carrid planetype.

SAP AG

TAW10

17-30

2-4

Model solution LTAW10_BASICS_FLIGHTE01

*------------------------------------------------------------* * INCLUDE LTAW10_BASICS_FLIGHTE01 * *------------------------------------------------------------* LOAD-OF-PROGRAM. SELECT carrid planetype seatsmax FROM taw10_carplan INTO CORRESPONDING FIELDS OF TABLE it_carr_planes.

2-1, 2-5 2-11

Model solution TAW10_BASICS_CREATE_PLANELIST

FUNCTION TAW10_BASICS_CREATE_PLANELIST. *"-----------------------------------------------------------*"*"Local interface: *" IMPORTING *" VALUE(IP_SEATSOCC) TYPE SFLIGHT-SEATSOCC DEFAULT 0 *" VALUE(IP_CARRID) TYPE SPFLI-CARRID *" VALUE(IP_PAYMENTSUM) TYPE SFLIGHT-PAYMENTSUM *" VALUE(IP_CURRENCY) TYPE SFLIGHT-CURRENCY *" EXPORTING *" VALUE(EP_PLANELIST) TYPE TAW10_TYPS_PLANETAB *" EXCEPTIONS *" NO_PLANES *"-----------------------------------------------------------DATA: l_wa_carr_plane TYPE t_carr_plane, l_wa_plane TYPE taw10_typs_plane. LOOP AT it_carr_planes INTO l_wa_carr_plane WHERE carrid EQ ip_carrid AND seatsmax GE ip_seatsocc. l_wa_plane-planetype = l_wa_carr_plane-planetype. l_wa_plane-seatsmax = l_wa_carr_plane-seatsmax. l_wa_plane-avg_price = ip_paymentsum / l_wa_carr_plane-seatsmax. l_wa_plane-currency = ip_currency. APPEND l_wa_plane TO ep_planelist. ENDLOOP. IF sy-subrc NE 0. MESSAGE e040 RAISING no_planes WITH ip_carrid. ELSE. SORT ep_planelist BY avg_price DESCENDING. ENDIF. ENDFUNCTION.

SAP AG

TAW10

17-31

Model solution TAW10_BASICS_CALL_FUNCTION

*&-----------------------------------------------------------* *& Report TAW10_BASICS_CALL_FUNCTION * *& * *&-----------------------------------------------------------* *& solution of exercise 3 function groups * *& and function modules * *&-----------------------------------------------------------* REPORT taw10_basics_call_function.

DATA: FIELD-SYMBOLS:

it_planelist TYPE taw10_typs_planetab. <plane> TYPE LINE OF taw10_typs_planetab.

PARAMETERS: pa_carr pa_occ

TYPE sflight-carrid OBLIGATORY, TYPE sflight-seatsocc,

pa_paysu TYPE sflight-paymentsum, pa_curr TYPE sflight-currency DEFAULT 'EUR'.

AT SELECTION-SCREEN.

CALL FUNCTION 'TAW10_BASICS_CREATE_PLANELIST' EXPORTING ip_seatsocc ip_carrid = pa_occ = pa_carr

ip_paymentsum = pa_paysu ip_currency IMPORTING ep_planelist EXCEPTIONS no_planes OTHERS = 1 = 2. = it_planelist = pa_curr

CASE sy-subrc.

WHEN 1. MESSAGE e040(taw10) WITH pa_carr.

WHEN 2. MESSAGE e041(taw10).

SAP AG

TAW10

17-32

ENDCASE.

START-OF-SELECTION.

LOOP AT it_planelist ASSIGNING <plane>.

WRITE: / <plane>-planetype, <plane>-seatsmax, <plane>-avg_price CURRENCY <plane>-currency, <plane>-seatsmax,

ENDLOOP.

SAP AG

TAW10

17-33

Calling Programs and Passing Data

Contents:
l Techniques for calling programs l Memory model l Techniques for passing data l Use

SAP AG 2002

SAP AG

TAW10

18-1

Calling Programs and Passing Data: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the SAP R/3 memory model l Call executable programs l Call transactions l Use the various memory areas to pass data

SAP AG 2002

SAP AG

TAW10

18-2

Calling Programs and Passing Data (1)

Calling Calling programs programs Memory Memory management management Passing Passing data data

SAP AG 2002

SAP AG

TAW10

18-3

Calling Programs

Time

Main memory

Main memory

1
Insert program Insertion

1
New program

2
End insert Restart

1 2

Program 1 Program 2

SAP AG 2002

There are two ways of starting an ABAP program from another ABAP program that is already running:
n n

The called program is inserted, that is the current program is interrupted to run the new one. The called program is executed, and afterwards, processing returns to the program that called it. The current program is terminated and the called program is started. Complete ABAP programs within a single user session can only run sequentially. We refer to this technique as sequential calling .

If you want to run functions in parallel, you must use function modules. For further information about this technique, refer to the course BC415 (Communication Interfaces in ABAP) or the documentation for the CALL FUNCTION ... STARTING NEW TASK ... statement.

SAP AG

TAW10

18-4

Calling an Executable Program


Program 1
Restart

Program 2

... SUBMIT prog_name_2. ...

prog_name_2
PROGRAM ... ...

List

F3
... SUBMIT prog_name_2 AND RETURN. ... Insertion

prog_name_2
PROGRAM ... ...

List

... SUBMIT prog_name_2 VIA SELECTION-SCREEN AND RETURN. ...

Insertion

Selection Screen

F3

prog_name_2
PROGRAM ... ...

Liste

F3
SAP AG 2002

F3

To start an executable program, use the SUBMIT statement. If you use the VIA SELECTION-SCREEN addition, the system displays the standard selection screen of the program (if one has been defined). If you use the AND RETURN addition, the system resumes processing with the first statement after the SUBMIT statement once the called program has finished. For further information, refer to the documentation for the SUBMIT statement.

SAP AG

TAW10

18-5

Calling a Transaction
Program 1
Restart ... LEAVE TO TRANSACTION 'T_CODE' [AND SKIP FIRST SCREEN]. ...

Program 2: Transaction

TCODE TCODE

1. Screen

SAPM t_name
... LEAVE PROGRAM. ...

2. Screen
F15

Insertion ... CALL TRANSACTION 'T_CODE' [AND SKIP FIRST SCREEN]. ...

1. Screen

SAPM t_name
... LEAVE PROGRAM. ...

2. Screen
F15
SAP AG 2002

With the LEAVE TO TRANSACTION 'T_CODE' statement you terminate the current program and start the transaction with transaction code T_CODE. The statement is the equivalent to entering /n<T_CODE> in the command field. CALL TRANSACTION 'T_CODE' allows you to insert ABAP programs that have a transaction code. To terminate an ABAP program, use the LEAVE PROGRAM statement. If the statement is used in a program that you called using CALL TRANSACTION 'T_CODE' or SUBMIT prog_name AND RETURN, the system resumes processing at the next statement after the call in the calling program. Otherwise, the user returns to the application menu from which he or she started the program. If you use the ... AND SKIP FIRST SCREEN addition, the system does not display the screen contents of the first screen. However, it does process the flow logic. If the transaction T_CODE you called with CALL TRANSACTION uses update techniques, you can use the UPDATE... addition to specify the update technique (asynchronous (default), synchronous, or local) that the program should use. For further information, refer to course BC414 (Programming Database Updates) and the online documentation.

SAP AG

TAW10

18-6

Calling Programs and Passing Data (2)

Calling Calling programs programs Memory management Memory management management Passing Passing data data

SAP AG 2002

SAP AG

TAW10

18-7

Logical Memory Model


User terminal session External session (window) 1
Internal session 1.2

External session (window) 2

Program 1.2

Internal session 1.1

ABAP memory 2

ABAP memory 1

Internal session 2.1

Program 1.1

Program 2.1

SAP memory
SAP AG 2002

The way in which the main memory is organized from the program's point of view can be represented in the above logical model. There is a distinction between internal and external sessions:
n

Generally, an external session is connected to an R/3 window. You can create a new session by choosing System New Session or by entering /o<T_CODE> in the command field. You can have up to six external sessions open simultaneously in one terminal session. n External sessions are subdivided into internal sessions (placed on a stack). Each program that you run occupies its own internal session. Each external session can contain up to nine internal sessions. Data for a program is only visible within an internal session. The visibility of the data is generally restricted to the relevant program. The following slides illustrate how the stack inside an external session changes with various program calls.

SAP AG

TAW10

18-8

Inserting a Program (1)


User terminal session External session (window) 1 External session (window) 2

ABAP memory 1

Internal session 1.1

ABAP memory 2

Internal session 2.1

Program 1.1

Program 2.1

SAP memory
SAP AG 2002

SAP AG

TAW10

18-9

Inserting a Program (2)


User terminal session
Insertion

External session (window) 1


Internal session 1.2

External session (window) 2

ABAP memory 1

Program Program 1.2 1.2

Internal session 1.1

ABAP memory 2

Internal session 2.1

Program 1.1

Program 2.1

SAP memory
SAP AG 2002

When you insert a program, the system creates a new internal session, which in turn creates a new program context. The new session is placed on the stack The program context of the calling program also remains intact.

SAP AG

TAW10

18-10

Terminating the Inserted Program


User terminal session External session (window) 1 External session (window) 2

ABAP memory 1

Internal session 1.1

ABAP memory 2

Internal session 2.1

Program 1.1

Program 2.1

SAP memory
SAP AG 2002

When the called (inserted) program finishes, its internal session (the top one in the stack) is deleted. Processing is resumed in the next-highest internal session in the stack.

SAP AG

TAW10

18-11

Restarting an Executable Program (1)


User terminal session External session (window) 1
Internal session 1.3

External session (window) 2

ABAP memory 1

Program 1.3 Internal session 1.2 Program 1.2 Internal session 1.1 Program 1.1

ABAP memory 2

Internal session 2.1 Program 2.1

SAP memory
SAP AG 2002

When you end a program and start a new one, there is a distinction between calling an executable program and calling a transaction, with regard to memory areas.

SAP AG

TAW10

18-12

Restarting an Executable Program (2)


User terminal session
Restart External session (window) 1 Internal session 1.3'

External session (window) 2

ABAP memory 1

Programm 1.3' Programm Internal session 1.2 Program 1.2 Internal session 1.1 Program 1.1

ABAP memory 2

Internal session 2.1 Program 2.1

SAP memory
SAP AG 2002

If you call an executable program using its program name (terminating the calling program), the system deletes the internal session of the program that you are terminating (the top one from the stack). The system creates a new internal session, which in turn creates the program context of the called program. The new session is placed on the stack Existing program contexts remain intact. The topmost internal session on the stack is replaced.

SAP AG

TAW10

18-13

Restarting a Transaction (1)


User terminal session External session (window) 1
Internal session 1.3

External session (window) 2

ABAP memory 1

Program 1.3 Internal session 1.2 Program 1.2 Internal session 1.1 Program 1.1

ABAP memory 2

Internal session 2.1 Program 2.1

SAP memory
SAP AG 2002

SAP AG

TAW10

18-14

Restarting a Transaction (2)


User terminal session External session (window) 1' External session (window) 2

ABAP memory 1'

Interner Modus 1'.1 Program 1'.1 1'.1

ABAP memory 2

Internal session 2.1 Program 2.1

Restart (complete initialization)


SAP AG 2002

SAP memory

If you start a program using its transaction code (that is, if one was defined), all of the internal sessions on the stack are deleted. The system creates a new internal session, which in turn creates the program context of the called program. After the call, the ABAP memory is initialized.

SAP AG

TAW10

18-15

Calling Programs and Passing Data (3)

Calling Calling programs programs Memory Memory management management Passing Passing data Passing data data

SAP AG 2002

SAP AG

TAW10

18-16

Overview: Passing Data Between Programs

SAP memory (SET/GET parameters)

3
ABAP memory

2 Program A Interface 1 4

Program B

DB
5
SAP AG 2002

There are various ways of passing data to programs running in separate internal sessions: You can use: The interface of the called program (usually a standard selection screen) ABAP memory SAP memory Database tables Local files on your presentation server The following slides deal with the first three of these methods. For further information regarding the passing of data using database tables or the shared buffer, refer to the documentation for the EXPORT and IMPORT statements. For further information on transferring data between an ABAP program and a presentation server, refer to the documentation for the function modules GUI_UPLOAD and GUI_DOWNLOAD.

SAP AG

TAW10

18-17

Passing Data Using the Program Interface

Standard selection screen

Program A

Data

Program B

SAP AG 2002

When you call ABAP programs that have a standard selection screen, you can pass data for the input fields in the call. There are two ways to do this: n By specifying a variant for the selection screen when you call the program n By specifying values for the input fields when you call the program

SAP AG

TAW10

18-18

Preassigning Values for Input Fields

Insert pattern

Pattern for SUBMIT statement inserts the appropriate frame for the program call into the source code

... ... ...

Other pattern

SUBMIT

DATA set TYPE|LIKE RANGE OF type|dataobject}. SUBMIT prog_name AND RETURN [VIA SELECTION-SCREEN] WITH parameter EQ|NE|... val WITH sel_opt EQ|NE|... val SIGN 'I'|'E'} WITH sel_opt BETWEEN val1 AND val2 SIGN 'I'|'E'} WITH sel_opt NOT BETWEEN val1 AND val2 SIGN 'I'|'E'} WITH sel_opt IN set ... .

SAP AG 2002

The WITH addition to the SUBMIT statement allows you to preassign values for parameters and selection options on a standard selection screen of the called executable program. The abbreviations "EQ, NE, ...; I, E" have the same meanings as with selection options. If you want to pass several selections for a selection option, you can use the RANGE statement instead of individual WITH additions. The RANGES statement creates a selection table, which you can fill as though it were a selection option. You then pass the whole table to the executable program. If you want to display the standard selection screen when you call the program, use the VIA SELECTION-SCREEN addition. When you use the SUBMIT statement, use the Pattern function in the ABAP Editor to insert an appropriate statement pattern for the program you want to call. It automatically supplies the names of the parameters and selection options that are available on the standard selection screen. For further information about working with variants and about other syntax variants of the WITH addition, refer to the documentation for the SUBMIT statement.

SAP AG

TAW10

18-19

ABAP Memory and SAP Memory


User terminal session External session (window) 1
Internal session 1.2

External session (window) 2


Internal session 2.2

Program 1.2

ABAP memory 2

ABAP memory 1

Program 2.2

Internal session 1.1

Internal session 2.1

Program 1.1

Program 2.1

SAP memory (SET /GET parameters)


SAP AG 2002

You can use SAP memory and ABAP memory to pass data between programs.
n

SAP memory is a user-specific memory area for storing field values. It is only of limited value for passing data between internal sessions. Values in SAP memory are retained for the duration of the user's terminal session. The memory can be used between sessions in the same terminal session. You can use the contents of SAP memory as default values for screen fields. All external sessions can use the SAP memory. ABAP memory is also user-specific. There is a local ABAP memory for each external session. You can use it to exchange any ABAP variables (fields, structures, internal tables, complex objects) between the internal sessions in any one external session. When the user exits an external session (/i in the command field), the corresponding ABAP memory is automatically initialized or released.

SAP AG

TAW10

18-20

Passing Data Using the ABAP Memory

Internal session 1

ABAP memory MY_ID


wa_fli it_spfli

PROGRAM p1 ... . DATA: p1_spfli TYPE spfli, it_spfli TYPE STANDARD TABLE OF spfli. ...

EXPORT wa_fli FROM p1_spfli it_spfli TO MEMORY ID 'MY_ID'. 'MY_ID'.


Internal session 2

MY_ID1

...

PROGRAM p2 ... . DATA: p2_spfli TYPE spfli, it_spfli TYPE STANDARD TABLE OF spfli. ...

IMPORT wa_fli TO p2_spfli it_spfli FROM MEMORY ID 'MY_ID'.

SAP AG 2002

The EXPORT ... TO MEMORY statement allows you to copy any number of ABAP data objects with their current values to the ABAP memory (data cluster). The ID ... addition enables you to identify different clusters (maximum of 60 characters). If you use a new EXPORT TO MEMORY statement for an existing data cluster, the new one will overwrite the old. The IMPORT ... FROM MEMORY ID ... statement allows you to copy the data from the ABAP memory into corresponding data objects of your ABAP program. It is also possible to only import parts of data clusters using IMPORT. The data objects that are to receive the data from the ABAP memory cluster must have the same types in both the calling and the called programs. To release a data cluster, use the FREE MEMORY ID ... statement. Bear in mind that when you call programs using transaction codes, you can only use the ABAP memory to pass data when inserting (CALL TRANSACTION).

SAP AG

TAW10

18-21

Passing Parameters Using the SAP Memory

Program A Airline

SET PARAMETER ID 'CON' FIELD sdyn_conn-connid.

LH
!

or
CALL TRANSACTION ... .

Connection 400

SET

SAP memory
CAR CON
Program B Airline

LH 400

LH

GET

Connection 400

or
SAP AG 2002

GET PARAMETER ID 'CON' FIELD sdyn_conn-connid.

You can define memory areas (parameters) in the SAP memory in various ways: n By creating input/output fields with reference to the ABAP Dictionary. These take the parameter name of the data element to which they refer. Alternatively, you can enter a name in the attributes of the input/output fields. Here, you can also choose whether the entries from the field should be transferred to the parameter (SET), or whether the input field should be filled with the value from the parameter (GET). To find out about the names of the parameters assigned to input fields, display the field help for the field (F1), then choose Technical info. n You can also fill the memory areas directly using the SET PARAMETER ID 'PAR_ID' FIELD var. statement and read them using GET PARAMETER ID 'PAR_ID' FIELD var. n Finally, you can define parameters in the Object Navigator and let the user fill them with values.

SAP AG

TAW10

18-22

Preview: Passing Data Using an Internal Table


Program 1
... DATA: bi_itab TYPE TABLE OF bdcdata, bi_wa TYPE bdcdata. * fill bi_itab ... * call other program CALL TRANSACTION 'T_CODE' USING bi_itab. IF sy-subrc = 0. ... ELSE. ...

Program 2: Transaction

T_CODE T_CODE

bi_itab

1st screen

2nd screen
F15

SAPM t_name
... LEAVE PROGRAM. ...

SAP AG 2002

The CALL TRANSACTION 'T_CODE' USING bi_itab statement allows you to insert the transaction T_CODE, and the screens are processed according to the internal table bi_itab. This internal table must be typed according to the structure bdcdata and filled appropriately. The MODE addition allows you to specify whether the screen contents should all be displayed ('A' the default setting), only when an error occurs ('E'), or not at all ('N'). The MESSAGES INTO mess_itab addition is used to specify where the system messages sent during the execution of the called transaction are written. The internal table must be typed according to the structure bdcmsgcoll. You can find out if the transaction was executed successfully from the system field sy-subrc. This technique is useful if, for example: n You are processing in the foreground, but the input fields have not been filled using GET parameters n You want to process the transaction in the background. In this case, you normally have to pass function codes as well. This technique is also one of the possible ways of transferring data from non-SAP systems. To do so the internal table in the bdcdata format must be filled completely.

SAP AG

TAW10

18-23

Fields of the Global Type bdcdata

Field name Length Length Description

program 40
Program name

dynpro dynpro 4
Screen number

dynbegin 1
First record

fnam 132
Field name

fval 132
Field value

Note when filling

Only in 1st Only in 1st record on screen record on screen

'X' for 1st record on screen, otherwise ' '

Casesensitive

SAP AG 2002

Filling the internal table in batch input format:


n n

Each screen that is to be processed and filled automatically in the transaction must be identified by a line, in which only the fields program, dynpro and dynbegin are filled. After the record that identifies the screen, use a separate bdcdata record for each field you want to fill. These records use the table fields fnam and fval. The following fields can be filled: Input/output fields, with data The command field (bdc_okcode), with function codes The cursor position field (bdc_cursor), with field names.

You also use the CALL TRANSACTION technique to transfer data from external systems . Further information on this topic is available in the course BC420 (Data Transfer) and in the online documentation.

SAP AG

TAW10

18-24

Example: Passing Data Using an Internal Table


program
SAPBC401_CALD_CREATE_CUSTOMER

dynpro
0100

dynbegin
X

fnam

fval

SCUSTOM-NAME <current_name> SCUSTOM-CITY <current_city> BDC_OKCODE SAVE

DATA: wa_bdcdata TYPE bdcdata, bdcdata it_bdcdata LIKE TABLE OF wa_bdcdata. * fill the bdcdata-table ... CALL TRANSACTION 'BC401_CALD_CRE_CUST' USING it_bdcdata MODE MODE 'N'. IF sy-subrc <> 0. MESSAGE ... WITH sy-subrc. ENDIF.
SAP AG 2002

Save

ID for command field

This example refers to the transaction BC401_CALD_CTA_U. If you request the creation of a new customer entry here, the transaction BC401_CALD_CRE_CUST is inserted. This transaction has not implemented an import from the ABAP memory, and its input fields are not set as GET parameters. The customer data is therefore passed using an internal table and the transaction processed in the background. If the operation is successful, the new customer data record can be entered in the waiting list.

The relevant internal table in bdcdata format is shown above. current_name is the customer name adopted from the input field at runtime, current_city is the city.
You address the command field using BDC_OKCODE. Here you enter the function code that is triggered by the user choosing a function key, pushbutton, or menu entry during the dialog flow (or by entering a code directly in the command field).

SAP AG

TAW10

18-25

Calling Programs and Passing Data: Unit Summary

You are now able to: l Describe the SAP R/3 memory model l Call executable programs l Call transactions l Use the various memory areas to pass data

SAP AG 2002

SAP AG

TAW10

18-26

Appendix

l This section contains supplementary material to be used as reference. l This material is not part of the standard course. l Therefore, the instructor might not cover this during the course presentation.

SAP AG 2001

SAP AG

TAW10

19-1

Program Types

Program Program Types Types Data Data Types, Types, Data Data Objects, Objects, and and Statements Statements Logical Logical Databases Databases Preview Preview

SAP AG 2001

SAP AG

TAW10

19-2

Programs of "Include" Type

Program: <program_name > REPORT <program_name>. : INCLUDE <include_name>. :

Include: <include_name> ( Program type: Include )

ABAP statements

SAP AG 2001

SAP AG

TAW10

19-3

TOP Include

Create program

Repository Browser:
program <name>

Create program
With TOP-Include

Program: <name>TOP Program type: Include

REPORT <name>. TYPES:... DATA: ...

Program: <name>

INCLUDE <name>TOP.

Program type: executable START-OF-SELECTION. :


SAP AG 2001

SAP AG

TAW10

19-4

Standard Includes for Function Groups


The Object List Edit Goto Utilities Environment System Help

Object Navigator

Workbench Edit

Goto

Extras

Environment System Help

The Object List


Development class program Function group Class Local Objects

Object Navigator

Object name
BC402_FMDD_WAITLIST

> < < < < < >

BC402_FMDD_WAITLIST Function modules Fields PBO modules Screens GUI title 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

Display

PBO modules Global declarations Function modules

Add waiting customer Waiting customer from list Display waiting list Move up waiting customer Return position in list Change waiting position

Include function modules


SAP AG 2001

n n n n

When you work with function groups and modules, you can use the ABAP Workbench to arrange the program source code in overview form and structure it with ease. In the Navigation function, you always branch to the correct object, and Include programs are given names and created. The respective call statements are automatically entered at the correct position. The call statements must contain only the name convention for function groups: Y|Z<rem_name>. The system then creates a program of F type, SAPLY|Z<rem_name>. This contains only INCLUDE statements that were created automatically. The Include programs are automatically given the name LY|Z<rem_name><abbrev><num>. In addition, the system includes the Include program, LY|Z<rem_name>UXX. Here, there is a call for an appropriate Include program, LY|Z<rem_name>U<num>, for each function module.

SAP AG

TAW10

19-5

Data Types, Data Objects, and Statements

Program Program Types Types Data Data Types, Types, Data Data Objects, Objects, and and Statements Statements Logical Logical Databases Databases Preview Preview

SAP AG 2001

SAP AG

TAW10

19-6

Structures and internal Tables Can be Nested

SAP AG 2001

n n n

Structure types can contain other structure types or table types. Table types can contain structure types and table types. In the keyword documentation for the keyword TYPES, you will find the syntax for defining table types.

SAP AG

TAW10

19-7

Type Groups in the ABAP Dictionary

TYPE-POOL Z400. TYPES: z400_name_type(25) TYPE C, BEGIN OF z400_flightrec_type, ... , END OF z400_flightrec_type.

REPORT ... . TYPE-POOLS z400. DATA: name TYPE z400_name_type, wa TYPE z400_flightrec_type. ... .

ABAP

SAP AG 2001

n n n

In addition to declaring a data type within an ABAP program, you can also declare data types in a type group in the ABAP Dictionary. The type group name in the ABAP Dictionary has a maximum of five characters. Type names within the type group <typpool> must begin with <typpool> followed by an underscore. The types in a type group must be declared in ABAP programs with the TYPE-POOLS command.

SAP AG

TAW10

19-8

Type Conversion

l When are two types compatible?


n

Two elementary types are compatible if they are identical in type and length (and number of decimal places in the case of packed numbers). Two structure types are compatible if they have the same structure and their components are compatible. Two table types are compatible if their line types are compatible and their key definitions, key categories, and table types are identical.

l Data objects with compatible types can be assigned without conversion. l Non-compatible types can be converted if a conversion rule has been defined.
SAP AG 2001

If two data types are not compatible, but a conversion rule exists, then the system performs type conversions for value assignments, calculations, or comparisons. The following graphics introduce the basic forms of conversion rules and give examples of the most important cases. All the conversion rules can be found in the ABAP documentation on the MOVE statement. If no conversion rule is defined for a statement, the system's reaction depends upon the particular program context: n In the case of statistical types, the system issues a syntax error. Example : DATA: date TYPE d VALUE '19991231', time TYPE t. FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t. ASSIGN: date TO <fs_date>, time TO <fs_time>. <fs_time> = <fs_date>. n In the case of dynamic types, the system issues a runtime error since the the field symbols are typed only when the data objects are assigned at runtime. Example (rest as above): ... FIELD-SYMBOLS: <fs_date> TYPE ANY, <fs_time> TYPE ANY. ...

SAP AG

TAW10

19-9

Logical Expressions
* comparisons for all datatypes: .. <dobj> {EQ|=} {<literal>|<dobj>} .. <dobj> {NE|<>} {<literal>|<dobj>} .. <dobj> {GT|>} {<literal>|<dobj>} .. <dobj> {GE|>=} {<literal>|<dobj>} .. <dobj> {LT|<} {<literal>|<dobj>} .. <dobj> {LE|<=} {<literal>|<dobj>} .. <dobj> BETWEEN {<lit>|<dobj>} AND .. <dobj> IS INITIAL ..

.. "equal .. "not equal .. "greater than .. "greater or equal .. "less than .. "less or equal {<lit>|<dobj>} ..

* nesting logic expressions: .. <nest_op> ( <expr1> <nest_op> <expr2> ) <nest_op> .. * possible operators <nest_op>: .. AND .. "all expressions must be true .. OR .. "one of the expressions must be true * negation: .. NOT <expr> ..
SAP AG 2001

"true, if <expr> false

If you have a comparison of non-numeric data objects, these are interpreted differently, depending upon type.

If possible: conversion in numbers (hexadecimal, for example, as binary number) Date and time: interpreted as earlier or later; for example, 12/31/1999 < 01/01/2000 Other characters: lexographical interpretation according to character code; adapt length by filling in blanks References: comparison of address and data type, only identical can be interpreted suitably

For comparisons of strings and bits, more relational operators are available (see online documentation for IF). In the case of links and negations, the standard rules for logical expressions apply: NOT is more powerful than AND, AND is more powerful than OR. Example NOT f1 = f2 OR f3 = f4 AND f5 = f6 therefore corresponds to ( NOT ( f1 = f2 ) ) OR ( f3 = f4 AND f5 = f6 ).

n n

To have a better overview and for security reasons, place your partial expressions in brackets, even if it is not absolutely necessary. By setting up your expressions carefully, you can influence the runtime requirement in a positive way.

SAP AG

TAW10

19-10

Overview: Termination Statements


LEAVE PROGRAM LEAVE TO TRANSACTION

CHECK

EXIT

MESSAGE a..

Loops:
DO WHILE SELECT LOOP

Nextrun

Leaveloop

Events I:
LOAD-OF-PROGRAM. START-OF-SELECTION. GET <node> [LATE]. END-OF-SELECTION.

Display list buffer; Execute event blocks II

Display message then Program end program end and delete all internal modes

Events II:
INITIALIZATION. AT SELECTION-SCREEN [OUTPUT]. TOP-OF-PAGE. END-OF-PAGE. AT LINE-SELECTION. AT USER-COMMAND. End current processing block and proceed with next processing block

Modularization units
SAP AG 2001

n n

ABAP event blocks or modularization units (subroutines, modules) are called processing blocks . The CHECK logic_expr statement has the following effect: Outside a loop, you can terminate a processing block prematurely. The block statements after the CHECK statement are skipped if the logical condition is not fulfilled. The system then continues with the first statement in the next processing block. Within a loop, it has the effect that the next loop is processed.

The EXIT statement reacts in three different ways: Within each loop, loop processing is completed to the end. Outside of the loops, but within the first events listed on this slide, the system displays the list buffer with the current content. Afterwards, the events of the other group are triggered and those events listed before START-OF-SELECTION are initiated at the LOAD-OF-PROGRAM event. At all other points, EXIT has the same effect as CHECK.

n n

Using the LEAVE PROGRAM or LEAVE TO TRANSACTION tcode statements, you can terminate the current program. After a termination message, the system terminates not only the current program, but also the entire program stack.

SAP AG

TAW10

19-11

The MESSAGE Statement, Message Classes, and Messages


Use '< <message message class> class >' TYPE '<message type>' MESSAGE ID '<message class>' NUMBER '<message '< <message message number>' number>' . number> Do ub lle eclic k Definition <message <message class> class> Message class: Attributes Message 040 041 002 Messages Message short text The name of the airline &1 is &2 Airline &1 is not available BC400

<message number> <message number>


SAP AG 2001

To trigger a message dialog in a program, enter the MESSAGE statement with the following additions: ID '<message class>' for the message class NUMBER '<number> for the message number

n n

To display the message text for a MESSAGE statement in a program's source code, double -click the message number to go to the associated message class texts. Other syntax variants are available for the MESSAGE statement. For more information, refer to the keyword documentation for the MESSAGE statement.

SAP AG

TAW10

19-12

Self-Explanatory Messages or Messages with Long Texts


: Message is self-explanatory There is a long text explaining the message

Long text Message class: Message class BC400 Number Short text 000 <short text> 001 <short text> 2

Self-explanatory

<short text> Diagnosis <text> System activities <text> Procedure <text> Procedure for system administrator <text>

Long text

Definition SAP AG 2001

If a message short text contains all the information the user needs, the message is described as selfexplanatory. Example : "The program has been saved." Self-explanatory messages are flagged as such in the message class. If you want to provide more detailed information for the user, you can do so by storing a long text with the message. In the Message Maintenance screen, the Self-Explanatory flag indicates whether or not a message is indeed self-explanatory. To display the long text, select the message line and choose Long Text. The system then displays the maintenance formats. You can display the formatted text by choosing Screen Output. You usually create the long text from a template, which contains the headings Diagnosis, System Activities, Procedure, and Procedure for the System Administrator. The system does not display the heading to the user if there is no text stored under it.

SAP AG

TAW10

19-13

Messages with Placeholders


Use MESSAGE ID '<message class>' TYPE '<message type>' NUMBER <nnn> WITH WITH <var1> <var1> <var2> <var2> <var3> <var3> <var4> <var4> .

Definition

&1

&2

&3

&4

Message class: Attributes Message 039 040 041


SAP AG 2001

BC400 Messages Message short text The name of the airline &1 is &2 Airline &1 is not available

You can include up to four placeholders in a message (&1, &2, &3 and &4). You can then assign current parameters to them in the MESSAGE statement using the WITH addition. You can use literals, text symbols, or variables. You must include a space between each one. The current parameters are assigned to the placeholders &1, &2, &3, and &4 in order. In the long text, the placeholders are given the names &V1&, &V2&, &V3&, and &V4& and replaced at run time in order, according to the same logic. To insert a placeholder in the long text: Place your cursor in the text where you want to insert the placeholder. Choose EditCommandInsert command . The system displays a dialog box. In Symbols, enter &V1& (or &Vi& i = 2, 3 or 4, as appropriate). Choose Enter to confirm the dialog box.

SAP AG

TAW10

19-14

Creating Message Classes and Messages


Create using forward navigation <message class> MESSAGE ID '<message class>' TYPE '<message type>' NUMBER '<message <message number>' number> .
Double-click Double-click

Create message class

No

Message class available? Yes Create message

Development class In the Object Navigator: ZBC400_12 Programs ... Message classes ZBC400_MC12 Create

ZBC400_12 ... Message class Note: Messages can be translated. They then appear in the user's logon language.

... Change Display

SAP AG 2001

n n n n

To create your own message class, give it a name in the customer namespace, that is, a name beginning with Y, Z, or the namespace prefix. To create a message, assign a three-digit number and a message class to it. You can create both the message class and the message itself using forward navigation from the MESSAGE statement. In the Object Navigator, you can create and edit a message class in any of the following ways: From the context menu belonging to the root node in the object list of the respective development class From the context menu belonging to the Message class node in the object list of the appropriate development class From the Other object... icon A dialog box containing a tab appears. In the Other tab, enter a message class, or a message with its message class, and then display, create, or change it by choosing the appropriate icon.

SAP AG

TAW10

19-15

Colors/Icons/Symbols in Lists

WRITE <data object> <option> . REPORT sapbc400udd_example_1a. INCLUDE <LIST>. : WRITE: / wa_spfli-carrid COLOR col_key, icon_date AS ICON,

Colors in Lists Flight AA 0017 LH 0400 LH 0402 from NEW YORK FRANKFURT FRANKFURT to SAN FRANCISCO NEW YORK BERLIN

Creation date: 01/01/2001 Created by: WITTMANN

SAP AG 2001

n n n

You can set several list display attributes within a WRITE statement. One such attribute is color, which can be adjusted using the formatting option COLOR <n>. You can choose from seven background colors that are activated by either a numeric value or a symbolic name. 0 col_background Background 1 col_heading Headers 2 col_normal List entries 3 col_total Totals 4 col_key Key columns 5 col_positive Positive threshold value 6 col_negative Negative threshold value 7 col_group Control levels SAP provides guidelines for creating lists in color. Please consult transaction LIBS for examples. With the help of one more parameter of the WRITE statement AS ICON , you can use icons in your list. For this purpose, you must include the Include <LIST> statement in your program. You can find an overview of all available icons in either the keyword documentation under WRITE, or in the WRITE statement structure.

SAP AG

TAW10

19-16

Dynamic Screen Sequence

Screen attributes
Screen number Next screen 100 100

Screen attributes
Screen number Next screen 200 200

PBO

100

PAI 0

200

PBO

200

PAI 0

CALL SCREEN 100

SAP AG 2001

You can use this technique to program clusters of screens with complicated links without having to continually return to the source code and call them using CALL SCREEN.

SAP AG

TAW10

19-17

Exceptions for Function Modules


Function module Edit Goto Utilities Environment System Help

Function Builder: Display BC402_FMDD_GET_FREE_SEATS


Function module documentation Function module BC402_FMDD_GET_FREE_SEATS Active

Attributes Exception NO_SEATS OVERLOAD DB_FAILURE

Import

Export

Changing Short text Freight carrier overbooked no data

tables

Exceptions

Source code

RAISE <exception>. *** with default message: MESSAGE <kind><num>(<id>) RAISING <exception>.
SAP AG 2001

You can have a function module trigger a Raise Exceptions . For this purpose, you must first define exceptions in the interface definition, that is, you must define distinguishable identifiers for your exceptions. In the source code, you program the triggering of an exception under the required conditions. At runtime, the function module execution is interrupted if an exception has been triggered. Changes to Export and Changing parameters have the same effect as with subroutine calls. There are two statement variants. Here, exception stands for an exception you have declared, that is, for the identifier. Depending upon whether the exception is carried out when the function module is called, the statements can have different effects. n RAISE <exception> If the exception is executed in the calling program, control is passed back to the same. Otherwise a runtime error occurs. n MESSAGE <kind><num>(<id>) RAISING <exception> If the exception is listed in the calling program, this statement corresponds to the first variant. If the exception is not executed, the system displays a message num of message class id with behavior kind. Therefore, a runtime error does not occur in this situation.

SAP AG

TAW10

19-18

Logical Databases

Program Program Types Types Data Data Types, Types, Data Data Objects, Objects, and and Statements Statements Logical Logical Databases Databases Preview Preview

SAP AG 2001

SAP AG

TAW10

19-19

Reading Logically Dependent Data

Example: Logical Database F1S

SPFLI

SFLIGHT

SBOOK

SAP AG 2001

n n

You can use easy-to-use read programs (logical databases) to read logically connected data. Each logical database has a structure containing a hierarchy of those tables and views that are to be read. You can attach exactly one logical database to each type 1 program. The logical database then supplies your program with entries from tables and views. This means that you need to program the data processing statements only.

SAP AG

TAW10

19-20

Logical Databases

l Special data collection programs delivered by SAP l Provide your program with data in a hierarchically logical sequence l Contain data base accesses that have been optimized for performance l Supply a dynamic selection screen l Contain all necessary authorization checks

You can can attach attach a a logical logical database database to to each each type type 1 1 program program using the program attributes. Special event blocks are also also available available for for processing processing individual records. individual records.
SAP AG 2001

n n n n

Each logical database is an encapsulated data collection program for frequent database access. Database access has been optimized using Open SQL. If you are working with a logical database, you do not need a selection screen for user entry, because it is created automatically. The system performs authorization checks according to the SAP authorization concept.

SAP AG

TAW10

19-21

Controlling an LDB from Within a Program

Data from the LDB

Program
NODES sflight. SPFLI GET sflight ...
:

SFLIGHT SBOOK

SAP AG 2001

The NODES <node> statement performs two functions: It defines a data object (a structure) as a table work area that has the same structure as the database table. This structure is then filled at run time with all the data records that the logical database has read from the database and made available to the program. It controls the executability of the selection screen. The selection screen was defined in the logical database should contain only those key information input fields that the program needs. The NODES statement allows you to ensure that only information from relevant tables is available to the logical database.

Logical databases read according to their structure, that is, from top to bottom. The depth of data read depends on a program's GET statements. The deepest GET statement from the structural view of the logical database determines the level.

SAP AG

TAW10

19-22

Event Blocks in Logical Databases

Program NODES: SPFLI, SFLIGHT. START-OF-SELECTION. GET spfli.

Logical database

SPFLI
ABAP runtime system

GET sflight.

SFLIGHT SBOOK

Basic list

END-OF-SELECTION.

SAP AG 2001

n n

n n

You can include a logical database in every executable program (type 1) using the program attributes. Each node in the hierarchy of the logical database also provides you with a GET event block in addition to the other event blocks (GET SPFLI, GET SFLIGHT, and GET SBOOK in the example in the graphic). You can program individual record processing using these GET event blocks. At run time, the event blocks that create lists are processed in the following order: START-OF-SELECTION. GET SPFLI and GET SFLIGHT are called several times in nested SELECT logic according to the structure of the logical database. END-OF-SELECTION is called after all GET events, and immediately before the list is sent to the presentation server

SAP AG

TAW10

19-23

Syntax Example: Event Sequence

REPORT bc400d_logical_database. NODES: spfli, sflight. START-OF-SELECTION. WRITE: / 'START-OF-SELECTION' color 3. GET spfli spfli FIELDS carrid connid. GET WRITE: / 'GET SPFLI' color 1, spfli-carrid, spfli-connid. GET GET sflight sflight FIELDS fldate. WRITE: / 'GET SFLIGHT' color 2, sflight-fldate. GET spfli spfli LATE. GET LATE. WRITE :/ 'GET SPFLI LATE'. END-OF-SELECTION. WRITE: 'END-OF-SELECTION' color 3.
SAP AG 2001

START-OF-SELECTION GET SPFLI GET SFLIGHT GET SFLIGHT GET SPFLI LATE GET SPFLI GET SFLIGHT GET SFLIGHT GET SFLIGHT GET SPFLI LATE END-OF-SELECTION DL 1984 25.08.1998 27.09.1998 29.09.1998 DL 1699 25.08.1998 27.09.1998

At run time, the event blocks that create lists are processed in the following order: START-OF-SELECTION. GET spfli: The first data record from database table SPFLI that corresponds to the selection criteria is placed in work area spfli and the event block is processed. GET sflight: The first data record from SFLIGHT that corresponds to the selection criteria as well as to the key of the current SPFLI record are placed in work area sflight and the event block is processed. GET sflight: The next data record from database table SFLIGHT is placed into work area sflight and the event block is processed again. GET sflight: This is called again until no further corresponding data records are found. GET spfli LATE is called before the next data record from SPFLI is placed into work area spfli. GET spfli: The logical database places the next corresponding data record from SPFLI in work area spfli. END-OF-SELECTION is called immediately before the list is displayed.

SAP AG

TAW10

19-24

Summary

ABAP: Program attributes ABAP: Attributes


Type Application Logical Database 1 S F1S

NODES :spfli, sflight. NODES START-OF-SELECTION. WRITE: / 'START-OF-SELECTION' color 3. GET spfli FIELDS carrid connid. GET spfli WRITE: / 'GET SPFLI' color 1, spfli-carrid, spfli-connid. sflight FIELDS fldate. GET sflight WRITE: / 'GET SFLIGHT' color 2, sflight-fldate. GET spfli spfli LATE. LATE. GET WRITE :/ 'GET SPFLI LATE'. END-OF-SELECTION. WRITE: 'END-OF-SELECTION' color 3.

SPFLI SFLIGHT SBOOK

SAP AG 2001

n n

Logical databases are included in type 1 programs as program attributes. Only one logical database can be used for each program. You can supply a logical database with the information regarding which fields you need from the database using the GET addition FIELDS. If the logical database supports this action, it will read from the database only those fields you require. If, for your list, you need database table data that is not supplied by your logical database, you can program any additional database access needed using SELECT.

SAP AG

TAW10

19-25

Preview

Program Program Types Types Data Data Types, Types, Data Data Objects, Objects, and and Statements Statements Logical Logical Databases Databases Preview Preview

SAP AG 2001

SAP AG

TAW10

19-26

External Data Transfer I

External Server

Sequential Files
SAP AG 2001

SAP Interfaces / Checks

n n n n n n

When you transfer data from another SAP or external system to your own SAP system, it is important to ensure data integrity. Thus, it is necessary to subject this type of data transfer to the same checks as data transfer in dialog mode. Since dialog mode checks in transactions are comprehensive and, in part, done on a cross-application basis, it is extremely difficult to program them yourself. Therefore, it is much easier to use the online checks provided for SAP transactions because these SAP transactions are used also for the data transfer. The techniques used for external data transfer are called batch-input processes. SAP offers standardized procedures for external data transfer for many areas within R/3. These procedures use these programming techniques: batch input, call transaction, and direct input. The SAP standard data transfer procedures are called using the Data Transfer Workbench (transaction SXDA). If no SAP data transfer procedures are available, transfer can be programmed individually using batch input or call transaction.

SAP AG

TAW10

19-27

External Data Transfer II


BATCH INPUT:
Sequential file

CALL TRANSACTION:
Sequential file

DIRECT DIRECT INPUT: INPUT:


Sequential file

BDC table BDC table table

BDC BDC table table

Queue file

CALL TRANSACTION Batch Batchinput input function function Application Application function function Application Application function function

SAP transfer program

SAP database SAP AG 2001

SAP database

SAP database

SAP AG

TAW10

19-28

Update

Dialog process

PBO

PAI
UPDATE Request

PBO

PAI
INSERT Request

PBO

PAI
DELETE Request
Log table
UPDATE req. INSERT req. DELETE req.

COMMIT WORK Update process

UPDATE

INSERT

DELETE

Database process

SAP AG 2001

n n

n n

Another way of bundling database changes at the end of an SAP LUW is to use the update technique. Here, you do not pass updates directly to the database, but enter them as update requests in a log table instead. Using the ABAP statement COMMIT WORK, you end SAP LUW in dialog mode. The SAP system then triggers a special work process called an update work process that, based upon your log entries, executes the actual changes to the database within a database transaction. The SAP LUW ends only when the update process has finished. The program part in the dialog and update process can run either synchronously or asynchronously. The advantage of update in contrast to bundling using subroutines is that you can store the data for the database change in the log table at any time and do not have to keep it in the program work area. Its disadvantage lies in the effort required for additional logging. Use asynchronous update when response times are important and the database updates are complicated enough that they justify the extra work involved in using the log table. Use synchronous update whenever you need the changed data immediately and when the database updates are complicated enough to justify the extra work involved in using the log table.

SAP AG

TAW10

19-29

You might also like