SAP Online Help | SAP Jobs | SAP Forum | SAP Training | SAP Books | SAP Software | SAP News | Contact Us

SAP Training

ABAP/4 Programming Tutorial

November 1st, 2005

Startup
Log onto SAP. Type "SE38" into the command field as Figure 1.1 shows,
and press . You are "going into SE38", the ABAP editor.

Figure 1.1 The SAP R/3 main screen

Type in the new program name "ZHELLO1", select *Attributes then
click on [Create as Figure 1.2 illustrates. If that name is already taken, choose
another name.

Note The opening square brace on [Create is an example
of the York-Mills Notation, which we will use throughout the book to describe
your navigation through menus, buttons and fields. See Appendix F for a complete
description. In this case, the square brace is a prefix that indicates the "Create"
is a button. Similarly, "{" indicates a menu item, "*" a
radiobutton and "<" a field entry. We’ll use italics for the labels
on those navigation objects.

Figure 1.2 ABAP/4 Program Development: Initial Screen

Fill in a title like "Test program for ABAP programming book". Enter
"1" in Type and "S" in Application, select Upper/lower case
as you can see in Figure 1.3 and click on "Save" (the file-folder
icon on the task bar). Select [Local private object as shown in Figure 1.4,
then click on [Source code.

Note We’ll explain in later chapters all the things we’re
racing through so quickly here such as values for "Type" and "Application".
In this chapter we’re going to just blast ahead to demonstrate some of what
you can do in ABAP/4, and how to do it.

Figure 1.3 ABAP/4: Program ZHELLO1 Attributes

Figure 1.4 Selecting a development class

Your first program

You’re now in the editor; it opens with the statement
REPORT ZHELLO1 .

The ABAP editor in Release 3.0 has three ways of presenting the code; you
select one in the menu item {Settings {Editor mode. Release 2.2 offers only
the "Command Mode" presentation, so we’ll assume you’re using that
mode.

Type in the second line of the program:

WRITE ‘Hello World’.

Note We’ll create several versions of this program as we work through
the chapter. You can view each intact program when it appears in the text

"

REPORT ZHELLO1 .
WRITE ‘Hello World’.

"

Notice the single-quote (’) delimiters and the terminating period. Save
your work by clicking on the file-folder icon on the task bar, and select the
menu items {Program {Execute, or click on [Execute, or in Release 3.0 press
F8. Behold! You have followed time-honored tradition with your first programming
task, as Figure 1.5 shows.

Figure 1.5 Output of first program

This output is called a report (and often a list) in SAP. When you’ve tired
of admiring your success, return to the source code by pressing F3 or by clicking
on "Back" (the left-pointing green arrow icon on the task bar).

A simple two-level list

One of the unusual and powerful capabilities in SAP is to "drill-down"
through data. We’ll gradually build this example to illustrate how you can write
programs to drill down, and in the process learn some of the nature and capability
of ABAP/4. Add two more lines to your program so it reads like ZHELLO2:

Save and execute it again, and it looks the same. However, if you place the
cursor on "Hello World" (or almost anywhere else on the report) and
double-click or press F2, you’ll see the next level of the report as shown in
Figure 1.6:

Figure 1.6 List of Continents

From here you can march back up the report levels with "Back" (the
left-pointing green arrow icon) or you can Exit all the way back to the source
code by pressing Shift-F3 or clicking on the up-pointing yellow arrow.

While you’re in the list of continents, double-click on one of them. It’ll
look as if nothing happened but you must go Back twice to return to the "Hello
World" level. The continents have been listed twice, and the two lists
of continents have the same contents but they are in distinct levels of the
report. R/3 will allow you to go as many as nine levels deep.

AT LINE-SELECTION is an event in ABAP/4 that’s triggered when you "select"
(double-click or F2) a line in the current report. The code block following
the event statement is executed whenever the event is triggered. If the event’s
code block writes output, then it will force another list level. ABAP/4 recognizes
several events; a few of which we’ll use in this chapter.

Notice the colon (:) on the second WRITE. This allows you to follow the keyword
with any number of comma-separated parameters; each parameter will be processed
by the keyword independently. In this case, the statement acts as three separate
WRITE statements to print out the three different strings. The forward slash
forces a newline, and the number 12 offsets the string to start in the 12th
column.

Adding variables

User-variables must be declared and typed in ABAP/4. In addition to user variables,
R/3 provides quite a few system variables that contain the state of the program
and the report. Rewrite your program to read like ZHELLO3:

Save and execute this version
of your program and watch the list level increment as you "Select",
and decrement as you go "Back". March down to list level nine and
see that indeed, you may not go any deeper. Remember that at any level you can
return immediately to the source code with "Exit" (Shift-F3 or the
Yellow arrow). "Exit" is a tricky command however; sometimes it’ll
take you all the way back to the SAP main screen. You have a new way to climb
back out by selecting (double-clicking) on the line that reads "Return".
Figure 1.7 shows the list of continents selected while you’re already in the
ninth level.

Figure 1.7 Lists are limited to nine levels

The DATA statement declares variables and establishes their types. The default
type is C (Character), so it is optional for string variables. The variable’s
length is specified in the parentheses immediately following the variable name.
You can optionally assign an initial value to the variable at declaration.

SY-xxxxx is the naming convention for system variables; SY-LSIND contains
the current list index (level); we added it so you can see where you are. SY-LISEL
contains the list selection (the contents of the line you selected), so the
program can test where it is. SET USER-COMMAND simulates in code a user action,
in this case the "Back"(F3 or green-arrow) command. SKIP, of course,
skips a line on the screen.

Note The system variables are often mnemonic. SY-LISEL is mnemonic for
LIne SELection. SY-SUBRC for SUBroutine Return Code. Most of these mnemonics
are in English and contrast with the mnemonics for data fields that are mostly
in German.

Notice that every command is terminated by a period (even ELSE!), that a command
can span multiple lines (DATA and the second WRITE), and that a line can contain
more than one command (SKIP…). ABAP/4 is case-insensitive except in some string
comparisons, so keywords can be upper, lower or proper (mixed) case as you choose.
We like UPPER keywords, lower variable and table names, and Proper Subroutine
and Function Module names. White space (spaces, tabs, newlines) count for very
little in ABAP/4. We like to indent structured commands and leave blank lines
to make code easier to read. You can insert comment lines by placing an asterisk
(*) in the first column, and in-line comments with the double-quote (");
comments are terminated by a newline.

Note The only virtue that we know of for using the asterisk is that the
system editors highlight asterisk-indicated comment lines in red. You can use
the double quote as your sole comment indicator, thereby simplifying your life.

Using internal tables

One data structure you can declare is the internal table (itab) which exists
only while this program runs. Once again, import or rewrite your program to
read like ZHELLO4:

Save and execute it again, and now you have a third
defined list level: some of the nations in the selected continent as you see
in Figure 1.8. The content of the third level depends on what you selected at
the second level. Neat! Also, the program no longer continues to deeper levels;
it stops where it’s "supposed to".

Figure 1.8 Output showing list of countries

The BEGIN OF… END OF… construction creates a "structure" - a
complex data type that may contain several fields. Adding the OCCURS… option
expands that structure into an internal table. The OCCURS value should be somewhat
near the number of records you expect, but the program will work fine with zero
or a very large number; a larger or smaller number of records affects processing
speed and memory utilization, but will work regardless. You refer to fields
in a table using the format tablename-fieldname.

Note The hyphen is commonly used to qualify field names to tables, similar
to the period in many other languages. It is a legal character in field names,
but we like to avoid them so that any hyphenated string obviously refers to
a table or structure field.

The BEGIN OF…OCCURS…END OF… commands not only create itabs, but also create
separate "header lines" or "work areas" that have the same
structure as the itab and HAVE THE SAME NAME! Many commands, such as the assignments,
actually affect only the header line. The information doesn’t get into the itab
until you APPEND the header line to the itab. It’ll take you a while to get
used to this: when you see a table name, it may refer to the table or to its
header line.

LOOP AT itabname loops through the named itab from the first record to the
last, executing for each record the commands between the LOOP and ENDLOOP statements.
At each iteration, the LOOP command populates the header line with the values
in that itab record, so the WRITE statements are actually writing the contents
of the header line, not the itab entry.

The CASE statement compares the variable in the first line to the values (variable
or literal) in the following WHEN statements. It executes the commands starting
at the first matching WHEN and stopping at the next WHEN or the ENDCASE. Finally,
it will execute the commands following WHEN OTHERS if no other WHEN matches.

FORM subroutines

As the program gets longer and does more things, it’s harder to follow. Sometimes
we need to have the program do the same thing in several places. We make the
program flow easier to follow and eliminate duplicate code by moving blocks
into subroutines which the program calls as needed. One type of subroutine in
ABAP/4 is the FORM, which is called with the PERFORM command. Import or rewrite
your program to read like ZHELLO5:

Save and execute it yet again, and you see that we
have a fourth level which shows the capital city of the country you’ve selected,
shown in Figure 1.9. The "Return" button is now a little more prominent
and has a permanent location on the screen. Other than that, the output doesn’t
look any different. The code has changed a lot though.

Figure 1.9 Output showing selected Capital city

We’ve added the event START-OF-SELECTION which is triggered after the program
is initialized, so it contains essentially the "main program". The
code block for any event is terminated by the next event statement (in this
case, the AT LINE-SELECTION statement), by the first FORM definition, or by
the end of the program. In this version, the main program consists of calling
the FORM (subroutine) "build_loc", then calling "level0".
It’s easier to follow when logical blocks are defined elsewhere, named sensibly,
and simply called in order. Since we need the return button in several places,
it’s a natural for a subroutine.

Note ABAP/4 event blocks may appear in any order within a program. An
event block is terminated by the start of the next event block, the first FORM
definition or the end of the program. However, it is good programming practice
to standardize on an ordering. We follow the ordering shown in Appendix E.

Since we’ve seen enough of the list levels, we removed them from the screens.

The new "Return" function is truly a button now, not just a line
in the report. The command GET CURSOR FIELD returns the name of the field you
selected. We wanted a big button, and the ability to select anywhere on it,
so we used one variable to paint its top and bottom lines and a second variable
to paint its label and ends; the variables are called ret_button1 and ret_button2.
The comparison operator CS returns TRUE if cfield ContainsString ‘ret_button’,
so the IF statement is satisfied if either variable is selected.

The CASE statement is easier to read when each branch simply calls a subroutine
rather than containing all the code. We’ve removed the WHEN OTHERS option because
we don’t want anything to happen if the user double-clicks in level 4 or below.
The "Return" button or "Back" are the only ways out of that
level.

The FORM definition for build_loc illustrates again the distinction between
an itab and its header line. The subfields in the header line are independent,
so the value of "continent" remains the same until you assign another
string to it. Again, you are assigning values to the header line; only with
APPEND do they appear in the itab.

Now that we have one flat table, we must write list level 1 in a new way.
We don’t have a simple table of continents, and we don’t want "North America"
to appear three times in the list. AT NEW fieldname is a conditional statement
that’s true every time the value of fieldname changes, as well as in the first
record if it differs from the header line. We CLEAR the header line so we know
it will not be the same as record one at the start, then LOOP. Note This technique
works only when the table is sorted by continent. Because we built the table
this way, though, we know that it will work here. If the internal table is built
from a non-sorted source, it must be sorted before using LOOP AT and AT NEW
in this way.

To write list level 2 from our single flat table, we need to select those records
whose continents match the one you chose in level 1. The WHERE option (optional
command clauses are called "additions" in SAP-talk) will limit the
execution of the code block to those records that match the WHERE condition,
in this case those records for which the value of loc-continent equals the contents
of "sel_cont". We assign to sel_cont the value of SY-LISEL (the selected
line, remember), offset by 11 characters. In other words, sel_cont equals the
selected line, starting at the 12th character; since we wrote the continent
to the screen starting in column 12, sel_cont now contains the continent without
any leading spaces.

In addition to writing names of countries in the selected continent, we’re
also using HIDE to store their capital city names. Hidden fields aren’t visible,
but they are associated with the current line. When a line is selected the hidden
field values are assigned to their header line fields, so we can use that information
for later displays or tests.

List level 3 differs from the others; it writes a single text statement based
on your earlier choices. We must assemble the string to write because R/3 writes
the full declared width of the text field, regardless of the length of its contents,
and we want a nice-looking sentence. We must concatenate some literal strings
and some variables, most separated by spaces, and one (the terminating period)
with no leading space. Release 3.0 has a CONCATENATE command that can do it
all, but Release 2.2 does not, so we’ll do this the old way.

First we stick a period on the end of the capital city name using the function
STRING_CONCATENATE. A function is a library subroutine accessible from any program.
Our program "exports" parameters to the function and "imports"
return values from it; the function also returns the listed error codes if appropriate
in the system variable SY-SUBRC (SUBroutine Return Code). Then we start building
our string with the start of the sentence "The capital of ". We assign
to the string, starting at offset 18, the contents of the selected line, starting
at its offset 14. Then we add " is " at offset 38 and the capital
name-plus-period at offset 42. Since we don’t know how long the country or capital
names are, we assemble them with lots of room, then CONDENSE the entire string;
that command shifts all the substrings leftwards until they are each separated
by one space. Now we can write it out.

Tuning up the report

Now that we’re approaching a useful report, let’s add some color and clean
up some loose ends. We will:

  • Use cfield to require selecting the "Hello World" string itself
    to go to the second level.
  • Reset cfield and the loc header line after we create each screen so old
    values can’t confuse us.
  • Write headers on each list, and paint the "Return" button as
    part of the page setup.
  • HIDE the continents in the level 1 list, and test for them in level 2.
    That way you write the next level only when you select a valid line on the
    screen.
  • HIDE the nation’s name in level 2 so we don’t have to extract it from a
    substring of SY-LISEL in level 3.
  • Only write out level 3 if we selected a valid screen line in level 2.
  • Write the "Return" button and "The capital of…" in
    colors.

Here’s ZHELLO6:

Save and execute this version and select all over
the screens; it now responds only when it makes sense. The colored "Return"
button is more obvious, and the colored level-3 statement clearly differs from
the other lists.
The TOP-OF-PAGE events are triggered whenever R/3 automatically generates a
new page. The first one only works on level 0 screens, and the DURING LINE-SELECTION
version works on all the other levels.

We discussed the return_button earlier, but we want to point out one more
thing in its FORM definition. List level zero, the first output screen, includes
a couple of title lines that don’t show up on lower (or is that higher?) levels.
So we restore the cursor to line five after painting the button if we’re in
level zero, and to line three in any other level. Subsequent writing will start
on the line we move it to.

We like to use "IF cfield CS ‘greeting’" instead of "IF cfield
= ‘greeting’" because R/3 returns the field name capitalized, and we like
to keep our lower-case convention for the variable name. The CS operator is
case-insensitive, whereas the equality operator is case-sensitive.

The condition IS INITIAL is true if the variable is reset (in its initial
state). The initial state for character type variables is a space; that is,
a reset character variable contains one space.

Valid color numbers and the colors they display in a typical SAP installation
are shown in Table 1-1.

Table 1-1 Valid Color Numbers

Gray-blue
Bright gray
Yellow (Yellow)
Blue-green
Green
Red
Violet

User’s initial choices

We can offer the user choices that affect how the program runs; inviting (or
requiring) him or her to enter a single value or a range or list of values.
We can also send out error messages if the user fails to properly complete the
choices.
Reports in R/3 consist of quite a bit more than their code. So far the examples
have been limited to code; this time we’ll use some of the other capabilities.
And we’ll look at our first database table.

The final version of our sample program is ZHELLO7:

Before you execute it, you must provide the content of TEXT-001 that we specified
in the SELECTION-SCREEN COMMENT line near the beginning of the program. Double-click
on the "TEXT-001", select [Yes to create it as shown in Figure 1.10,
then type in the label "Color for Capital city display (1-7)" as shown
in Figure 1.11. Save it and go back (green arrow) to the source code. This text
element is the first example of a program element that is somewhere other than
in the code. It’s stored in a table associated with the program. You could also
have gotten to the table using the path {Goto {Text elements *Numbered texts
[Edit.

Figure 1.10 Dialog box to create a Text element

Figure 1.11 Maintaining Text elements

SAP stores most system data, owner’s "Master" (lookup) data and
business transaction data in database tables. The TABLES statement hooks in
the named tables, making them available to the program, and creates a header
line for each. In this example, T005T is SAP’s table of country codes, their
names and what we call their citizens. Double-click on the "T005T’ in the
TABLES statement. You’ll see a brief description of the table and a list of
its fields with their descriptions as shown in Figure 1.12. This illustrates
the amazingly integrated nature of R/3: everything seems to connect to everything
else, and you can drill down to get there from almost anywhere. "Green
arrow" back to the source code.

Figure 1.12 Table and Fields of T005T

Save and execute this last version and see the selection screen shown in Figure
1.13. Click on [Execute or press F8. R/3 returns the cursor to the empty Color
parameter field and sends you a message that you must enter a valid number.
Type in a number between 1 and 7 then [Execute again. This time it places the
cursor in the first "s_land1" field (whatever that is) and insists
you enter a country code. Type in "a*" in the first field and [Execute
again. Now you’re in familiar territory. Try the "Country list" choice
in level 1 and see what happens. You see every country in the SAP database whose
code matches your "s_land1" choices; and you can drill down to see
what that country’s residents are called.

Figure 1.13 Initial selection screen

We placed the range selection option on the entry screen with the SELECT-OPTIONS
command. It expects you to enter a single value or a wildcard pattern in the
"From" field, or the beginning and ending values of one or more ranges
in the "From" and "To" fields. You can look up possible
values for those fields: press F4 or click on the down-pointing arrow at the
right of the field when the cursor is in the field. Choose [No, you don’t want
more selection criteria as shown in Figure 1.14, to see the list shown in Figure
1.15. In this case, the values are country codes found in the T005T table.

Figure 1.14 "Restrict values ranges" dialog box

Figure 1.15 "Possible values" pull-down list

If you click on the right-pointing arrow to the right of the "To"
field, a new screen appears in which you can enter as many ranges as you need,
as shown in Figure 1.16.

Figure 1.16 Multiple-ranges selection screen

The "s_land1" label on the selection screen doesn’t mean anything
to the user (and is pretty ugly), so let’s change it. That label is another
text element. You reach that one by {Goto {Text elements *Selection texts [Edit
to see the table shown in Figure 1.17. In the "s_land1" record, you
can change the second field from "?…(S_LAND1)" to whatever you want
that will fit. In our example, we’ll use " Range of Countries." Tinker
with the leading spaces to align it with the "Color for Capital city display
(1-7)" label as shown in Figure 1.18.

Figure 1.17 Maintaining Selection texts

Figure 1.18 Improved Selection screen

The various SELECTION-SCREEN commands place text on the screen. User choices
are invoked by the PARAMETERS (single-value) and SELECT-OPTIONS (ranges) commands.
The PARAMETERS label would have been determined by the selection text elements
like the SELECT-OPTIONS was if we hadn’t painted a COMMENT on the same screen
line.

We’ve added two new events to filter the screen entries. AT SELECTION-SCREEN
ON color and AT SELECTION-SCREEN ON s_land1 are triggered when you [Execute
out of the selection screen. In these cases, we just test for valid entries.
A type "E" (error) message tells R/3 to return to the selection screen
with the cursor in the subject field, and to display the message (number 208
in this case) from the message set 00 (notice the MESSAGE-ID 00 option in the
REPORT ZHELLO7 line). Double-click on the "00" in the top line and
select [Messages to see all the messages available in that set as shown in Figure
1.19. Message 208 is simply "&" which R/3 expands into the contents
of the WITH option. If neither IF is satisfied, then the selection screen is
accepted and the program proceeds.

Figure 1.19 List of messages in set 00

We extract selected records from database tables using the SQL-like SELECT
command. The selection conditions we chose are (1) the language (Spras from
the German Sprache) is the same as the user’s login language, and (2) the country
code (Land1; Land is German for country, nation or state) is in the list you
selected at the selection screen. All the commands between SELECT and ENDSELECT
will be processed for each selected record.

And finally, the string ‘We don'’t know about the people from ‘ shows how
to include an apostrophe in a string, and USING string2 shows how to pass parameters
to the color_write subroutine.

Summary

We have developed an example of interactive list processing in ABAP/4 from
the classic, very simple "Hello World" to a rather complete multi-level
illustration of the "drill-down" capability. We showed the use of
several of the commands available in ABAP/4, and glimpsed a couple areas beyond
the code that contain program elements.
The remainder of this book will expand on every command shown and every point
illustrated in this example. We’ll explain a lot of things that we touched lightly
or just leaped over in this chapter, and we’ll provide examples of the other
two main uses of ABAP/4 in an R/3 installation: creating batch data communications
(BDC’s), and creating reports.

Related Links: Glossary | Phase 3: Realization |

No Comments »

No comments yet.

Leave a comment

You must be logged in to post a comment.

SAP News

SAP and CSC Form Alliance to Offer Banks Pricing Optimization Technology—LAS VEGAS - November 14, 2007 - Continuing its focus on providing banks the flexibility they need to integrate, migrate and update application functionality based on an integrated platform, SAP AG (NYSE: SAP) today announced an alliance with Computer Sciences Corporation (NYSE: CSC). The alliance will address the growing need for banks to differentiate themselves [...]

SAP BW Reporting Analyst—This role is for a UK analyst resource with SAP BW reporting skills for a large energy company. Need significant experience with SAP BW reports as well as experience with SAP BW reports deployed via the SAP Enterprise Portal or SAP GUI. General understanding of BW and Portal Authorisations. Familiarity Visual Composer is a plus [...]

test2—test2

Indian unit fastest growing arm of SAP—Business software provider SAP today announced that SAP India has emerged as the fastest growing subsidiary for the company worldwide following a recording-breaking performance during the 2007 financial year. http://www.business-standard.com/common/news_article.php?leftnm=8&subLeft=1&chklogin=N&autono=312878&tab=r

SAP Announces Management Transition at TomorrowNow—Newtown Square, PA - November 19, 2007 - SAP (NYSE: SAP) today announced that several senior managers of TomorrowNow, including the company’s CEO, have chosen to resign. In addition, SAP said it is considering several options for the future of the TomorrowNow business, including possible sale. http://www.sap.com/about/press/press.epx?pressid=8597


SAP Books

ABAP Objects: Introduction to Programming SAP Applications—ABAP Objects: Introduction to Programming SAP Applications

Web Programming with the SAP Web Application Server—by Frederic Heinemann, Christian Rau "This book is intended primarily for developers who want to create and implement Web-based applications in the R/3 environment..."

ABAP Objects: Introduction to Programming SAP Applications—ABAP Objects: Introduction to Programming SAP Applications


SAP Software

Creating your own programs—Please note: The name has to start with Y or Z.

Developing BSP applications on Web AS 6.10—The start page of the first CD contains a link, “Starting Web AS 6.10 Demo - Getting started with a simple BSP (Business Server Pages) demo”, which describes the initial steps.

SAP Memory Analyzer—The Memory Analyzer was developed to analyze productive heap dumps with hundreds of millions of objects. Once the heap dump is parsed, you can re-open it instantly, immediately get the retained size of single objects and quickly approximate the retained size of a set of objects. The Analyzer is (relatively) low on resource consumption, so you can analyze multi-GB heap dumps on 32 bit boxes.

Creating a new development class—Transaction SE80 now has an “Edit Object” button. You can use it to create a new development class. The name must start with Y or Z.

Runtime error under DOKTL—This error occurs only when you run the system on a PC without a network connection. To solve this problem, install the MS Loopback Adapter as described on the first CD.


SAP Training

Basis interview questions—ST02 / ST03 In general via table buffers, you could go into the whole Work Process, roll in, roll out, heap (private) memory, etc. however just as a Unix or DBA admin would know, is you look this up when needed for the exact specifics.

Glossary—Glossary

SAP Basis Certification Sample Questions—SAP Basis Certification Sample Questions

Phase 1: Project Preparation—In this phase of the ASAP Roadmap, decision-makers define clear project objectives and an efficient decision-making process. A project charter is issued, an implementation strategy is outlined, and the project team as well as its working environment are established.

Phase 2: Business Blueprint—In this phase you document and define the scope of your R/3 implementation and create the Business Blueprint. The Business Blueprint is a detailed documentation of your company's requirements in Winword format. Application consultants and the Business Process Teams achieve a common understanding of how the enterprise intends to run its business within the R/3 System, by carrying out requirements-gathering workshops.


SAP Jobs


SAP Online | Jobs | Forum | Training | Books | Software | News | Contact Us >> ©SAPTechies.com