54
Karl-Heinz Kühnhauser Discover ABAP Bonn Boston

Discover Abap From Sap Press

Embed Size (px)

Citation preview

Page 1: Discover Abap From Sap Press

Karl-Heinz Kühnhauser

Discover ABAP™

Bonn � Boston

152.book Seite 3 Donnerstag, 11. Oktober 2007 7:18 19

Page 2: Discover Abap From Sap Press

Contents at a Glance

Preface ..................................................................... 15

1 ABAP and Getting Started with the SAP System ....... 21

2 Data Dictionary ........................................................ 43

3 Programming in the ABAP Editor ............................. 69

4 Fields and Calculations ............................................. 97

5 Modifying Character Strings ..................................... 121

6 Debugging Programs ................................................ 139

7 Modifying Transparent Database Tables ................... 159

8 Calculating Dates, Times, Quantities, and Currencies ......................................................... 199

9 Modifying Data in a Database Table ......................... 231

10 Program Flow Control and Logical Expressions ......... 261

11 Selection Screens ..................................................... 311

12 Internal Tables ......................................................... 369

13 Modularizing Programs ............................................ 429

152.book Seite 5 Donnerstag, 11. Oktober 2007 7:18 19

Page 3: Discover Abap From Sap Press

7

Contents

Preface ........................................................................... 15

Who This Book Is For .................................................................. 15What You’ll Discover ................................................................... 16Navigational Tools for This Book ................................................. 16System Requirements .................................................................. 16What’s In This Book? ................................................................... 17Code Samples for Download ....................................................... 19Acknowledgments ....................................................................... 19

1 ABAP and Getting Started with the SAP System .... 21

Overview of the Architecture of an SAP System ........................... 22Technical Architecture .......................................................... 23Business Organization Architecture ....................................... 24Platform-Independence ......................................................... 27

Application Programs and Runtime Environment ......................... 28Work Processes ..................................................................... 29Structure of ABAP Programs .................................................. 31

Logging On and Off the System ................................................... 33Overview of Business Modules .............................................. 35ABAP Workbench ................................................................. 37

2 Data Dictionary ........................................................ 43

Getting Started with the ABAP Dictionary ................................... 44Database Tables .................................................................... 44Creating and Maintaining Tables ........................................... 46

Data Elements and Domains ........................................................ 50Creating a Data Element ....................................................... 50Creating Domains ................................................................. 55Checking and Activating a Data Element ............................... 60Maintaining the Technical Settings of the Table .................... 62

Creating Data Records ................................................................. 64Entering Data Records ........................................................... 65Displaying the Contents of the Table ..................................... 66

152.book Seite 7 Donnerstag, 11. Oktober 2007 7:18 19

Page 4: Discover Abap From Sap Press

Contents

8

3 Programming in the ABAP Editor ............................ 69

Creating an ABAP Report ............................................................ 69ABAP Editor: Overview ............................................................... 73

Modes of the ABAP Editor ................................................... 74Controlling the ABAP Editor ................................................. 75

Understanding and Editing ABAP Programs ................................ 81Executing an ABAP Report .......................................................... 83Reading and Outputting Database Tables ................................... 85Formatting Lists .......................................................................... 86

Chain Statement ................................................................... 87Lines .................................................................................... 87Blank Lines ........................................................................... 87

Writing and Editing Source Code ................................................ 88Notes on the Source Code .................................................... 89List Screen from Our Sample Source Code ............................ 94

4 Fields and Calculations ............................................ 97

Preparing the Report .................................................................. 98Declaring Fields .......................................................................... 102

Declaring Variables ............................................................... 103Declaring Constants .............................................................. 107

Basic Arithmetic Operations ....................................................... 108Compatible and Convertible Data Objects ............................ 110Conversion Rules .................................................................. 111Special Features of Division Operations ................................ 113

Sample Code for Fields and Calculations ..................................... 114Notes on the Source Code .................................................... 115Improved List Format ........................................................... 118

5 Modifying Character Strings .................................... 121

Declaring Character Strings ......................................................... 122String Operations ........................................................................ 124

Shifting Character Strings ...................................................... 124Replacing Character Strings .................................................. 126Condensing Character Strings ............................................... 127Concatenating String Fields .................................................. 128

152.book Seite 8 Donnerstag, 11. Oktober 2007 7:18 19

Page 5: Discover Abap From Sap Press

Contents

9

Splitting Character Strings ..................................................... 130String Operations with Direct Positioning .............................. 130

Sample Code for String Operations .............................................. 132Notes on the Source Code .................................................... 134Outputting the Source Code ................................................. 137

6 Debugging Programs ................................................ 139

Overview ..................................................................................... 140Calling the ABAP Debugger ......................................................... 140Working with the ABAP Debugger .............................................. 144

Fields Mode .......................................................................... 144Table Mode .......................................................................... 148Watchpoints Mode ............................................................... 150Breakpoints Mode ................................................................. 154Static Breakpoints ................................................................. 157

7 Modifying Transparent Database Tables ................. 159

Do you remember the transparent database table from Chapter 2? ................................................................................... 159Copying a Database Table ........................................................... 161Enhancing Non-Key Fields ........................................................... 165

Maintaining Fixed Values in Domains .................................... 166Special Points for Currency and Quantity Fields ..................... 169Maintaining Foreign Keys ...................................................... 171Maintaining Append Structures ............................................. 179Maintaining an Include Structure .......................................... 183

Manipulating Key Fields of Tables ............................................... 188Deleting Table Fields ................................................................... 192Deleting Tables ........................................................................... 194

8 Calculating Dates, Times, Quantities, and Currencies ................................................................. 199

Field Definitions .......................................................................... 199Using Date Fields in Arithmetic Operations ................................. 202Using Time Fields in Arithmetic Operations ................................. 209Using Quantity and Currency Fields in Arithmetic Operations ...... 214Sample Code for Date, Time, and Currency Fields ........................ 217

152.book Seite 9 Donnerstag, 11. Oktober 2007 7:18 19

Page 6: Discover Abap From Sap Press

Contents

10

Notes on the Source Code .................................................... 221Outputting the Source Code ................................................. 228

9 Modifying Data in a Database Table ....................... 231

Authorization Concept ................................................................ 232Lock Concept .............................................................................. 234Open SQL Statements ................................................................. 237

Creating a New Data Record ................................................ 238Modifying an Existing Data Record ....................................... 241Modifying a Data Record ...................................................... 242Deleting a Data Record ........................................................ 243

Sample Code for INSERT ............................................................. 245Notes on the Source Code .................................................... 247Outputting the Source Code ................................................. 248

Sample Code for UPDATE ........................................................... 249Notes on the Source Code .................................................... 251Outputting the Source Code ................................................. 252

Sample Code for MODIFY .......................................................... 252Notes on the Source Code .................................................... 254Outputting the Source Code ................................................. 255

Sample Code for DELETE ............................................................ 256Notes on the Source Code .................................................... 258Outputting the Source Code ................................................. 259

10 Program Flow Control and Logical Expressions ...... 261

Control Structures ....................................................................... 262Using Patterns ............................................................................ 263Branches ..................................................................................... 266

IF Structure .......................................................................... 267CASE Structure ..................................................................... 270

Loops ......................................................................................... 272SELECT Loop ........................................................................ 273DO Loop .............................................................................. 273WHILE Loop ......................................................................... 275Termination Statements for Loops ........................................ 277

Logical Expressions ..................................................................... 281Simple Logical Expressions ................................................... 281

152.book Seite 10 Donnerstag, 11. Oktober 2007 7:18 19

Page 7: Discover Abap From Sap Press

Contents

11

Linked Logical Expressions .................................................... 284Sample Code for IF ...................................................................... 288

Notes on the Source Code .................................................... 290Outputting the Source Code ................................................. 292

Sample Code for CASE ................................................................. 293Notes on the Source Code .................................................... 295Outputting the Source Code ................................................. 296

Sample Code for DO and Termination Conditions ........................ 298Notes on the Source Code .................................................... 300Outputting the Source Code ................................................. 302

Sample Code for WHILE and Logical Expressions ......................... 303Notes on the Source Code .................................................... 306Outputting the Source Code ................................................. 308

11 Selection Screens ..................................................... 311

Events ......................................................................................... 313Order of Events ..................................................................... 313Examples of Events ............................................................... 314

Simple Selections ........................................................................ 316PARAMETERS Statement ...................................................... 317Additions to the PARAMETERS Statement ............................ 318

Complex Selections ..................................................................... 323SELECT-OPTIONS Statement ................................................. 324Multiple Selections ............................................................... 326Additions to the SELECT-OPTIONS Statement ....................... 328

Using Selection Texts ................................................................... 329Overview of Text Elements .................................................... 329Creating Selection Texts ........................................................ 330

Saving the Selection Screen ......................................................... 333Creating Selection Variants .................................................... 334Starting a Report with a Variant ............................................ 340

Completing Text Objects ............................................................. 341Creating Text Symbols ........................................................... 342Creating Messages ................................................................ 343

Free Layout of the Selection Screen ............................................. 347Formatting Single Lines ......................................................... 348Formatting a Line Block ........................................................ 350

Sample Code for Selection Screen (Simple Form) ......................... 351

152.book Seite 11 Donnerstag, 11. Oktober 2007 7:18 19

Page 8: Discover Abap From Sap Press

Contents

12

Notes on the Source Code .................................................... 354Outputting the Source Code ................................................. 356

Sample Code for Selection Screen (Extended Form) .................... 356Notes on the Source Code .................................................... 361Outputting the Source Code ................................................. 365

12 Internal Tables ......................................................... 369

Purpose of Internal Tables .......................................................... 370Structure and Types of Internal Tables ........................................ 372Creating an Internal Standard Table ............................................ 375

Traditional Syntax with Header Line ..................................... 375Object-Oriented Syntax Without Header Line ...................... 377

Filling an Internal Standard Table ................................................ 380Filling an Internal Table with a Header Line .......................... 380Filling an Internal Table with a Work Area ............................ 386

Processing an Internal Table Line-by-Line ................................... 390Processing an Internal Table with a Header Line ................... 390Processing an Internal Table with a Work Area ..................... 398

Deleting the Contents of Internal Tables ..................................... 400Deleting an Internal Table with a Header Line ...................... 401Deleting Work Areas and Internal Tables with a Work Area ................................................................. 402

Sample Code for ITAB with Header Line ..................................... 403Notes on the Source Code .................................................... 408Tracing the Output of the Source Code in the ABAP Debugger ................................................................... 411

Sample Code for ITAB with Work Area ....................................... 417Notes on the Source Code .................................................... 422Tracing the Output of the Source Code in the ABAP Debugger ................................................................... 425

13 Modularizing Programs ........................................... 429

Overview .................................................................................... 430Source Code Modules ................................................................. 431Procedures ................................................................................. 434

Subprograms ........................................................................ 434Function Modules ................................................................ 449

152.book Seite 12 Donnerstag, 11. Oktober 2007 7:18 19

Page 9: Discover Abap From Sap Press

Contents

13

Memory Areas for Data Transfer .................................................. 465Global SAP Memory .............................................................. 466Local SAP Memory ................................................................ 466ABAP Memory ...................................................................... 467

Sample Code for Modularization ................................................. 468Notes on the Source Code .................................................... 476Outputting the Source Code ................................................. 478

Sample Code for Calling an External Report ................................. 478Notes on the Source Code .................................................... 485Outputting the Source Code ................................................. 489

Index ........................................................................................... 491

152.book Seite 13 Donnerstag, 11. Oktober 2007 7:18 19

Page 10: Discover Abap From Sap Press

15

Preface

This book is intended as a practical introduction for those of youwho are planning to enter the world of ABAP programming. Thisis the primary goal of the book; everything else is secondary.Therefore, this book intentionally simplifies and oversimplifiesthings by reducing technical and business-related issues to a min-imum. In doing so, it accepts gaps, because it cannot and will notcover the topic of ABAP to its full extent. Instead, it limits itself todescribing a core topic and moving along a common threadthroughout all the chapters in order to reach the intended targetgroup — programmers with little or no ABAP knowledge, projectteam members and developers for SAP introduction projects, etc.In this way, the book is able to impart a feeling of success to new-comers to ABAP.

For this reason, this book can neither replace a course in basic SAPprinciples nor any advanced literature on specific ABAP-relatedsubjects. It is not exhaustive in any respect. Furthermore, the bookis not intended to be a "dry run;" instead, it is intended to motivateyou to get to know and use the SAP system. All steps integral toreaching this goal are comprehensively described on the basis ofexamples, background information, and source code listings.

Who This Book Is For

This book is primarily intended for developers who work incompanies that are currently implementing an SAP system. It isalso intended for consultants and project managers who want toread and understand ABAP source code and to implement changesby themselves. Lastly, the book has also been written for studentsand trainees who are learning ABAP as part of their professionaltraining.

152.book Seite 15 Donnerstag, 11. Oktober 2007 7:18 19

Page 11: Discover Abap From Sap Press

Preface

16

What You’ll Discover

You will be guided from a simple ABAP report through importanttable maintenance tasks in the ABAP Dictionary to the modularizedflow control and complex data transfer structure between differentreports. For this purpose, we'll use a business example — a ficti-tious member management system — continuously throughoutthis book in order to apply the theoretical aspects directly to real-life scenarios. Thus, the focus of this book lies on describing andapplying ABAP knowledge, not on the business-related context.

Navigational Tools for This Book

Throughout the book, you will find several elements that will helpyou access useful information. We have used the following icons tohelp you navigate:

› Tip: Here you’ll find useful information as well as special tipsand tricks that can make your work easier.

› Note: Notes call out information about related ideas, otherresources to explore, or things you should keep in mind.

› Warning: Please watch out! This icon alerts you to commonerrors and pitfalls.

› Example: Here you’ll encounter real-life scenarios and exercises.

This is amarginal note

Additionally, marginal text provides a useful way to scan the bookto locate topics of interest for you. Each appears to the side of aparagraph or section with related information.

System Requirements

For optimal use of what is described in this book, we stronglyrecommend that you meet some basic requirements. Ideally, youshould have already familiarized yourself with some SAP basics

152.book Seite 16 Donnerstag, 11. Oktober 2007 7:18 19

Page 12: Discover Abap From Sap Press

What’s In This Book?

17

such as navigating through the main menu. Also, experience withgeneral programming logic from other programming languages,macros, or scripts would be beneficial to the success of your learn-ing efforts. In addition, having access to an SAP system, for exam-ple, an R/3 or ERP system, including the relevant authorizations,would be advantageous. Here, the mini-SAP system would be suffi-cient.

Mini-SAP System

What’s In This Book?

Chapter 1 describes the organizational and technical architectureof SAP systems as well as development prerequisites you need tobe aware of to get started with ABAP. Furthermore, it demonstratesthe division of labor between the runtime environment and appli-cation programs as well as the structure of ABAP reports.

Chapter 2 provides an overview of the purpose of the ABAP Dictio-nary. Based on the example of a transparent table, you will learnhow to create a table, how to enter and display table entries, andwhat you’ll need to do regarding data elements, domains, and tech-nical settings.

In Chapter 3, you’ll create your first ABAP report, maintain itsproperties, create the source code, and execute the report. More-over, you'll learn about the first ABAP statements and the relevantsyntax.

You'll carry out your "basic arithmetic operations using variables"in Chapter 4. This chapter will also introduce you to the propertiesof data objects and to the difference between compatibility and

The mini-SAP system is included in various SAP PRESS books (http://www.sap-press.com). Alternatively, you can purchase it at a dis-counted price from the SAP website (http://www.sap.com). The mini-SAP system provides the ABAP development environment, which isall you need when using this book.

152.book Seite 17 Donnerstag, 11. Oktober 2007 7:18 19

Page 13: Discover Abap From Sap Press

Preface

18

convertibility. In addition, it describes some useful tricks you canuse to improve list formats.

In Chapter 5, you’ll work with character strings and carry out dif-ferent variants of string operations. You’ll learn how to search forsubstrings and modify character strings.

Chapter 6 focuses on pursuing the program flow as well as on find-ing program errors. For this purpose, you’ll use the ABAP Debug-ger with its most important modes.

In Chapter 7, you’ll enhance and modify a transparent table andyou'll learn about foreign keys. In addition, you’ll implement tablecontent checks. For this purpose, you will use fixed values in thedomain, value tables, and check tables. Furthermore, you’ll learnabout the specifics of currency and quantity fields.

In Chapter 8, you will declare date and time fields, process thesefields, and examine their specific features. For a better understand-ing, this chapter uses many examples, which are described andtraced in the ABAP Debugger.

Chapter 9 describes how you can modify the contents of a databasetable, insert new rows into the table via ABAP statements, andchange and delete existing rows. Moreover, the chapter discussesthe risks involved in deleting and manipulating data.

Our sample application is beginning to get more complex: In Chap-ter 10, you’ll make some case distinctions, implement controlstructures and branches, and learn about logical expressions.

Chapter 11 describes how you can provide a report with input val-ues for the program flow in a selection screen. You will developsimple and complex selections and selection texts, and design theselection screen in accordance with your own requirements. Fur-thermore, this chapter describes the meaning of text symbols, mes-sages, and variants in relation to the selection screen.

Chapter 12 describes internal tables including their meaning anddifferent forms. You’ll learn what a header line is and be able todistinguish the difference between an internal table and a work

152.book Seite 18 Donnerstag, 11. Oktober 2007 7:18 19

Page 14: Discover Abap From Sap Press

Acknowledgments

19

area as well as important statements for processing the table rows.For a better understanding, this chapter also focuses on tracing theprogram flow in the ABAP Debugger.

Chapter 13 describes the modularization of programs. You’ll learnabout source code modules, internal and external subprograms aswell as function modules. Another important aspect discussed inthis chapter is the transfer of data and data structures to calledmodules.

Code Samples for Download

In order to avoid the time-consuming typing of source code, youcan download the source code of all sample listings from the web-site that accompanies this book at http://www.sap-press.com.

Acknowledgments

I would like to take this opportunity to thank my wife and children.They had to manage without me for a long time, and by relievingme from household work, they made it possible for me to write thisbook.

Lastly, I hope that you will enjoy reading this book and I wish allof you much success in learning ABAP.

Karl-Heinz KühnhauserNuremberg

152.book Seite 19 Donnerstag, 11. Oktober 2007 7:18 19

Page 15: Discover Abap From Sap Press

69

3

Programming in the ABAP Editor

Everything looks complicated when you first get started, but whenyou’re done, it’s usually not half as difficult as you imagined. Smallsuccesses balance out the effort. After working through this chap-ter, you’ll be proud of your first list.

This chapter shows you how to use the ABAP editor to create, acti-vate, and execute your first program. It familiarizes you with ABAPstatements and shows you how to take the first steps in workingwith the ABAP editor.

Creating an ABAP Report

SE38You can start the ABAP editor from the SAP menu (Tools � ABAPWorkbench � Development � ABAP Editor) or using TransactionCode SE38.

One name, one program

You must enter a program name in the initial screen. The name canbe up to 30 characters long and should contain only letters andnumbers. Don’t use special characters (letters with diacritical

152.book Seite 69 Donnerstag, 11. Oktober 2007 7:18 19

Page 16: Discover Abap From Sap Press

Programming in the ABAP Editor

70

3

marks) except for an underscore. Please remember that you mustadhere to the naming convention for customer objects. The pro-gram name must begin with a "Z," so name your first report"Z_MEMBERLIST01" and click Create (see Figure 3.1).

Figure 3.1 Creating an ABAP Report

Maintaining pro-gram properties

In the next screen, you define the attributes — the properties of thereport (see Figure 3.2) — and give it a descriptive Title, such as"First Member List." You must also specify the original language ofthe report — the language in which it is created —"EN" for Englishin this case.

Why is this information important?

The information in the original language of the report is important,because all texts in SAP, whether in menus or screens, are maintainedin a country-specific manner. SAP provides a proprietary translationtool that you can use to translate the texts from the original languageto the target language, without having to change the source code ofthe program. If developers have done their job well, a translator with-out programming knowledge can translate all the texts.

152.book Seite 70 Donnerstag, 11. Oktober 2007 7:18 19

Page 17: Discover Abap From Sap Press

Creating an ABAP Report

71

3

Figure 3.2 Maintaining Program Properties

The status of our program is still "New (Revised)." That makessense, because we’re still creating it. The status will change to"Active" later on, and it will then be executable.

Program typeFor the Type of program, select Executable program. An execut-able program can be started without a transaction code directly, orin the background with a batch job. The invisible runtime envi-ronment controls the report. It calls defined processing blocks in afixed sequence and handles the processes of program execution,such as outputting a list at the end of the report.

Program statusAs the Status of the program, select Test program from the list andselect Basis for the Application. Both criteria help programmanagement. They describe the status of program development: ifyou’re dealing with a finished customer program in production ora program in the experimental and testing phase. They alsodescribe the business application area that the program belongs to.

152.book Seite 71 Donnerstag, 11. Oktober 2007 7:18 19

Page 18: Discover Abap From Sap Press

Programming in the ABAP Editor

72

3

See Chapter 11for more information

on the Selectionscreen.

Leave the next three optional fields blank. You can use the Autho-rization Group to assign the program to a program group and thenset authorization checks for the group, so that only authorizedusers can start the report. A Logical database is a higher-level read-program that makes it easier for you to find and assign data in var-ious tables. It can ensure that data is processed in the rightsequence and perform other tasks that we cannot discuss in moredetail here.

Additionalattributes

Select the following settings for the four remaining checkboxes:

› Editor lockDo not set the Editor lock. You need it only when you want toprevent another user from changing, renaming, or deleting theprogram. In the real world, this precaution can be helpful. Onlythe author of the last program change can remove the lock.

› Unicode checks activeCheck Unicode checks active. As of Release 6.10, ABAP sup-ports multibyte coding. Earlier releases used only character setsbased on single-byte coding — ASCII or EBCDIC codes. In somecircumstances, programs without Unicode checks can triggersyntax or runtime errors.

› Fixed point arithmeticActivate Fixed point arithmetic. Otherwise, packed numbersare treated as whole numbers without consideration of decimalplaces, and intermediate results are rounded in calculations. Inother words, if you’re interested in exact calculations (which isthe case in Chapter 4), you must activate fixed point arithmetic.

› Start using variantDon’t select Start using variant. Variants populate the selectionscreen with initial values. To ensure that a report is actuallypopulated with the same initial values every time the reportruns, you can store the selection screen in a variant. If you startthe report with the variant, the selection screen is already popu-lated, which significantly reduces the risk of errors.

152.book Seite 72 Donnerstag, 11. Oktober 2007 7:18 19

Page 19: Discover Abap From Sap Press

ABAP Editor: Overview

73

3

Tip

Maintaining an object catalog entry

After you save the program, you’re instructed to create an objectcatalog entry. As we noted in Chapter 2, you should save the objectlocally.

ABAP Editor: Overview

Frontend andbackend mode

That automatically (and finally) takes you to the ABAP editor (seeFigure 3.3), which has two basic modes: frontend mode and backendmode.

Figure 3.3 ABAP Editors in Change Mode

The Start using variant option is beneficial in your daily work. In thereal world, these kinds of selection screens can be quite compre-hensive. But right now, starting the report with only a variant will notbe helpful. In Chapter 11, we will assign initial values to the reportwith a selection screen for the first time.

152.book Seite 73 Donnerstag, 11. Oktober 2007 7:18 19

Page 20: Discover Abap From Sap Press

Programming in the ABAP Editor

74

3

Modes of the ABAP Editor

The frontend mode loads the ABAP source code onto the client,where it is processed locally. In backend mode, the source code isnot loaded locally. It remains on the server. Saving a change in thesource code transmits the change to the server.

Both modes offer the same layout of the source code and are appro-priate for editing ABAP source code. The difference between thetwo modes lies in their operation and functional scope:

Operation andfunctional scope

› Frontend modeIn frontend mode, local editing quickly executes all editing func-tions without communication with the server. The contextmenus are user-friendly, and functions like cut, copy and paste,and drag-and-drop will probably remind you more of a wordprocessing program than a program editor. But communicationbetween the frontend and the backend when large quantities ofdata are involved can have quite a negative affect on perfor-mance. Frontend mode also assumes specific operating systemson the client.

› Backend modeThe traditional backend mode works to accomplish a goal. It pro-cesses several rows as a block of rows during cut and paste andrequires highlighting the block with several clicks (see Table 3.2in this chapter). We recommend using various intermediatebuffers so that you can use several clipboards at one time.

Why backend mode?

Although novices probably find that it takes longer to get used to andis not immediately comfortable, the backend mode has two advan-tages. It offers better performance with large quantities of data and itcan process all the development objects that the ABAP editor needs.Limitations still exist in frontend mode. Backend mode also doesn’tlimit the choice of local operating systems on the presentation server.

That’s why we will always use backend mode in the following. Ofcourse, you can use frontend mode if it better meets your personalstyle of working.

152.book Seite 74 Donnerstag, 11. Oktober 2007 7:18 19

Page 21: Discover Abap From Sap Press

ABAP Editor: Overview

75

3

Switching between editor modes

The ABAP editor always starts in the last mode in which it wasoperated. If you want to switch from one mode to another, use theUtilities � Settings menu to navigate to the dialog for user-specificsettings in the ABAP Workbench. Select the new editor mode in theABAP Editor tab and confirm your selection with Enter. The set-ting remains in effect until you change it again.

Controlling the ABAP Editor

Toolbars as controlling units

Above the input and output area of the screen that is used to editsource code, you’ll find the control area of the ABAP editor: twotoolbars. The upper one (see Figure 3.4) helps to control the ABAPeditor. Table 3.1 explains the individual icons.

Figure 3.4 Toolbar to Control the ABAP Editor

Icon Function Description

Switch between changing and displaying the source code

When you change the source code, the background of the input and output area is white. The background changes to gray after you switch to "Display." Of course, you cannot change the source code in this mode.

Switching program status from active to inactive

Several versions of an object can exist in the real world, but only one of them can be active at any given time. If you want to inactivate an active version for a time so that you can activate a different version of the object, you can use this function.

Switching to another object

During a project, developers simultaneously work on several modules that they become familiar with little by little. You can use this function to display a window from which you can quickly control all other objects that belong to your development project.

Table 3.1 Functions of the Toolbar to Control the ABAP Editor

152.book Seite 75 Donnerstag, 11. Oktober 2007 7:18 19

Page 22: Discover Abap From Sap Press

Programming in the ABAP Editor

76

3

Switching to another object(cont.)

The only type of object you have become familiar with so far are dictionary objects like tables. Advanced developers use this function to navigate to function groups, class libraries, and web objects.

Syntax check of the source code

If the system finds a syntax error during a check, a window is displayed that indicates the problem areas. If it does not find any errors, the status line notifies you that no syntax errors were found.

Activate program If the program is inactive, the system creates an active version with this function. The correctness of the syntax is checked and an active program version and runtime version are generated. The active object is generated even if the program is already active.

Execute program in test mode

The program is started in test mode in the Workbench.

Where-used list of the object

If an object is used in or by other objects, the list shows in which other objects the current object is used. You can navigate to the location of the call from the list to check the context in which the object is used there. For example, tables are used in many programs, so that changes to a table structure could have unpleasant side effects. When making changes, it’s always a good idea to gather information about the environment in which an object works.

Display object list This function takes you to the view provided by a different tool, the repository browser. You see all the objects that belong to your development project. You work with the repository browser when you require access to several objects for a project.

Icon Function Description

Table 3.1 Functions of the Toolbar to Control the ABAP Editor (cont.)

152.book Seite 76 Donnerstag, 11. Oktober 2007 7:18 19

Page 23: Discover Abap From Sap Press

ABAP Editor: Overview

77

3

The lower toolbar (see Figure 3.5) is used to edit the source code.As you can easily see from the icons, the functions here are similar

Display navigation window

This function is quite practical in complex development projects. An additional window displays the last objects that were edited, so you can quickly navigate among them.

Help on. . .

This function opens a context-dependent window. This window appears in the ABAP editor when you request help on ABAP terms like key words, function modules, and tables.

Set or delete breakpoint

Sooner than you think, the program will do what it was programmed to do rather than what you want it to do. The end of the program no longer meets expectations and it’s time to observe the processing of the program.

Set or delete breakpoint(continued)

You use this function to set a stopping point (breakpoint) on a line of source code. The control icon is displayed to the left of the line. When the program runs, it stops at this line and switches to debugging mode (see Chapter 6). Double-click on the icon at the start of the line to delete the breakpoint.

Insert pattern You must often insert several lines of commands or comment blocks in the source code. To save you the effort of all that typing, this function is quite practical. For more information, see Chapter 10.

Pretty Printer Source code can quickly become unmanageable unless visual aids are built in for comments, paragraphs, and insertions. To avoid having you keep track of how many spaces you need at the start of a line (for nested loops, for example), this practical function handles everything for you.

Icon Function Description

Table 3.1 Functions of the Toolbar to Control the ABAP Editor (cont.)

152.book Seite 77 Donnerstag, 11. Oktober 2007 7:18 19

Page 24: Discover Abap From Sap Press

Programming in the ABAP Editor

78

3

to those of other interfaces: cut, copy, paste, and so on. Table 3.2explains the meaning of the icons.

SAP buffers In particular, working with buffers differs from working with theclipboards familiar to you from your client. In addition to thebuffer of the presentation server (client) as the standard buffer, theSAP system has three additional buffers: X, Y, and Z.

Copying withina system and

beyond a system

If you’re copying in the standard SAP buffer, you can insert thecontents of the buffer into another location in the source code inthe same mode. If you’re copying in one of the three supplementalbuffers, you can also insert the contents into the source code in adifferent mode. In both cases, however, the SAP system must bethe same. The buffers are related to the system and are emptiedwhen you quit the editor or log off the system. If you want to copybetween systems, you must start from the SAP system and copy tothe buffer of the client, either with the SAP menu or with Ctrl+Cand Ctrl+V.

The cursor must be placed on the line that is being edited. A sectionof a line must be highlighted beforehand. A block that consists ofseveral lines must be highlighted at the beginning and at the endof the block.

Figure 3.5 Toolbar to Edit Source Code

Icon Function Description

Cut line If you place the cursor on a line in change mode and press this button, you cut the line out of the source code. It disappears from the source code and is stored in the SAP buffer. From there, you can insert the line into another location in the source code. The SAP buffer has only one set of content: new content overwrites old content.

Table 3.2 Functions of the Toolbar for Editing Source Code

152.book Seite 78 Donnerstag, 11. Oktober 2007 7:18 19

Page 25: Discover Abap From Sap Press

ABAP Editor: Overview

79

3

Copy line This function copies the line in which the cursor is placed into the SAP buffer. The source code still contains the original line.

Insert line In change mode, this function copies the content of the SAP buffer to the line in which the cursor is placed.

Selection mode You use selection mode to edit several lines as a block. To copy a block of lines to another location in the source code, proceed as follows in change mode:

1. Place the cursor in the first line of the block of lines.

2. Click on the selection button: the line turns red.

3. Place the cursor on the last line of the block of lines.

4. Click on the selection button again. This line and all the lines in between turn red.

5. Copy the selected block to the X buffer (or to one of the other buffers) via Utilities � Block/Buffer � Copy to X Buffer. The status line notifies you that the block was copied to the buffer.

6. Position the cursor in the target line. Careful programmers create a blank line for the sake of safety and position the cursor there. In the following step, the contents of the buffer are inserted into the line in which the cursor has been placed.

7. Insert the contents of the X buffer into the source test via Utilities � Block/Buffer � Insert X Buffer.

Cancel command Cancel the last editor command in change mode.

Insert new line In change mode, insert a blank line in front of the line in which the cursor has been placed.

Icon Function Description

Table 3.2 Functions of the Toolbar for Editing Source Code (cont.)

152.book Seite 79 Donnerstag, 11. Oktober 2007 7:18 19

Page 26: Discover Abap From Sap Press

Programming in the ABAP Editor

80

3

Delete line In change mode, delete the line in which the cursor has been placed.

Concatenate line In change mode, this function merges the current line with the following line. This option is helpful when editing leaves only one word of a command in the following line.1

Duplicate line/block You can use this function to copy lines or blocks in the source code and reinsert them into the original position with a click. Depending on the actual case, it works like a combination of the Copy Line and Insert Line buttons or the steps to highlight a block, copying a block to the buffer, and reinserting the block in front of a line.

Move line/block This function moves text. The text in the line is moved five columns to the right. If you don’t want to rely on Pretty Printer, you can use this function to ensure better legibility on your own.

Find You can use this function to search for and replace text in the source code. Whether you’re searching for a character string that is a word, a character string that is part of a larger character string, or for uppercase or lowercase characters, this function will find it if it exists. The cursor in placed on the first line of the hit. You can set the search area at the cursor position or specify a set of lines. If several inactive versions of your source code exist, you can also search inactive versions.

Find next You usually need this function along with the Find function. If you suspect the presence of additional hits in your source code, you can continue to search with this option.

1 Please use this option carefully. You can use it to write two short commands inone line. ABAP has no problem if you end every command with a period, butdoing so would make the source code difficult to read and runs counter to theconvention of placing each new command in a new line.

Icon Function Description

Table 3.2 Functions of the Toolbar for Editing Source Code (cont.)

152.book Seite 80 Donnerstag, 11. Oktober 2007 7:18 19

Page 27: Discover Abap From Sap Press

Understanding and Editing ABAP Programs

81

3

Understanding and Editing ABAP Programs

Comments in thesource code

When you now look at the source code (see Figure 3.3), you mightsee red, especially in lines 1–7. The asterisk (*) in the first positionturns the entire editing line into a comment line. You also have asecond option for comments: you can write something after anopening quotation mark ("). Everything after the quotation mark isinterpreted as a comment rather than as a command. Section“Notes on the Source Code” in this chapter provides an example ofthis feature.

Please try from the very start to create good legible inline documen-tation; the business world calls this adequate documentation, butthis term is not operational. Comment lines that make up some30 % (or more) of the source code can, in some situations, be com-pletely appropriate. Always remember that you might soon be athird-party looking at the source code. You will note how quicklyyour own code becomes unfamiliar even after a couple of months.

REPORTIn the ABAP editor, you’ll see black along with red in line 9. Thisis the first ABAP statement (also called a command) that you’llbecome familiar with, namely, the REPORT statement. It is alwaysthe first statement in an executable program.

You’ll also see the first operand (or addition) of the command: theprogram name (Z_MEMBERLIST01).

One more pointYou can also see a period (.) in the line, because every ABAP state-ment must end with a period. Even if a statement stretches overseveral lines or screens, a period must be placed at the end of thestatement. However, you should note that a period doesn’t have afixed place like the end of a line. It is just important that the periodis the last character of the command (i.e., it closes the command).The place in the line is not important. It also could be placeddirectly after the last operator. See the following complete state-ment:

REPORT Z_MEMBERLIST01.

152.book Seite 81 Donnerstag, 11. Oktober 2007 7:18 19

Page 28: Discover Abap From Sap Press

Programming in the ABAP Editor

82

3

Tips for self-help

WRITE Of course, you want to see the success of your first ABAP programquickly, so you now write your first comment in line 10 (after theREPORT statement):

WRITE 'This is my first list'.

Literal It’s not difficult to discern that the WRITE statement outputs a list,in this case, a literal 'This is my first list'. A literal is a set char-acter string in the source code. It begins with a single quotationmark and unfortunately cannot be maintained as language-depen-dent. In Chapter 11, we’ll start working with text elements that canbe translated, but for now let’s just enjoy our immediate success.

Figure 3.6 ABAP Keyword Documentation

If the REPORT command didn’t offer any explanation here, you can eas-ily determine what the statement does and what operands it has.Click on the statement and then press F1. A help window opens withABAP key word documentation; you have information on the effects ofthe command along with examples and tips (see Figure 3.6). The win-dow also displays possible additions, and you can display hints andexamples as well.

152.book Seite 82 Donnerstag, 11. Oktober 2007 7:18 19

Page 29: Discover Abap From Sap Press

Executing an ABAP Report

83

3

Executing an ABAP Report

Short countdownFour steps are involved in the execution of our first ABAP program:

� Save

� Check

� Activate

� Execute

Save the program via Program � Save or with the Save (Ctrl+S) but-ton. The status line issues a confirmation. Then check the programvia Program � Check � Syntax or the Check (Ctrl+F2) button. If youreceive a message in the status line that no syntax errors werefound in the program, you can activate the program via Program �Activate or with the Activate (Ctrl+F3) button.

Activation checks the correctness of the syntax, generates an activeversion of the program, generates a runtime environment, anddeletes the object from the list of inactive objects. Activation there-fore combines several work steps. You should already be familiarwith the next activation screen from Chapter 2. The status line dis-plays the message, "Object was activated." The report is thenexecutable and you can start (execute) it.

Starting from theABAP Workbench

You have two ways to perform a required test here. The first wayis to navigate via Program � Test � Directly or with the Directly(F8) button. You start the report from the ABAP Workbench. If theprogram terminates, you then have to reopen the ABAP Work-bench and redisplay the source code on the screen to look forerrors and correct them.

Starting from ABAP program execution

The second way is akin to the way that a user would start a report.Usually, users don’t have the necessary access rights to work in theABAP Workbench. Depending on the rights that a given user hasbeen assigned, user menus can look different, but they all haveentries for System and Help. That’s why a “normal user” can startthe report from the SAP menu with System. Let’s test thisapproach.

152.book Seite 83 Donnerstag, 11. Oktober 2007 7:18 19

Page 30: Discover Abap From Sap Press

Programming in the ABAP Editor

84

3

Open a second session (a second window) via System � GenerateSession or with the Generate New Session button. In this session,navigate via System � Services � Reporting to ABAP program execu-tion . In this case, the system has already entered the name of theprogram to be executed in the field. You simply have to press theExecute (F8) button to start the program. The advantage of usingthis approach is that you can see the dump in the second session ifthe program terminates. If the program terminates, the systemgenerates a log as a screen list that contains hints about probablecauses and an excerpt of the source code that caused the error. Ifthe source code is still in the first session, it’s much easier to ana-lyze errors and make corrections.

Did everything work?

Figure 3.7 First Output of a List

That wasn’t difficult, but we’re not done yet. In the next step, let’stry to output the data records of the table that we created and popu-lated in Chapter 2.

We’re assuming that our first attempt didn’t trigger a program termi-nation. If everything worked, you can see the result — the first mem-ber list (see Figure 3.7). You can use the Back (F3) button to returnto ABAP program execution. Then you have to switch to the sessionwith the ABAP editor.

152.book Seite 84 Donnerstag, 11. Oktober 2007 7:18 19

Page 31: Discover Abap From Sap Press

Reading and Outputting Database Tables

85

3

Reading and Outputting Database Tables

When you want to work with database tables in a report, you mustinform the report about the tables. You can inform the report aboutour table, ZMEMBER01, with the following statement:

TABLES zmember01.

TABLESThe TABLES statement implicitly creates a structure of the samename in the program, the table area or table work area. All the fieldsof the structure have the same names and data types as the fields inthe database table. When reading the data records from the data-base table, you can place each of them in the structure and thenwork with them.

The hyphen

SELECTThe following program is the simplest way to output the rows of adatabase table line-by-line in a list:

SELECT * FROM zmember01.WRITE / zmember01.

ENDSELECT.

The SELECT statement means that the records from the ZMEM-BER01 table are transferred, record for record, into the program

You address the fields of the structure with their names; you addressthe MNAME fields of the ZMEMBER01 table with ZMEMBER01-MNAME.The first part of the name is the table name; the second part of thename is the field name. Note the hyphen between both parts. It sepa-rates the parts of the name without any blank spaces. For your addi-tional work, also note that you use the hyphen only for this purpose:never use it with variable names.

Of course, no one remembers the type declarations for all the fieldsof the database tables in use. If you need to refer to them, use forwardnavigation (double-click on the name of the table) to branch to thedisplay of the dictionary, where you can see the required informationon the fields in the Fields tab. Then use the Back button to return tothe ABAP editor.

152.book Seite 85 Donnerstag, 11. Oktober 2007 7:18 19

Page 32: Discover Abap From Sap Press

Programming in the ABAP Editor

86

3

structure. The asterisk (*) indicates that all the fields of a record aretransferred. If you want to transfer only some of the fields, youmust specify those fields as a field list instead of using the asterisk.

In this form, the SELECT command corresponds to loop processing.All records of the database table are transferred to the programstructure record by record. The structure of the loop begins withthe SELECT statement and ends with the ENDSELECT statement.

Formatting Lists

The structure contains the statements for processing the recordsthat have been read. In this case, the entire ZMEMBER01 structurewill be written to a list for each record. You trigger a new line witha slash (/) in the WRITE command. Please note that you must inserta space before and after the slash.

WRITE / With three data records in the database table, you have three linesin the list: each line of the list is as long as the structure. The struc-ture is output as a character string in the list. There is no empty col-umn between the fields and the legibility of the list leavessomething to be desired. It would be better to see the fields in thedesired order with some space between them on the list. You mustaddress the fields of the structure. Consider the following example:

WRITE / zmember01-mdob.

The slash triggers output of the field on a new line. The followingstatement, however, places the output of the field at the end of thecurrent line of print: the field is simply appended to the line.

WRITE zmember01-mname.

This approach can truly produce infinitely long lines. On its own,the system breaks a line on the screen only when the screen set-tings demand it. It breaks a line on paper only when the output set-tings on the printer or the width of the paper demand it.Accordingly, each and every developer is responsible for the cor-rect design of a line.

152.book Seite 86 Donnerstag, 11. Oktober 2007 7:18 19

Page 33: Discover Abap From Sap Press

Formatting Lists

87

3

Chain Statement

A WRITE statement is needed for every field of the structure thatshould be output in the list. You would have to expend a great dealof effort to write a statement each time. Luckily, you don’t have to.Simply tell the system that several WRITE statements are to be exe-cuted after each other.

WRITE:Place a colon (:) after the first statement and separate the statementwith a comma instead of a period. Place a period only after the laststatement. In our example, the chain statement appears as follows:

WRITE: / zmember01-mdob,zmember01-mname.

Of course, these kinds of chain statements are not limited to WRITEcommands.

Looking good

Lines

UnderlineFor simple list formatting, the ULINE command (without additionaloperands) creates a horizontal line in a new line of the list.

ULINE.

You can use this command to set off sections of a list and improveits legibility.

Blank Lines

The SKIP statement creates blank lines in a list.

SKIP.

Please consider the transparency and readability of the source code.Even when you work with chain statements, you must adhere to theprinciple of writing each statement to a new line. As far as possible,you must avoid writing two or more statements in one line.

152.book Seite 87 Donnerstag, 11. Oktober 2007 7:18 19

Page 34: Discover Abap From Sap Press

Programming in the ABAP Editor

88

3

If you want to create several blank lines, simply specify the numberof blank lines. The following statement produces three blank lines:

SKIP 3.

Writing and Editing Source Code

Type it yourself You can simply type your first source code manually (see Listing3.1),1 so that you can become familiar with the ABAP editor. Youcreate empty lines with Enter. You can also use the familiar copyand insert functions (Ctrl+C, Ctrl+V, and so on) and practice withthe additional functions of the ABAP editor for entire lines orblocks of lines, as described in Section “Controlling the ABAP Edi-tor” in this chapter.

1 *&---------------------------------------------*2 *& Report Z_MEMBERLIST01 *3 *& *4 *&---------------------------------------------*5 *& *6 *& *7 *&---------------------------------------------*89 REPORT z_memberlist01 .10 TABLES zmember01. " Declare table11 WRITE 'This is my first list'.12 ULINE. " horizontal line1314 * loop15 * each record of the table with all fields16 * will be printed on a new line of the list17 SELECT * FROM zmember01.18 WRITE / zmember01.19 ENDSELECT.20 SKIP. " 1 blank line2122 * select statement like before

1 You can also download the source code in Listing 3.1 from the website for thisbook at http://www.sap-press.com.

152.book Seite 88 Donnerstag, 11. Oktober 2007 7:18 19

Page 35: Discover Abap From Sap Press

Writing and Editing Source Code

89

3

23 * single fields of the record will be printed24 SELECT * FROM zmember01.25 WRITE / zmember01-mdob.26 WRITE zmember01-mname.27 ENDSELECT.28 SKIP. " 1 blank line2930 * select statement like before31 * single fields will be printed like before32 * but the write statement is concatenated into a chain

statement33 SELECT * FROM zmember01.34 WRITE: / zmember01-mdob,35 zmember01-mname.36 ENDSELECT.

Listing 3.1 Z_MEMBERLIST01 Report

Notes on the Source Code

Short documentation

You start editing in line 10, right after the REPORT statement that isinserted automatically. The system automatically generates thefirst eight lines. They serve as short documentation on the author,creation date, and change history.

Line 10TABLES zmember01. " Declare table

The report is therefore aware of the ZMEMBER01 table (along withits structure and fields) and creates a table area in the program thatyou can use to read and process the table fields. The statement con-cludes with a period.

Comment linesAfter the blank space, a comment line begins with the quotationmark in the same line: "Declare table." The system interprets allcharacters to the right of the quotation mark as a comment. Evenif you write a statement over several lines, you can still insert com-ments into individual lines. The comments would appear in themiddle of the statement.

152.book Seite 89 Donnerstag, 11. Oktober 2007 7:18 19

Page 36: Discover Abap From Sap Press

Programming in the ABAP Editor

90

3

Line 11WRITE 'This is my first list'.

The text between single quotation marks is output to the currentposition in the list. Because this is the first WRITE statement, thecurrent position is line 1, column 1.

Line 12ULINE. " horizontal line

ULINE produces a horizontal line across the entire width of the list.That separates the title from the rest of the list.

Line 13The blank link should improve the legibility of the list.

Lines 14, 15, and 16* loop* each record of the table with all fields* will be printed on a new line of the list

These three lines are comment lines that explain the followingstatements.

Line 17SELECT * FROM zmember01.

One recordafter the other

The SELECT statement opens a structure. A loop reads all the datarecords of the table and transfers them one by one into the tablearea of the program. The table area contains a complete record ofthe table. The record is processed from the table area. Onceprocessing of the record ends, the next record is read. The asteriskmeans that all the fields of a record are being selected.

Line 18WRITE / zmember01.

The slash after the WRITE statement outputs the list to a new line incolumn 1, rather than to the current print position. Note that ablank space must be placed before and after the slash.

152.book Seite 90 Donnerstag, 11. Oktober 2007 7:18 19

Page 37: Discover Abap From Sap Press

Writing and Editing Source Code

91

3

Output as character string

Writing the ZMEMBER01 option outputs the table area as a whole— as a character string. The length of the character string is thesum of the lengths of the fields. In the character string, the fieldsare given according to their type – they are not formatted for print-ing.

Line 19ENDSELECT.

The ENDSELECT statement closes the open SELECT structure. Justlike other loops have a closing command for every opening com-mand, each SELECT statement (if it’s a loop) has an ENDSELECTstatement.

Just like math

Line 20SKIP. " 1 blank line

Improved legibilityThe SKIP statement creates a blank line in the list. This statementis helpful for improving the legibility of the list.

Lines 21, 22, and 23The source text has a blank line and two comment lines here, justas it does in lines 13—16.

Line 24SELECT * FROM zmember01.

The situation here is similar to that working with brackets in math. Anopening bracket always has a closing bracket: they always appear inpairs. When nesting brackets, you must make sure that you haveassigned them correctly. The same applies to loops in programming.When nesting loop structures, you must also take special care to makesure that the loop is opened in the right position, the loop processingruns correctly, and that the loop is closed. We have not yet nested anyloops, but the principle applies already.

152.book Seite 91 Donnerstag, 11. Oktober 2007 7:18 19

Page 38: Discover Abap From Sap Press

Programming in the ABAP Editor

92

3

All records of the table are reread in a loop — as in line 17. Theredifference here is in the following record processing.

Line 25WRITE / zmember01-mdob.

Writing convention

Line 26WRITE zmember01-mname.

This WRITE statement also outputs a field of the table structure: theMNAME field. The output is placed in the current position in thelist, after the MDOB field in this case. If fields are written after eachother in the same line, the system automatically inserts a linebreak.

LINE-SIZE With this kind of output, you must make sure that the line hasenough room for the fields that you want to have in the first line.You could also add LINE-SIZE after the REPORT statement to manip-ulate the width of the list.

Line 27ENDSELECT.

The ENDSELECT statement closes the SELECT loop from line 24 —the last one that was opened.

This WRITE statement outputs a field from the work area of the tablestructure: the MDOB field of the ZMEMBER01 table structure. Notethe writing convention here: structurename-fieldname. If the fieldname or the structure name contains a hyphen as part of the name,the system cannot uniquely identify and interpret the statement.That’s why when assigning names, you should always work with anunderline ( _ ) –TABLE_A-FIELD_B, for example.

The slash after the write statement always places the output on a newline in column 1.

152.book Seite 92 Donnerstag, 11. Oktober 2007 7:18 19

Page 39: Discover Abap From Sap Press

Writing and Editing Source Code

93

3

Line 28SKIP. " 1 blank line

As in line 20 of the source code, insertion of a blank line hereimproves legibility.

Lines 29–32Blank lines and comments are inserted into the source code here.

Line 33SELECT * FROM zmember01.

The table is read for the third time.

Line 34 und 35WRITE: / zmember01-mdob,

zmember01-mname.

C as in chain statement; C as in comma

In the list, the result looks exactly like the second read loop. Thedifference is in the writing. When several statements that followeach other are the same and differ only in the operands, you canuse a chain statement. Line 34 has a colon right after the WRITEstatement — without a space. That tells the system that severalWRITE statements now follow each other. The individual statementsare not ended with a period, but are separated by commas. Onlythe last statement, as usual, is closed with a period.

The first statement in our example outputs the MDOB field of theZMEMBER01 table structure to a new line in column 1. It is closedwith a comma. The second statement writes the MNAME field ofthe same table structure to a list with a blank space after the MDOBfield. Because this statement is the last statement of the chain state-ment, it is closed with a period. Please note that a chain statementcan involve several statements right after each other. The principlethat a new command belongs in a new line also applies to a chainstatement.

Line 36ENDSELECT.

152.book Seite 93 Donnerstag, 11. Oktober 2007 7:18 19

Page 40: Discover Abap From Sap Press

Programming in the ABAP Editor

94

3

Don’t forget to end the loop: this ENDSELECT statement belongs tothe SELECT statement in Line 33.

List Screen from Our Sample Source Code

Self-programmedoutputs

If you look at the list screen (see Figure 3.8), you can see that thesystem has generated some outputs on its own: the date and thedescriptive text from the program properties.

Figure 3.8 List Screen for the Z_MEMBERLIST01 Report

But right now, the outputs that we created ourselves are moreimportant:

Outputs created › The first line is the text, "This is my first list."

› The second line is the horizontal line beneath the text.

› The next three lines present the unformatted output of the tablestructure. One line in the list corresponds to the complete con-tents of the structure. Because the table contains three datarecords, the processing loop is run through three times and threelines are written to the list.

152.book Seite 94 Donnerstag, 11. Oktober 2007 7:18 19

Page 41: Discover Abap From Sap Press

Writing and Editing Source Code

95

3

› After the blank line, you can see three lines, each with a birthdate and name. Note that the date is output in a different formatthan it was in the first block. When we declared the field in thetable, we defined the "Date" field type. That includes a country-specific presentation of the data format. The internal formattingof the field is seen in the output of the table structure: YYYYM-MDD. Because only two fields of the table structure should beoutput, the remaining fields do not appear in the list.

› The contents of the third block do not differ from those of thesecond block. The difference exists only in the source code,where the WRITE command was given as a chain statement.

Did everything work as planned? If so, use the Back (F3) button toreturn to the ABAP editor. In the next step, we’ll work with fieldsand calculations.

152.book Seite 95 Donnerstag, 11. Oktober 2007 7:18 19

Page 42: Discover Abap From Sap Press

491

Index

$TMP 48, 163&, placeholder 347* 81. 81/ 86

A

ABAP 21ABAP commands 81ABAP Debugger 139, 144, 155, 411,

425call 140close 155system fields 147tablespace 149

ABAP Dictionary 39, 44, 46, 161, 187, 201, 214, 232, 237

ABAP Editor 40, 69, 73, 88controlling 75dynamic breakpoints 155icons 75toolbar 75

ABAP keyword documentation 82ABAP memory 467ABAP Objects 31, 380, 445ABAP programs

modular structure 32structure 31

ABAP reportcreating 69executing 83

ABAP runtime environment 31ABAP statements 81ABAP Workbench 37, 83, 432Access effort 393Access key 37, 373Access time 373, 374Accounting 36Activation sequence 166ADD 110Addition 82, 108ADJACENT DUPLICATES 400

Advanced Business Application Pro-gramming � ABAP

Alphanumeric characters 122AND 285AND RETURN 449APPEND 382, 388, 423, 426Append structure 159, 180

activating 182assigning 180component 181, 182creating 180maintaining 179name 181

APPL0 63Application layer 23Application server 24Arithmetic operations

using date fields 202Arithmetic operator 110

- 110* 110+ 109/ 110, 113

Array fetch 385, 408Article numbers 123AS CHECKBOX 321AS TEXT 397Assigning names to variables 103Asterisk 463AT 130AT SELECTION-SCREEN 314, 315,

346AT SELECTION-SCREEN ON 318AUTHORITY-CHECK 233Authorization

check in source code 233concept 232group 72object 233program execution 234transactions 234

Automatic client management 65Automatic type conversion 282, 383

152.book Seite 491 Donnerstag, 11. Oktober 2007 7:18 19

Page 43: Discover Abap From Sap Press

492

Index

B

Back-end mode 73, 74advantages 74

Background processing 337Basic arithmetic operations 102, 108Basics of ABAP programming 33BEGIN OF 376BEGIN OF LINE 348BETWEEN 283Blank character 109

removing 128Blank lines, generating 87Block

duplicate 80moving 80

Block name 350Block of lines

deleting 101selecting 100

Block/buffer 100Block-by-block transfer 385Body line 441, 467

change 391delete 400, 401, 402

Branch 266BREAK-POINT 142, 157Breakpoints 77, 140, 150

active 154delete 154, 155dynamic 142, 155, 157manage 155save 155set 142, 154

Breakpoints mode 154Buffering 63, 78, 232BY 396

C

c, data type 122, 125, 131, 202, 214, 240, 241, 282

Calculation 97determining an invoice amount 216determining an invoice date 203determining keydates 202

Calculation 97 (cont.)determining last day of previous

month 205determining last day of the current

month 206determining past days 206determining periods of time 202determining remaining days 207determining the age of a person 207determining the beginning of a month

204determining the keydate 204determining the payment date 203dimension of time periods 208remaining days 207sales tax 215time period containing date change

212time period in days 209time period in hours 210time period in minutes 210time period in seconds 210time period in years 209time until midnight 211using time fields 209with currency fields 214with quantity fields 214

Calculation accuracy 112CALL FUNCTION 459, 465Cardinality 177CASE 270, 272, 296, 465Case distinction 261, 270Case sensitivity 300Central control component 489Chain statement 87, 93, 117, 375, 376,

378CHAR, data type 166, 169Character string 91, 121, 122

complementing 124concatenating 128condensing 127modifying 121replacing 124, 126searching 124shifting 124splitting 130

152.book Seite 492 Donnerstag, 11. Oktober 2007 7:18 19

Page 44: Discover Abap From Sap Press

493

Index

Charactersalphanumeric 122cutting 124numeric 123

CHECK 278, 438Check program logic 140Check table 175, 193Checkbox 448Checksum process 374CLEAR 240, 241, 242, 401, 402, 411,

415, 424, 427, 444Client 35

handling, automatic 237management, automatic 65number 237

Client-server architecture 23, 231Clipboard 74Cluster 467Cluster name 467Cluster tables 45Code table 282Collective shaft 269Column distribution 118Command 81

canceling 79COMMENT 348Comment 81

asterisk 81lines 100, 264on the screen 348quotation mark 81

Company code 35Compatible data objects 110Complex condition 266Components, append structure 181,

182Composite profiles 233Computational accuracy 113, 214COMPUTE 112CONCATENATE 128, 138

SEPARATED BY 129CONDENSE 127, 138

NO-GAPS 128Conditions 275

complex 284resolving 284

Consolidation system 24, 26CONSTANTS 107Constants 103Context-sensitive 346CONTINUE 277Control structure 262, 267Conversion in dialog 192Conversion rules 110, 111Convertible data objects 110Copy 189Core areas 36Create line 87Creating selection variants 334Cross-application components 36Cross-client tables 237Cryptology 374CUKY, data type 169, 170, 214CURK, data type 201CURR, data type 169, 201, 202, 214Currency

amount 169fields 169, 201key 201unit 169, 174

Customer name space 181, 184Customizing 25Cut 189

D

d, data type 199, 240DATA 104, 107, 122, 199, 221, 240,

375, 411, 422, 437BEGIN OF 376DECIMALS 104END OF 376LIKE 105, 123, 200OCCURS 376TYPE 104VALUE 106, 123, 200

Datablock 384browser 47, 165, 187class 63consistency 449declarations 433

152.book Seite 493 Donnerstag, 11. Oktober 2007 7:18 19

Page 45: Discover Abap From Sap Press

494

Index

Data (cont.)loss 190, 193temporary 324transfer 467

Data element 50activate 61check 60creating 50

Data objects 103, 377, 386, 437compatible 110convertible 110

Data records 371checking 164creating 64delete 243displaying 67entering 65

Data type 53, 55, 103, 112, 377, 437c 122, 125, 131, 202, 214, 241, 282CHAR 166, 169character 199complex 377CUKY 169, 170, 214CURK 201CURR 169, 201, 202, 214d 199, 240DEC 169, 214differences 125elementary 104, 377f 317generic 122, 123i 104, 111, 209n 123, 125, 131NUMC 55, 169p 104, 108, 111, 202, 209, 214, 215QUAN 169, 215string 488t 200UNIT 169, 215

Database layer 23Database lock 234Database server 24Database tables 465

modification 159outputting 85reading 85

Database tables (cont.)transparent 159

Database utility 190, 194Database, adjust 160, 192Date fields 199

defining 199filling 203in arithmetic operations 202processing 202

Date format 95Debugging 139Debugging mode 140, 142DEC, data type 169, 214Decimal numbers 104Decimal places 104, 107Decimal separator 107DECIMALS 104Declaration 105Declaration part 31DEFAULT 318, 328DELETE 238, 243, 244, 259, 261, 395,

400, 414, 424ADJACENT DUPLICATES 400

DESCENDING 397DESCRIBE 392

LINES 392Development system 24, 25Dialog modules 31Dictionary elements 378Digital signature 374Display list 146DIV 113, 208, 209DIVIDE 110Division 108, 113, 208

different cases 113integer 308integral 113

Division of work 232DO 273DO loops 274Documentation 54Domains 50, 106

activate 58creating 51, 55

Dump 84Dynamic name assignment 241, 244

152.book Seite 494 Donnerstag, 11. Oktober 2007 7:18 19

Page 46: Discover Abap From Sap Press

495

Index

Dynamic program � DynproDynpro 28, 312

E

Editor lock 72Editor mode 75Elementary data types 104Elements

copying 99creating your own 51

ELSE 267, 269ELSEIF 268, 269END OF 376END OF BLOCK 350END OF LINE 348ENDCASE 270ENDDO 273ENDFORM 436, 440, 441ENDIF 262, 267Endless loops 273ENDLOOP 390ENDSELECT 86ENDWHILE 276Entry check 169, 171, 174, 175, 177Error

analysis 84case 271, 296exit 465, 488handling 248, 316, 346log 190message 177

Event 363Event keyword 313, 363Event orientation 363Events 313

examples 314terminating 280

Exception handling 465, 488Exchange rate conversion 214Exclusive lock 236Executable program 71EXIT 279, 280, 302Exponential numbers 112EXPORT 467Export parameter 459, 465

EXPORT TO MEMORY 467External report

calling 446

F

f, data type 317F1 66, 82, 319, 349F3 84, 343F4 55, 66, 168, 178, 319, 334F5 144F6 145F7 145F8 84, 145, 364Field 49, 97, 103, 139, 182

asterisk 86declaring 102definitions 199identical names 377, 382, 384, 388,

389inserting 159label 53, 332length 103, 122list 86, 169, 379, 438, 467mode 144processing 102type 378

Field contentchanging 147check 146modify 147monitor 153shifting 126

Filling date fields 200Find 80Find next 80Fixed point arithmetic 72Fixed values 109, 166

individual values 167intervals 167maintaining 166testing 167

Flow control 489FOR FIELD 349Foreign key 171, 176, 235

maintaining 175

152.book Seite 495 Donnerstag, 11. Oktober 2007 7:18 19

Page 47: Discover Abap From Sap Press

496

Index

Foreign key 171, 176, 235 (cont.)relationship 193table 175testing 177

FORM 436, 437, 441, 444, 446Formatting lists 86Forward navigation 51, 85, 183, 185,

187, 432, 435, 466Frames 347FREE 402, 403, 411Free text 347FROM 400Front-end mode 73, 74Function builder 40, 450, 452

test environment 456Function code field 39Function groups 450, 451Function library 450Function module 40, 77, 235, 431,

449call 459, 462documentation 460exceptions 455export 454flow type 452import 454name 459properties 452search 451searching 450testing 450, 457value transfer 454

G

Generic data type 122, 123Generic key 176GET PARAMETER 466GET PARAMETER ID 466Global SAP memory 466Global variables 437

H

Hash algorithm 374, 395Hashed table 374, 395

Hat 411, 427, 441Header line 371, 372, 379, 380, 382,

390, 441Help 77Hierarchy levels 123HIGH 324Human resources 36Hyphen 85

I

i, data type 104, 111, 209Identical names 388IF 262, 267, 269, 278, 284IF structure 270, 323, 326, 465

nesting 269IMPORT 467IMPORT FROM MEMORY 467Import parameter 459IN PROGRAM 445INCLUDE 385, 389, 432Include

compress 187expand 187report 432

INCLUDE STRUCTURE 384Include structure 183

activating 186create 185insert 185maintaining 184position 184preconditions 183

Inconsistencies check 177INDEX 392, 399Index 373, 391, 393, 395Index tables 374, 392, 395, 399Industry minutes 225Information systems 36INITIAL SIZE 378Initial value 106, 240INITIALIZATION 313, 315, 363Initialize header line 401Inline documentation 81Input blocks 347

152.book Seite 496 Donnerstag, 11. Oktober 2007 7:18 19

Page 48: Discover Abap From Sap Press

497

Index

Input fieldspositioning 347

Input help 166, 171, 177, 179Input help list 178Input verification 315, 317, 364INSERT 237, 238, 242, 392, 399, 423Insert 189Integers 104Integral division 113Integral division with remainder 114Interfaces 378Internal tables 370, 441, 467

benefits 370define 371, 375, 379filling one record at a time 381process 390structure 370

INTO 399, 400INTO CORRESPONDING FIELDS 385IS INITIAL 283, 322Item numbers 123

K

Key 49, 379, 391, 394, 399generic 176non-unique 373, 378unique 373user-defined 373

Key fields 184, 188, 394, 399change 188deleting 190, 193manipulation 160

Key words 77Keyword documentation 82

L

Language key 343Leap year 287Legibility 32Length 131LIKE 105, 123, 200, 319, 382Limiting loop runs 274Limits 372

Lineblock 350break 86, 92change 391concatenating 80copying 79cutting 78delete 395deleting 80duplicate 80duplications 374free layout 348insert 392inserting 79inserting new line 79moving 80redundant 400structure 378

Line type 372, 376, 377, 386define 380

LINES 392LINE-SIZE 92List

formatting 86headings 330of suggested values 168processor 312, 314screen 94, 312

Literal 82, 107, 123, 244, 259, 391, 414, 459, 467

Literals 222, 300, 342LOAD-OF-PROGRAM 32, 313Local names 444Local object 27, 48, 99Local SAP Memory 466Local variable 437, 440Locale object 163Locale variable

explicit definition 437implicit definition 438

Locklogical 235point-in-time problem 236problem 236remove 236table 235

152.book Seite 497 Donnerstag, 11. Oktober 2007 7:18 19

Page 49: Discover Abap From Sap Press

498

Index

Lock concept 232, 234, 235physical database 234SAP 234

Lock objectremove 235set lock 235

Logical AND 285Logical database 72Logical expressions 261, 281

linked 269linking 284

Logical operators 281Logical OR 284Logistics 36Logon 34Logon client 65Logon screen 34Long text 460LOOP 390, 391, 392, 395, 398Loop 86, 90, 91, 227, 272, 371

endless loops 273inner 275outer 274processing 91termination statements 277with conditions 272without conditions 272

LOW 324LOWER CASE 320, 328Lower-case and upper-case letters 244LT 278

M

Maintainability 32Maintenance dialog 165Maintenance screen 185Mandatory parameter 460Memory area 376Memory ID 467Memory space, initial 378Menu painter 40MESSAGE 344, 346, 347, 364Message 341

editing 344number 347

Message 341 (cont.)on the status bar 316pool 344saving 345type 346, 364type E 346

Message class 343, 347creating 344

MESSAGE-ID 344MOD 114, 208, 209MODIFY 237, 242, 391, 392, 398

FROM 398Modularization 22, 377Module 437Module pool 312MOVE-CORRESPONDING 383Multiple selections 326Multiplication 108MULTIPLY 110

N

n, data type 123, 125, 131Name assignment

dynamic 244static 242, 243

Naming convention 181Native SQL 30, 45Navigation window 77Negation 286Nesting 91, 272, 274, 277, 378, 434Nesting levels 269Network drives 457Network paths 457NEW-PAGE PRINT ON 312NO-EXTENSION 329NO-GAPS 128Non-key fields 188

enhancing 165NOT 286Notation

modern 445traditional 445

Numbersintegers 104packed 112

152.book Seite 498 Donnerstag, 11. Oktober 2007 7:18 19

Page 50: Discover Abap From Sap Press

499

Index

NUMC, data type 169Numeric characters 123Numeric text fields 123

O

Objectactivating 166classes 233key 179list 76local 27, 48, 99, 163navigator 41

Object orientation 375, 377OBLIGATORY 319, 328OCCURS 376Office 36Open SQL 39, 232

statements 237Operations, arithmetic 209OPTION 324OR 284Output position 118

P

Packed numbers 112Parameter

mandatory 460, 463optional 463

Parameter ID 466create 466initializing 477reading 477writing 486

Parameter list, checking 445PARAMETERS 317Parentheses 287Parenthetical levels 285Patterns 77, 263

inserting 263, 266PERFORM 435, 436, 441, 444, 445,

446, 477IN PROGRAM 445USING 438

Period of time for date values 208

Physical area 63Placeholder 347Placement operands 347Point-in-time problem 236Pool tables 45POSITION 349Position 118

operand 129, 438, 441, 445specifying 118

Positioning 131Preassignment 106Preselection 291Presentation layer 23Presentation server 23Pretty Printer 77Primary key 242, 243Printing 312Procedures 32, 430, 434, 449Processing

reading 371writing 371

Processing blocks 31Processing type

background 192direct 192

Production system 25, 26Profiles 233Program

activate 76activating 83checking 83execution 84flow control 261name, dynamic 446saving 83starting 83status 71, 75termination 84

Propertiessemantic 177

Q

QUAN, data type 169, 215Quantity fields 169Quantity units 169

152.book Seite 499 Donnerstag, 11. Oktober 2007 7:18 19

Page 51: Discover Abap From Sap Press

500

Index

R

Radio buttons 322RADIOBUTTON GROUP 323Range 325, 327READ 393, 394, 399, 410, 413

INDEX 399INTO 399

Readability 103Record

create 242modify 242

Redundancies 190Reference field 170, 193, 201REFRESH 401, 402, 411, 424Release reserved memory area 402Reorganization work 160Repetition 262REPLACE 126, 138REPORT 81, 99, 141, 344Report 28

copying 98data transfer 465start with variant 340, 447

REPORT, LINE-SIZE 92Repository info system 450Response time 374Return code 147, 238, 239, 242, 243,

271, 296, 414, 465, 488Reusability 185, 377Role 233Row

create 242delete 189, 243highlighting 74insert 189update 242

Runtime environment 313Runtime object 163Runtimes 192

S

Sandbox 26SAP GUI 33SAP Logon 34

SAP Memory 477read 466write 466

SAPscript Editor 54Screen check 177Screen painter 40SE11 44, 161SE38 69SE91 344Search term 126Search, generic 451SELECT 85, 227, 237, 272, 273, 381,

385Selection buttons � Radio buttonsSelection mode 79, 100Selection screen 311, 319, 334, 338,

447, 448avoiding 448processing 346saving 333

Selection table 324Selection texts 329, 330

activating 332creating 330editing 331using 329

Selections 316, 323SELECTION-SCREEN 348

BEGIN OF LINE 348COMMENT 348END OF BLOCK 350END OF LINE 348FOR FIELD 349POSITION 349TITLE 351WITH FRAME 351

SELECT-OPTIONS 324, 325, 329Semantic properties 177Separator string 130SEPERATED BY 129Session 84SET PARAMETER 466SET PARAMETER ID 466Settings, technical 62Shared lock 236SHIFT 125

152.book Seite 500 Donnerstag, 11. Oktober 2007 7:18 19

Page 52: Discover Abap From Sap Press

501

Index

Shifting field contents 126Short description 52Short documentation 89SIGN 324Single quotation marks 90Single values 325Size category 63SKIP 87, 292Slash 86SORT 396, 415

BY 396Sort sequence 397SORTED TABLE 379Sorted table 374, 393, 395Sorting

binary 397criteria 397language-specific 397

Source codeediting 78, 88modularization 430switching 75writing 88

Source field 111, 129SPACE 136SPLIT 130, 138

AT 130Standard key 373Standard selection screen 312Standard table 181, 188, 373, 378,

393enhancing 180

STANDARD TABLE OF 378Start position 131START-OF-SELECTION 32, 314, 365,

435Statement block 267, 270, 348

terminating 277Statement blocks 262Statements 81Static name assignment 242, 243Step into 144, 412, 425Stop sign 411Stopwatch 276String 199

String operation 124, 132, 209, 222, 223

String, data type 488Structure 85, 182, 371

components 182end 262, 313include 385maintenance screen 186start 262

SUBMIT 447, 449, 466AND RETURN 449VIA SELECTION-SCREEN 447WITH 447

Subprogram 430, 434, 438call 435, 444external 444fields 438internal 444

Subroutine 435Substring 131Substructures 183SUBTRACT 110Subtraction 108Suffix 457SY-DATUM 200SY-INDEX 276, 280Syntax 374

check 76, 434error 76

Systemclient 50date 200table 147, 344

SY-SUBRC 147, 238, 239, 271, 456SY-TABIX 395

T

t, data type 200T100 343, 364Tab, fields 182TABLE 400Table 77, 377

activating 63area 85, 89body 371, 372, 380, 390, 391

152.book Seite 501 Donnerstag, 11. Oktober 2007 7:18 19

Page 53: Discover Abap From Sap Press

502

Index

Table (cont.)checking 62completion 61content, displaying 66content, modify 237conversion 193copying 161declaring 89definition 374deleting 194, 196entries 164entry 371error message 170field, deleting 192header 372index 395internal 370maintaining 46, 165maintenance dialog 64mode 148modify 159physical conversion 190row 164saving 47status 163T100 364TCURC 172temporary 370transparent 45type 377, 378, 379, 386without header line 380

Table processing 374multidimensional 371n dimensional 372

Table structure 92physical 188

Table work area 85buffer 239delete 240

TABLES 85, 239, 441, 444Tablespace 63

check 149Target field 111, 129Target table 162TCURC 172, 175

table 172

Technical settings 62Temporary data 324Temporary tables 370Termination condition 274, 281, 302Termination statements 278

effects 279Test data records

enter 165Test mode 76Test system 24, 25Text element 222, 329

editing dialog 342Text fields, numeric 123Text objects, completing 341Text pool 329

activating 343Text symbol number 342Text symbols 330, 341, 348

editing 342Time fields 200

defining 200filling 201

TIMES 274TITLE 351Toolbars 75Totals

calculating 291outputting 291

Totals fields, initializing 292Transaction code 38, 234Transaction SE91 344Transaction, runtime 466TRANSLATE 321Translation 342Transparency 32Transparent tables 45Trick 35 205, 206Troubleshooting 140TYPE 104Type conversion 137, 199

automatic 282Type declaration 85Type definition 378, 379, 389TYPES 378

152.book Seite 502 Donnerstag, 11. Oktober 2007 7:18 19

Page 54: Discover Abap From Sap Press

503

Index

U

ULINE 87UNDER 119Underline 92Unicode check 72Unit of currency 255UNIT, data type 169, 215UPDATE 237, 241, 242Upgrade 180Upper and lower case 317, 446Uppercase and lowercase letters 123Uppercase and lowercase spelling 391User master record 233USING 438, 444

V

Validation 168, 179VALUE 106, 123, 200, 411VALUE CHECK 320Value range 56Value table 172, 174, 175Values

negative 106transfer 447, 448valid 171

Variable 103, 467Variant 72

creating 334editing 337properties 337protecting 337, 339start using 72

Variants 334VIA SELECTION-SCREEN 447, 448

W

WAERS, domain 172, 174Watchpoints 140, 150

create 151mode 150save 155

WHEN OTHERS 271WHERE 245, 273, 396, 410, 424Where-used list 76, 194, 195WHILE 275WHILE loop 275Wildcard 451WITH 347, 447WITH FRAME 351WITH HEADER LINE 379, 423WITH KEY 394, 399WITH UNIQUE KEY 379Work area 240, 242, 371, 372, 376,

377, 382, 391, 398, 400, 423define 379defining 240initialize 248, 402

Work process 235Working memory areas 449, 465WRITE 82, 86, 87, 118

UNDER 119

X

X buffer 78

Y

Y buffer 78

Z

Z buffer 78ZIP codes 106

152.book Seite 503 Donnerstag, 11. Oktober 2007 7:18 19