Vous êtes sur la page 1sur 56

ABAP BASICS

ABAP TRAINING MATERIAL


( BASICS )

1
ABAP BASICS

TABLE OF CONTENTS

SOME FACTS ABOUT SAP 4

WORKING WITH R/3 SYSTEM 6

SAP R/3 logon Screen....................................................................6

Logging Off..................................................................................8

Using Transaction Code.................................................................8

Getting help in the R/3 system.....................................................10

Working with R/3 user sessions...................................................11

R/3 ARCHITECTURE 11

Client / Server architecture..........................................................12

Three tier architecture of R/3.......................................................13

ABAP/4 DEVELOPMENT WORKBENCH 14

DATA DICTIONARY 16

About Data Dictionary.................................................................16

Advantages................................................................................16

Tables in ABAP/4 dictionary.........................................................19

Creation of table.........................................................................20

Creating Domain.........................................................................20

Creating Data Element................................................................20

GENERAL INTRODUCTION TO ABAP/4 21

Characteristics of the ABAP/4 programming languages.................23

REPORTS....................................................................................23

DIALOG PROGRAMS.....................................................................24

2
ABAP BASICS

DATA TYPES AND DATA OBJECTS 26

Data Types.................................................................................26

Data Objects............................................................................... 27

Kinds of Data Objects..................................................................27

Parameters................................................................................. 29

WRITE STATEMENT 31

Formatting output......................................................................32

Formatting options for all data types...........................................33

Formatting options for numeric fields..........................................33

BRANCHES 35

Branching with IF statement........................................................35

Branching with CASE statement...................................................36

LOOPING 37

Looping with DO statement.........................................................37

Looping with WHILE Statement....................................................37

TRANSLATE command.................................................................40

Insert statement.........................................................................46

Update statement.......................................................................47

Delete statement........................................................................47

3
ABAP BASICS

Some Facts about SAP


After the Internet, SAP R/3 is one of the hottest topics in the computer industry and the company
that developed it. It is targeted to most industries, manufacturing, retail, oil & gas,
pharmaceutical, banking, insurance, telecommunication, Transport, chemical and so on. All
major hardware Vendors were fully engaged to partner with SAP: AT&T, BULL, Compaq, IBM,
Sun have supported and certified R/3 platform.

SAP has list of major consultants all over the world like Anderson Consulting, Price Waterhouse
– Cooper & Lybrand, Ernst & Young, KPMG and many more.

The company behind R/3 is SAP AG, founded by four former IBM employees in 1972. The
company’s headquarters are in Walldorf, a small German town. The company name, SAP stands
for SYSTEMS, APPLICATIONS and PRODUCTS in data processing. In 1992 R/3 was
introduced and in 1995 SAP AG was ranked fifth among independent software vendors. One of
the reasons for SAP’s success is that since it is a standard package, it can be configured in
multiple areas and adapted to specific need of a company. Today, more than 21,600 customers
in over 120 countries run more than 69,700 installations of SAP® software. With subsidiaries in
more than 50 countries, the company is listed on several exchanges, including the Frankfurt
stock exchange and NYSE under the symbol “SAP”.

SAP has two main products in the business software market, Mainframe system R/2 and Client-
server R/3. Both are targeted to business application solutions. Here R indicates REAL TIME.

R/2 is SAP AG mainframe software that runs on IBM, Siemens and other compatible equipment.
This type of solution cannot be open, but with ALE technology, R/2 can be linked with R/3
system and share data. This system is mainly targeted at enterprises with data-intensive and
centralized industries.

R/3 is the product that has really placed SAP AG as the leader in the country. This complex
Client/server system is core of our course. The global acceptance of R/3 is not only because it
caters all complex needs of business but also this international acceptance is because of R/3’s
international applicability. For SAP this does not mean having software available in different
languages, but also covering currency, taxes, Legal practice concerning HR, Import/export
regulations. SAP also values its customers and it is shown by the comprehensive set of quality
services put by SAP to help customers during the process of implementing and supporting the
R/3 systems. These services include product information; training, installation and upgrade
service like:

4
ABAP BASICS

OSS: Online Service System is one of the primary sources of service and support provided by
SAP. With OSS, customers can search the SAP information database and find solutions for
errors and problems with R/3 systems. You can also submit your problems to SAP.

Consulting Service: with remote consulting service customer receives immediate and updated
technical support and answers to their questions.

Maintenance service: This is the basic and most common type of support for customers in
technical support and answers to their questions.

Information Service: These are the various information sources for receiving detailed
information about the R/3 system, marketing brochures, system documentation, training
information and many more things.

Preventive services: The primary one is the Early Watch Service, which ensures successful and
efficient installation of the R/3 system in all phases. This service makes regular/performance
checks and analyzes the system to identify potential problems, help system managers and SAP
administrators to tune the system. Soon after the Early Watch session, SAP sends the customer a
report with the result of the analysis and recommendations for avoiding potential problems such
as database becoming full.

So overall SAP R/3 is an open client/server software system, designed to manage business
information needs of an entire enterprise. The whole dataflow of SAP R/3 works in an
integrated way, which means the data needs to be entered just once and the system automatically
updates other logically related data.

5
ABAP BASICS

WORKING WITH R/3 system

The SAP R/3 presentation interface behaves very similarly to any other typical window
application and is also known as SAPGUI. The first screen that you come across in R/3 system
is SAP logon screen.

SAP R/3 logon Screen

This is the first screen that appears when you use SAP logon utility. It has four fields: the client,
the user, the password and the language.

Client: Here you enter the client number. The client is group of users who has similar rights. It
can be group of users in a business entity or a whole business entity or a whole company.
♦ User: The name of the SAP user identification. Users of the SAP system are client-specific,
which means that user belonging to one client is valid to only the particular client.
♦ Password: It is the password that has been assigned by the system administrator.
♦ Language: SAP R/3 system supports multinational language on the same system at the same
time, which is very useful for multinational companies with different branches in several
countries and possibly using different languages.

After entering all the fields press ENTER key and system will take you to MAIN MENU screen.

6
ABAP BASICS

User might get different screens when he logs on, depending upon default settings of the user
master record i.e., if user is DEVELOPER then the screen which he often works on is editor
screen and he can go directly to this screen, if system administrator sets this screen for the user.

Main features of any R/3 window are as follows:


♦ R/3 standard window elements behave exactly the same, as any other standard window
application would, like minimizing a screen, setting the active window etc.
♦ From TOP to BOTTOM, R/3 window can contain typical elements such as check boxes,
push buttons, input fields and following elements:
♦ Menu bar is the first element of the every R/3 window. It contains the menu item
corresponding to the particular R/3 application. The two menu options SYSTEM and HELP
are always present in every R/3 window. SYSTEM menu option contains all utilities and
functions, and is available to user at all the times. The HELP menu contains all the available
options for the different types and methods of obtaining online help in the system.
♦ Standard tool bar. The second R/3 window element is present in every R/3 window. It is
nothing but a collection of icons, which perform common functions like saving the object,
exit etc. The various icons on std. Tool bar are as follows (from left to right):
Enter Command Field Save Back
Exit Cancel Print Find
Find Next First Page Previous Page Next Page
Last Page Help

All icons in R/3 window application support FOCUS property. It means, if you place cursor
over an icon, the system will show the function of the icon.

♦ Application tool bar: The next part of the screen contains icons most commonly used in that
particular task or transaction.
♦ Status bar is the bottom line of the screen and usually shows errors or information messages
to the user. It also includes other information such as system id, session number, client,
server name and the response time.

In between application tool bar and status bar you have working area, which is different for
different screens.

7
ABAP BASICS

Logging Off

User can log off the R/3 system from any screen. There are three ways of logging off the R/3 system,
which are as follows:
♦ From the Menu bar choose SYSTEM → LOG OFF. In this case, you get the log off dialog
box, which informs the user that any data not saved will be lost if continuing with the log off
procedure.
♦ Use/NEX transaction code in the command field. This is dangerous, since it does not ask if
you want to save the data.
♦ Clicking on the EXIT button on the R/3 initial screen.

Using Transaction Code

The R/3 system provides an alternative and efficient way of selecting menu options for moving
around the tasks and functions of the SAP system by using transaction code directly in the
command field.

When moving with transaction, you can go to any part of the system by merely typing a
transaction code in the command field, provided you have authorization for that. That
transaction code is the four-character code associated with any task. By typing the transaction
code and pressing ENTER key, the system takes you directly to the initial screen for transaction.
Whenever any transaction code is entered in the command field, it gets stored in the buffer
memory. If you click on drop down arrow, system displays list of transaction code already
entered and you can select from this list or enter new one. There are almost (12094) twelve
thousand and ninety four transactions in SAP. For every task, transaction code is associated and
it can be found by

♦ SYSTEM → STATUS
Status window is popped up which contains the transaction code in the trans field.
♦ Through DYNAMIC MENU. It gives the list of tasks. If you click on the top line of the
application areas and pressing the search and search next button will give you the transaction
code. /N will take you to initial screen of R/3

8
ABAP BASICS

Important transaction codes, which you will be using often, are:

Editors
• SE37 Function Builder
• SE38 ABAP/4 Editor
• SE41 Menu Painter
• SE51 Screen Painter
• SE71 Form Painter

Dictionary
• SE11 Initial ABAP/4 dictionary maintain screen.

Browsers
• SE80 Object browser.
• SE16 Data browser.

Testing Tools
• SE30 Runtime Analysis
• ST05 SQL Trace

9
ABAP BASICS

Getting help in the R/3 system

R/3 includes many possibilities to get online help for almost every element of the system, users
can get help for entire application, for specific function, for definitions of various terms used in
SAP, i.e., Glossary, messages, screens, fields etc.

You obtain HELP by using any of the following options:

♦ Help function from the R/3 window, which is compulsory menu item of every R/3 window.
♦ ? Icon of standard tool bar.
♦ F1 function key.

The SAP system provides help on most fields that appear on the R/3 system. To get help on
particular field, position the cursor over it and press help button or F1 function key.

Another way in which R/3 system provides help is when system displays error messages in the
status bar. Double clicking on the status bar shows additional information about the message.

10
ABAP BASICS

Working with R/3 user sessions

A very important feature provided by SAP. In R/3 system you can work with more than one task
at any given point of time, by means of opening sessions. You can call sessions as independent
R/3 window where you can perform other tasks.

By default, a user can open SIX sessions simultaneously and can work or move around with all
sessions at the same time. Sessions can be closed at any time, without having to log off the
system.

User can create new sessions from anywhere as CREATE SESSION comes under SYSTEM
menu which is available in every R/3 window.

SYSTEM → CREATE SESSION Or /O in command field


This will open a new session or window and will place it in front of all other windows.

To move among sessions


♦ Just mouse click on any part of the R/3 window to make that session active.
♦ Combination of ALT + TAB key.

R/3 Architecture
The overall R/3 system includes the following components:
Business
Applications

Basis System
Or
Middle Layer

Operating Data Base Network


System

The UPPER layer, the functional layer contains the different business application. The
integration of all application depends upon basis system. Applications are developed in ABAP/4
Lang. (Advanced Business Application – the 4th generation language)

The R/3 basis software is the set of programs and tools, which interfaces with the operating,
system, the underlying database, protocols and the presentation interface. This layer enables all

11
ABAP BASICS

the application to work exactly the same way no matter what operating system or database, the
system is installed on. It is an independent layer and ensures the integration of all modules.
Besides all these specific jobs, BASIS system also contains following components and thus
provides more additional features.

♦ ABAP/4 development workbench, which in turn includes many features like repository, data
dictionary, workbench organizer, which will be discussed in later part of the topics.
♦ ABAP/4 language, system administrative tools, all these components are used to control,
tune the R/3 system.
♦ Spool system manages the formatting of data for printing and passing it to the host spool
system.
♦ For background execution. Mail system you can send and receive mail from the outside
world (Internet).
♦ Communication interface to external system from R/3 system: Manages communication at
the OS level (TCP/IP), at the database level & between applications too. (RFC, EDI, and
ALE)
♦ Database interface – This component supports different Relational databases from different
vendors. The main task of database interface is to convert the SQL request from the SAP
development environment to the database’s own SQL environment.
♦ Background processing with this facility you can submit your program
BASIS system contains the layered components that facilitate the development of client/server
architecture.

Client / Server architecture

Client/Server architecture is mainly a software concept that includes a set of service providers
and service requesters. The set of computers acts as service providers and is called as server.
The sets of software component, which act as service requester, are called as client.

In the client/server architecture, the database acts like a library clerk retrieving books from the
shelf. The user programs have to request database for the data instead of searching for the data
themselves. This way there is no risk of the users putting the data out of order. If the desired
data is in use, the database makes the user wait until it is free.

The major advantage of the client/server architecture is that the server is available for a number
of clients and there is distribution of work between the clients and the server. The user directs
the request to the client; the client in turn understands the user’s request and redirects the request
to the server. The server retrieves the data, gives it to client.

You can have client and server on the same machine or on different machines. Each client has a
corresponding process inside the server.

12
ABAP BASICS

One of the most used client/server configurations with the R/3 system is the 3 tiered architecture,
which separates a system’s computer into 3 functional groups:

Three tier architecture of R/3

Database Server
Application Server
Presentation Server

(Unlike normal Client/server architecture where you have only two layers i.e., client and server.)

Communication among the 3 tiers is accomplished by standard protocol services like TCP/IP or
CPIC (Common Programming Interface Communication).

Database
Server

Application Application Application


Server Server Server

Presentation Presentation Presentation Presentation Presentation Presentation


Server Server Server Server Server Server

In above case database server stores the data centrally. Basically contains database engine and
associated processes. The database layers contain the database system used by all servers.

Application server contains software components to run the program. It contains a SAP kernel,
which can run ABAP/4 program.

The presentation server is your client through which you send your request to application server.
It is also called as SAP graphical user interfaces known as SAPGUI and is available in windows
3.1, Windows NT, Windows 95, and Macintosh. They all look similar whatever underlying
system they are running on.

The SAPGUI includes all graphical capabilities of window interface with menu bars, tool bars,
focus property, and the entire mouse clicking operations.

13
ABAP BASICS

The R/3 system is open system in the sense that it can run on any operating system or any
database and any communication technology. It means that:
♦ R/3 system can run on any operating system platform such as UNIX, NT, 95, AS/400.
♦ It supports various RDBMS such as SQL server, Oracle, Informix, DB2.
♦ Standard GUIs supported by R/3 are Windows 95, NT, Windows 3.1, and Macintosh.
♦ SAP can use standard communication protocols TCP/IP, CPIC, OSF/DCE/DME for network.

ABAP/4 Development Workbench

The development environment of SAP R/3 system is fully integrated set of various development
tools, data dictionary, and programming language. Full integration of all components means that
changes in any part have a direct and immediate effect on all application using those
components.

The screen of ABAP/4 development workbench looks like

14
ABAP BASICS

Tools of ABAP/4 workbench

For programming:
♦ ABAP/4 dictionary Defining, maintaining and storing the data dictionary of the SAP R/3
system stores all the dictionary objects including tables relationship and Help information.
Transaction code for this is SE11.
♦ ABAP/4 editor Creating and maintaining the ABAP/4 program, editing function modules,
logical database, and screens. Transaction code is SE38.
♦ Function library Defining and maintaining the ABAP/4 function modules. Transaction code
is SE37.
♦ Screen painter Designing and maintaining the screens in transaction. Transaction Code is
SE51.
♦ Menu painter Designing and maintaining the means for graphical user interface. Transaction
code SE41.

For Navigating:
♦ Object browser Managing and organizing the development object in a hierarchical form.
Transaction code is SE80.
♦ ABAP/4 repository information Navigating and searching for the dictionary Objects,
development objects and relationship objects. Transaction code SE84.
♦ Data browser Navigating in the data tables of the database. Transaction code is SE 16.

For Debugging:
♦ SQL trace tracking the database calls from the system transaction and programs. Transaction
code is ST05.
♦ Debugger Stopping the program and analyzing the results of the execution of every program
statement.
♦ Runtime Analysis Analyzing the performance the system calls Transaction code is SE30

For Organizing:
♦ Workbench organizer controlling and keeping track of development work and team related
development projects and managing versions of development objects. Transaction code is
SE09.
♦ Transport system performing and managing the transport of development object across
different system. Transaction code is SE01

15
ABAP BASICS

Data Dictionary

The ABAP/4 dictionary is central workbench repository utility providing the data definition and
the information relationship that are later used in all the business application within R/3

The ABAP/4 dictionary can be seen as a logical representation or a superior layer over the
physical underlying database. This database must support the relational data model. This model
is strictly followed by data dictionary.

About Data Dictionary

A Data dictionary in computing terms is the source of information in which system data is
defined. The data dictionary is the centralized and structured source of information for
business applications. You can say that it is core of a well-structured development environment.

The elements that make up a dictionary are known as metadata. Metadata is the term for the
data whose function is to describe other data. Data in dictionary is not the actual data like
emp. name or emp. address but rather a type of data whose function is to define the properties of
the data such as type, length, and relationship.

Advantages
Advantage of using data dictionary is avoiding inconsistencies when defining data type that will
later be used in different applications. This avoids redundancies.

When a type is defined in the dictionary, it is available to any program in the application. A
change in the definition of a type of data in the dictionary automatically affects any other data or
program, which has this data.

Again, data dictionary is a fast and efficient way to answer questions such as which entries exist
in a table of the database, what the structure of table is.

16
ABAP BASICS

Activation of dictionary objects

For a dictionary object to be effective at runtime, that is, for a dictionary object to be available
for use within a program, transaction, and so on, it must be in active status. For objects to
become active, R/3 includes the ACTIVATION function.

When a table or aggregated object is activated, it is placed at the disposal of the system as a
runtime object in a way that makes it available quickly for the application program to access
relevant information of new activated objects.

When a dictionary object is modified, that means that the object previously existed and activated.
You need to reactivate the object after modification.

When mass activation is performed massively, it might take a quite a long time. Then it should
be in the background system. This type of activation is known as background activation.

The ABAP/4 Data dictionary is the central component of ABAP/4 repository. A Data dictionary
is centralized and structured source of information for business application. The ABAP/4
dictionary is the core of the R/3 development system. It is the source of every definition, within
R/3, from the very basic domain to the company data model. It is totally integrated with other
tools of the development environment like screen painter, menu painter, and editor.

Some of the main available functions in the ABAP/4 dictionary are as follows:

♦ Add, delete, modify, and manage the definition of the dictionary data.
♦ Preserve the data integrity.
♦ Be the central source of information e.g. from the dictionary you get the information about
the defined relationship between two tables or even the directory tells whether table is active
or empty.
♦ It also permits documentation of system data.

In the R/3 system instead of working with original objects, you work with internal representation
of objects. With this type of operation the system performance is enhanced and has the
advantage that the development tools, screen interpreters always access current data.

When any of the data dictionary objects are used in other parts of the development workbench
for example, in program, programmer only has to enter a table name or field name. The system
automatically knows all the properties and information of the field.

17
ABAP BASICS

To call ABAP/4 dictionary, from the main menu, Tools → ABAP/4 workbench → data
dictionary or enter transaction SE11.

Data dictionary objects:

♦ Table: is a 2D data matrix containing rows and columns. Rows contain data while column
indicates fields. Table can contain 0 or multiple rows.
♦ Structure: is a skeletal view of a table. It contains the definition of columns and don’t have
any contents. Structure is generally a template based on which a table is created. The basic
difference between structure and table is that the structure does not exist at the underlying
database system level. Structure exists as definition in the dictionary.
♦ Views: A view is an imaginary table. It contains data, which is really stored in other tables.
The contents for the view are dynamically generated when called from program.
♦ Data element: is definition of the properties and type for a table field. It is an intermediate
object between the object type domain and the table field. A field in R/3 system is always
associated with a data element, which at the same time is related to domain.

18
ABAP BASICS

♦ Domain: is formal definition of the data type from a technical point of view. It sets the
attributes such as data type, length, possible value range and so on.
♦ Lock objects: These types of objects are used for locking the access to database records in
table. This mechanism is used to enforce data integrity that is two users cannot update the
same data at the same time. With lock objects you can lock table-field or whole table.
♦ Search Help Objects: , which gives list of possible values for either primary keys or non-
primary keys.

Tables in ABAP/4 dictionary

Tables are the basic objects in R/3 application. There are almost 8000 tables in R/3 system.
Following types of tables are available

• Transparent tables
• Pool tables
• Cluster tables

From user point of view, all tables are used to store data whatever be the type of table. There is
no difference in the behavior or operation of these tables. All of them can be managed by using
standard OPEN SQL. However from an administrator point of view transparent table do exists
with the same structure both in the dictionary as well as in the database, exactly with the same
data and fields. While other two are not transparent in the sense that they are not manageable
directly using database system tools. You can access these tables in R/3 environment from the
ABAP/4 dictionary. You cannot use native SQL on these tables. Pool or cluster tables are
logical tables, which are arranged as records of transparent table.

A table is made up of rows and columns. When the table is created, its columns are named; data
type is supplied for each column. There can be only one data value in each column of each row
in a table. Record or as it is called in different RDBMS is nothing but group of fields. While a
column is a field of a table, a table is an indexed file. The main index is called as primary key,
which can be a single field or combination of keys or fields. A primary key can be defined as a
field, which indefinites a single unique record of the table. A table cannot have record with
duplicate primary key.

In any RDBMS, tables are related to each other. But to relate table to each other it is necessary
that one of the tables contain some information of other table. Mostly tables are related to each
other through primary keys. The primary key of one table, if it exists in other table then it is
called foreign key. This type of database management system means that there is some
redundancy of data. But using normalization procedures available can minimize it. One of the
most important functions of foreign key is to ensure data integrity. For example say you have

19
ABAP BASICS

EMP table, which has fields: emp. no., emp. name, dept. code, salary and you have DEPT tables,
which has dept. code and dept. desc. Then in DEPT table dept. is primary key while dept. code
in EMP table is foreign key. If you enter dept.code for particular employee in EMP table the
dept.code should exist in DEPT table. System will check the value for dept.code in DEPT table,
and if does not exist then will flash error. In this case DEPT is called check table while EMP is
foreign key table.

Creation of table

Steps to create a table


♦ Create domain
♦ Create data element
♦ Create actual table

Creating Domain

Domain as already explained defines the technical properties of a field such as type and value
range. A domain can be created from initial screen of data dictionary by clicking on create and
clicking domain Radiobutton. Parameters to be passed are:

Data type: Where you need to enter the data type available in SAP.
Field length: Field length is the number of valid position.
Value table: Name of a table to be entered. The fields referring to this domain may only assume
values contained in the value table.
Once the domain is created, save and activate it, so that it can be used for further objects (basic
rule of dictionary).

Creating Data Element

The second step of table creation is to create data element. It assigns a certain meaning to the
table field, which are defined using that data element. A Data element always needs to be defined
over a domain and field is always defined over a data element. This allows all fields with same
technical properties to use the same data element.

Parameters to be passed when creating a data element:


Short text: Mandatory field.
Domain: A mandatory field. If the domain does not exist, SAP can take you directly to
domain definition screen.

20
ABAP BASICS

Text element: You can enter description is short or long text for the field. This text is used when
entering data for these fields.
Save and activate.

Creation of actual table

Parameters to be passed for creation of table:

Short description: Mandatory field.


Delivery class: As per User Requirement
Table fields: Specify whether primary key. In this case it is mandatory to enter data
element.
Data class: Establishes the physical area of the database.
Size category: Allows you to specify estimated space requirement for the table.

Further down under buffering square box, the system allows specifying whether table is going to
be buffered. When a table is buffered, it is loaded into the table buffer from the application
server memory and it will remain there until you switch off or reboot system.

If the table is to be buffered, you need to specify the type of buffering. Full is for entire table
while partial is for only those records which are being accessed.

Once the table is created, it has to be generated or activated to be able to access by other objects
like programs.

General Introduction to ABAP/4

SAP originally developed the programming language ABAP/4 (Advanced Business Application
Programming) for internal use to provide best working conditions for developers. SAP
constantly improves the language to adapt to the increasing requirements of the business
applications. At present, ABAP/4 is the only tool for developing applications at SAP.

SAP customers use ABAP/4 for their own developments. The ABAP/4 Development
Workbench contains all tools you need to create and maintain ABAP/4 programs. ABAP/4
programs are not complied but generated. During generation, the system creates a so-called
runtime object from the source code and the program attributes. When you start the program, the
system executes the runtime object.

ABAP/4, a fourth generation language, contains all usual control structures and modularizing
concepts for structured programming. The three parts of the ABAP/4 language are:

21
ABAP BASICS

Structure and execution of ABAP/4 programs


Basic language elements
Programming reports
Programming dialogs

Structure and execution of ABAP/4 programs are essentially different from entirely sequential
programming languages such as FORTRAN, PASCAL, or C. ABAP/4 instead shares certain
similarities with modular, event-orient programming languages such as Visual Basic or JAVA.
The two most important statements concerning structure and execution are:

An ABAP/4 program has a modular structure.


For execution, you need a special runtime environment.
This means, that ABAP/4 source texts always consist of a collection of program modules (one
single module in the easiest case) or the sequential set of statements. The individual program
modules consist of sequential elements. The set of statements of a program module is also called
processing block.
The runtime environment is responsible for calling the individual program modules one after the
other. The runtime environment is the ABAP/4 processor, which can communicate with the list
processor or the dialog processor, depending on the program type.

Program flow within the individual processing blocks is sequential, as you know it from other
sequential programming languages (for example, FORTRAN, PASCAL and C). Within the
processing blocks, you can use the general control statements for the program flow, such as IF,
DOES, WHILE, ABAP/4 does not contain GOTO elements.

We mainly use programs that consist of a single processing block only and, therefore, behave
most likely like programs of other sequential programming languages. For programming
applications, the entirely sequential concept is not sufficient. SAP distinguishes between two
general types of application programs:

Reports: You use reports to read databases and represent the results in lists. Reports are
collections of processing blocks that the system calls depending on events.

Dialog programs: You can dialog programs to execute transactions, which usually read and
change databases. Dialog programs are collections of processing blocks (so-called module
pools) that are called by a screen flow logic. The third part of the User’s Guide describes dialog
programming in detail.

Reports can call dialog programs and vice versa.

22
ABAP BASICS

In its easiest version, an ABAP/4 program contains one single sequential piece of coding and,
thus, one single processing block.

Characteristics of the ABAP/4 programming languages


♦ Declarative elements for declaring data of different type and structures.
♦ Operational elements for manipulating data.
♦ Control elements to control processing flow.
♦ ABAP/4 is multi-lingual. Text elements such as titles, headings, and text body are stored
separately, independent of the program codes. Thus, you can change, translate, and maintain
text elements without having no adapt the coding.
♦ ABAP/4 supports business-related data types and operations. You can execute calculations
using special data and time fields. The system automatically executes all necessary type
conversions.
♦ ABAP/4 provides a number of functions for processing character strings.
♦ ABAP/4 allows you to define and call subroutines. You can even call subroutines of other
programs. There are different ways of how to pass parameters to and from the Subroutines.
♦ ABAP/4 contains a special type of subroutine, called function module. Function modules are
stored and maintained in a central library. They have clearly defined data interfaces to the
calling program. You can test function modules in a stand-alone mode independent of the
calling program.
♦ ABAP/4 contains an SQL subset called OPEN SQL. OPEN SQL allows you to read and
change database tables independent of the underlying database system.
♦ ABAP/4 allows you to define and process internal tables that exist only for the execution
period of the program. Internal tables efficiently support the usage of database tables and
allow you to implement complex data structures in a program.
♦ ABAP/4 allows you to store data not only in databases but also as sequential files on
application and presentation servers.

REPORTS

♦ Reports are ABAP/4 programs.


♦ You use reports to evaluation data from database tables. The results of such an evaluation
can be displayed on the screen or printed form.
♦ Reports are stand-alone programs.
♦ The user can execute reports directly via the program name, for example, by choosing
System ® Utilities ® Reporting.
♦ A report program contains a collection of processing blocks for different events that are
always triggered externally. In a report, you can react on events by programming the
corresponding processing blocks or ignore the events by not writing the corresponding
processing blocks. A report itself never creates events.

23
ABAP BASICS

♦ Reports can use logical databases or select statements defined by developer.


♦ For each application, SAP supplies logical databases. Or you can easily create logical
database yourself.
♦ Event control of a report corresponds to a certain scheme:
When a report is executed, the ABAP/4 processor creates together with the logical database
used (if any) a sequence of certain events for which you can program processing blocks. The
chronology of the events is (more or less)

Steps involved in creating a Report:


1. Processing the selection screen
After starting a report, the selection screen allows the user to enter limits or control
values for further report processing. The report can contain several processing blocks for
events during selection screen processing, for example, for checking the input values.
2. Reading the database
After selection screen processing come the events for reading the database. Either the
report reads data from relational databases it using the corresponding ABAP/4 statements
(open SQL) or leaves this task to a logical database. In the latter case, the logical database
creates a sequence of events to allow the report to copy the data.
3. Evaluating data and creating lists
During or after reading the database the report creates the output list. During list creation,
several events allow you to layout the output list (for example, layout the page header).
4. Outputting a list
The last part of the processing sequence controlled by the ABAP/4 processor is the list
output on the screen or printer. When displaying the list on the screen, user can trigger
other reports, that are interactive and are event driven. For example, by clicking the
mouse. By programming processing blocks for these events, you change a normal report
to a so-called Interactive report. If a report does not contain event keywords, the entire
coding of the report belongs to a single processing block, which is called by a standard
event. This standard event is triggered directly after processing the selection screen.

DIALOG PROGRAMS

♦ You use dialog programs to execute transactions. The users of dialog programs in dialog
sessions read and change database tables. Apart from the actual data processing (Open
SQL), update and enqueue concepts are of great importance when programming dialogs.
♦ Dialog programs are not stand- alone

24
ABAP BASICS

♦ To execute dialog programs, they must be linked to at least one screen that itself is linked to
a transaction code. The transaction code determines the initial screen with which the dialog
session starts.
♦ Dialog programs are controlled by screen flow logic
♦ The actual ABAP/4 dialog program is a so-called module pool. A module pool contains a
collection of dialog modules that are called by the screen flow logic.
♦ To each module pool, at least one, but usually several screens are allocated. Each screen has
flow logic. The flow logic consists of PBO (process Before output) and PAI (process After
Input) blocks. This flow logic does not use the ABAP/4 programming language and the
ABAP/4 Editor tool, but a special statement set and the Screen Painter tool, which you also
use to layout screens. The flow logic mainly contains the chronologically ordered calls of the
modules in the corresponding module pool.
♦ The collection of PBO flow logic, screen, and PAI flow logic is called Dynamic program
(Dynpro). A module pool must have at least one dynpro. Each screen of a dialog session
thus is the visible part of a dynpro, to which also the flow logic belongs. The processing logic
of a dialog session is stored in the corresponding module pool in the form of ABAP/4
modules.
♦ The ABAP/4 modules in the module pool are separated into PBO and PAI modules. The
PBO or PAI blocks of the flow logic of each dynpro of a module pool can call each PBO or
PAI module of this module pool.
♦ You can use ABAP/4 statements in the processing logic of the module pool to control the
chronology of the different dynpros. After starting a dialog session via the transaction code,
which is firmly connected to a dynpro of the module pool, the screen flow logic passes user
entries to the processing logic in the ABAP/4 module pool. The processing logic processes
the user entries (database accesses) and, if required, defines the appropriate subsequent
screens.

25
ABAP BASICS

Data Types and Data Objects

Data types and data objects are essential components of the ABAP/4 type concepts. Both can be
declared and maintained by user. Unlike other programming languages in ABAP/4 you can
create DATA TYPES independently.

Data Types

♦ Are pure descriptions


♦ No memory is associated with data types.
♦ Describes the technical properties of data objects.

Structure and definition classify data types. Can be of:

1. Elementary or structured
2. Predefined or user defined

Predefined User-defined

ELEMENTARY C, D, F, I, N, P, T, X Based upon elementary


Data types.

You can use directly E.g.,


TYPES: number types I.
Can’t allocate memory to
types.

STRUCTURED Predefined types are User defined structured


TABLES types are Field String and
internal tables.

26
ABAP BASICS

Data Objects

♦ Data objects are units created during runtime.


♦ Data object cannot exist without data type.
♦ Occupies memory space.

Kinds of Data Objects

1. INTERNAL DATA OBJECTS

♦ Literal

A literal has a fixed value.


Ex WRITE: “WORK HARD”

♦ Variables

DATA statement is used to create variables


Ex DATA: NUM TYPE I
NUM is a variable declared by DATA statement. Any variable, which you use in program,
need to be declared before you use it and can be done by DATA statement.

Here variable is declared by referring to existing data type.

Variable can also be declared by referring existing data object.


Ex. We have already declared NUM by DATA statement.
DATA: PRICE LIKE NUM.
Here variable is declared by using LIKE parameter, which tells system that price has all the
attributes of data object NUM i.e., PRICE is also of type I.

The main difference between TYPE and LIKE parameter when defining or declaring the
object is that TYPE is used to refer existing DATA TYPE (elementary or structured or user
defined) while LIKE is used to declare data objects with reference to existing DATA
OBJECTS.

♦ Constant

Constant is a data object, which contains fixed value through out the program. Constant can
be declared in program by using CONSTANT statement.

Ex. CONSTANT: INT TYPE I VALUE 15.

27
ABAP BASICS

In program value of INT cannot be changed. If you give a statement like INT = 20.
In this case system will give error.

2. EXTERNAL DATA OBJECTS

Are defined in tables i.e., in ABAP/4 dictionary. You can access this data from table.

TABLES: SFLIGHT
DATA: SEATS LIKE SFLIGHT-SEATSMAX.

3. SYSTEM-DEFINED DATA OBJECTS

SPACE & SYSTEM VARIABLES like sy-uname, sy-datum, & sy-repid.

4. SPECIAL DATA OBJECTS

PARAMETERS: are variable, which can accept value from user.

SELECTIONS CRITERIA: are special internal tables to accept value range from user.

Need for Data types:

Consider the following example.

DATA: fname(20),
mname(20),
lname(20),
add1(20),
add2(20),
add3(20).

If you have DATA statement like above, and if you need to change the length of all the fields say
from 20 to 25, then you need to change all the fields i.e., going through each and every
statement.

But consider the following case where TYPES has been used.

TYPES:str(20)
DATA:fname type str,

28
ABAP BASICS

Mname type str,


Lname type str,
Add1 type str,
Add2 type str,
Add3 type str.

In this case if you need to change the length of all fields from 20 to 25. Then just change the
length of STR and change will be reflected for all the fields.

If you define all the types in TYPE-POOL i.e., global definition of all the types, you can use
these types anywhere and in any program.

Parameters

Parameter statement is used to accept input from user. PARAMETER statement is used when
you want user to enter data and depending upon what he enters you need to take action. The
parameter statement declares the variable and also allows system to accept data into that
variable.

Syntax.
Parameters: num type I.
Here parameter statement declares the variable and creates the selection screen on which user
enters the data i.e., in this case num is declared of type I and user can enter any number. Entered
value is stored in the same variable and can be used in program.
Data: m type I
Parameters: num type I
M = num – 5
Write: / ‘The number is’, m.
You can define default values with parameter statement for example
Parameter: num type I default 12.
In this case when selection screen is displayed the default value is displayed. User can either use
same value or overwrite the value.
Parameter of type character and length = 1, can be displayed as Checkbox and Radiobutton.
Parameter: C1 as Checkbox,
C2 as Checkbox.
Parameter: R1 Radiobutton group g1,
R2 Radiobutton group g1.

When parameter is defined as Radiobutton, it needs to be attached to one group. Only one
Radiobutton of one group can be clicked.

29
ABAP BASICS

Every parameter can be associated with language dependent text that is displayed on the
selection screen. This can be done with the help of text elements.

30
ABAP BASICS

WRITE Statement

The basic APAB/4 statement for outputting data on the screen is WRITE.

Syntax:

WRITE <field> <option>.

This statement outputs the field <f> to the current list in its standard output format.
By default, the list is displayed on the screen.
The field <field>can be any variable or table field or just literal.

PROGRAM ZDEMO
WRITE: /‘HELLO’.

When you start this program, the system leaves the current screen i.e., your editor screen and
branches to the output screen, which is also called as list screen:

The list screen has the same name as the title of the program specified in the program attributes.
First line on the screen contains the list header. By default, the list header is the same as the title
of the program. The current page number (1) appears on the right. The list header is followed
by one line and then the output is displayed.

Write : ‘HELLO’.
Write : ‘WORK HARD’

On the screen, the output is normally left justified. But in above case, because we have used two
WRITE statements, the output fields are displayed one after the other, each separated by one
column (i.e., one blank). If there is not enough space for an output field on the current line, a
new line is started.

Almost all system-defined fields are right justified except FLOAT, INTEGER, and PACKED
i.e., number field. The numeric data types F, P, and I are right justified and padded with blanks
on the left. If there is sufficient space, thousands of separators are also output. If a type P field
contains decimal places, the default output length is increased by one.

With the data type D, the internal format of a date differs from its output format. When you use
the WRITE statement for outputting data, the system automatically outputs dates of type D in the
format specified in the user’s master record (e.g. DD/MM/YYYY or MM/DD/YYYY).

31
ABAP BASICS

Formatting output

You can position the output of a WRITE statement on the screen by making a format
specification before the field name as follows:

Syntax:

WRITE AT [/][<pos>][(<len>)] <f>,


Where

• ‘the slash’/‘ denotes a new line,


• <pos> is a number or variable denoting the position on the screen,
• <len> is a number or variable long denoting the output length.

For variables you need to mention the AT, for direct values it is not necessary.

DATA: LEN TYPE I VALUE 10,


POS TYPE I VALUE 11,
TEXT (10) VALUE ‘1234567890’
WRITE AT POS (LEN) TEXT.

This produces the following output on the screen;


The text – 1234567890 – appears in the text.

If the output length <len> is too short, fewer characters are displayed. Numeric fields are
truncated on the left and prefixed with an asterisk (*). All other fields are truncated on the right,
but no indication is given that the field is shorter.

DATA: NUMBER TYPE I VALUE 1234567890,


TEXT (10) VALUE ‘abcdefghij’.

WRITE: (5) NUMBER, /(5) TEXT.

This produces the following output:


7890
abcde

In the default setting, you cannot create empty lines with the WRITE statement.
WRITE: ‘One’,
/‘ ’,
/ ‘Two’

32
ABAP BASICS

The output looks as follows:


One
Two

The system suppresses lines that contain nothing but empty spaces.

You can use various formatting options with the WRITE statement.

Syntax

WRITE………… <field> <option>

Formatting options for all data types

Option Purpose
LEFT-JUSTIFIED Output is left justified.
CENTERED Output is centered.
RIGHT-JUSTIFIED Output is right justified.
NO-GAP The blank after the field <f> is omitted.
NO-ZERO If a field contains only zeros, these are
replaced by blanks. For type C and N
fields, leading zeros are replaced
automatically.
Formatting options for numeric fields

Option Purpose
NO-SIGN The leading sign is not output.
DECIMALS <d> <d> defines the number of digits after the
decimal point.
EXPONENT <e> In type F fields, the exponent is defined in
<e>
ROUND <r> Type P fields are multiplied by 10**(-r)
and then rounded
CURRENCY <c> Format according to currency <c> in table
TCURX.
UNIT <u> The number of decimal places is fixed
according to the unit
<u> specified in table T006 for type P
fields.

33
ABAP BASICS

Horizontal lines
You can generate horizontal lines on the output screen by using the following syntax:
Syntax
ULINE
Will draw a horizontal line.
ULINE (10)
Will start drawing horizontal line from 10th column position.
WRITE at 10(40) SY-ULINE
This statement draws a horizontal line from 10th position.

Vertical lines
You generate vertical lines one the output screen by using the following syntax:
Syntax
WRITE [AT [/] [<pos>]] SY-VLINE.

Blank lines
You can generate blank lines on the screen by using the following syntax :
Syntax
SKIP [<number>]
Starting on the current line, this statement generates <number> blank lines on the output screen.
If no value is specified for <number>, one blank line is output. In the standard setting, you
cannot create empty lines with the WRITE statement alone.
To position the output on a specific line on the screen use:
Syntax
SKIP TO LINE <number>
This statement allows you to move the output position upwards or downwards.

34
ABAP BASICS

Branches

Like other higher programming languages, ABAP/4 provides standard keywords to control the
flow of a program.

Usually ABAP/4 programs get executed statement by statement. Many times you need to skip
few statements depending upon certain conditions i.e., you change the flow of program. This
can be done by:

♦ branching (IF, CASE)


♦ looping (DO, WHILE)

However, unlike other language where you have only internal control, ABAP/4 has internal
control and external control of the program flow.

♦ The internal control is steered by standard keywords as mentioned above. You define this
in your program code.
♦ The external control is stored by events. Events are generated either from other ABAP/4
programs or from interactive user input (like, for example, using the mouse to click on the
screen). The system does not necessarily process the statements in the same sequence as they
are listed in an ABAP/4 program. This makes ABAP/4 an event-driven programming
language. The external control plays an important role mainly for report programs.

Branching with IF statement

The IF statement allows you to divert the program flow to a particular statement block,
depending on a condition. This statement block consists of all the commands which occur
between an IF statement and the next ELSEIF, ELSE, or ENDIF statement.

Syntax

IF<condition1>
<statement block>
ELSE
<statement block>
ENDIF

If the first condition is true, the system executes all the statements up to the end of the first
statement block and then continues processing after the ENDIF statement.

35
ABAP BASICS

To introduce alternative conditions, you can use ELSEIF statements. If the first condition is
false, the system processes the following ELSEIF statement in the same way as the IF statement.
ELSE begins a statement block which is processed if none of the IF and ELSEIF conditions is
true. The end of the last statement block must always be concluded with ENDIF.
IF <condition1>.
<statement block>
ELSEIF <condition2>.
<statement block>
ELSEIF <condition3>.
<statement block>
ELSE.
<statement block>
ENDIF.
ABAP/4 allows unlimited nesting of IF – ENDIF statement blocks, but they must terminate
within the same processing block. In other words, an IF – ENDIF block cannot contain an event
keyword.

Branching with CASE statement

To execute different statement blocks depending on the contents of particular data fields, you can
either use IF statement or the CASE statement as follows:

Syntax
CASE <f>.
WHEN <f1>.
<statement block>
WHEN <f2>.
<statement block>
WHEN <f3>.
<statement block>
WHEN OTHERS.
<statement block>
ENDCASE.

The system executes the statement block after the WHEN statement if the contents of <f> equals
the contents of <fi>, and continues processing after the ENDCASE statement. The statement
block after the optional WHEN OTHERS statement is executed if the contents of <f> do not
equal any of the <fi> contents. The last statement block must be concluded with ENDCASE.

The conditional branching using CASE is a shorter and simpler form of similar processing with
IF. When you have many conditions IF becomes more complicated in such cases CASE is used.

36
ABAP BASICS

LOOPING

Looping with DO statement

If you want to write your name say for 10 times, you need to write WRITE statement for 10
times.
When you want to process a statement more than once, you can write this statement within a
loop with the DO statement as follows:

Syntax

DO 5 times.
Write : / name.
ENDDO.

The system continues processing the statement block for 5 times introduced by DO and
concluded by ENDDO.

The system field SY-INDEX contains the number of times the loop has been processed so in this
case when the loop is over value of sy-index will be 5.

In this case you know that, you want to perform WRITE statement for 5 times. But that is not
the case always. Many times you need to terminate the loop depending upon certain conditions.
This can be done, by using EXIT or STOP statement.

The important point to remember when you don’t you use TIMES option, is to avoid endless
loops when working with the DO statement. If you do not use the TIMES option, include at least
one EXIT, STOP statement so that the system can leave the loop.

EXIT and STOP takes you out of that loop.

Looping with WHILE Statement

If you want to process a statement block more than once as long as a condition is true, you can
program a loop with the WHILE statement as follows:

Syntax
DATA: M TYPE I VALUE 0.
WHILE M < 10.
WRITE: / M.
M = M + 1.

37
ABAP BASICS

ENDWHILE.

The system continues processing the statement block introduced by WHILE and concluded by
ENDWHILE statements as long as M is less than 10 or until the system finds an EXIT, STOP.

The system field SY-INDEX contains the number of times the loop has been processed.

You can nest WHILE loops any number of times and also combine them with other loops.

Difference between DO loop and WHILE is that in WHILE, condition is checked first and if
condition is true then loop is executed while in DO loop, the loop gets executed first if you don’t
have TIMES option and then the condition is checked (if you have any).

You can have nested DO and WHILE or DO and IF or IF and IF or any possible situation.

38
ABAP BASICS

String Operations

ABAP/4 provides several keywords for processing data objects of type C, also known as
character strings.

Shift command
To shift the contents of a field, by one position or one character you can use the SHIFT
statement. Using SHIFT allows you to shift field contents, byte-by-byte or character-by-
character.

With the SHIFT statement, you can execute the following:

String = ‘HELLO’.
String 1 = ‘ALL OF YOU’.
String 2 = ‘WORK HARD’.

Shift string
Shift string1 by 2 places.
Shift string2 right.
Shift string1 by 2 places circular.
The output will be

ELLO – By default if nothing is specified then string is shifted by one position.


L OF YOU – Here the string is shifted by 2 places.
_WORK HARD – In this case the string is shifted to right by one place (with leading blanks)
K HARDWOR – In this case the string is shifted to the left so that 3 characters on the left appear
on the right.

Replace command
You use the REPLACE statement.
Syntax
REPLACE<strl>WITH<str2>INTO<c>[LENGTH<1>].
ABAP/4 searches the field <c> for the first occurrence of the first, <1> positions of the pattern
<str1>. If no length is specified, it searches for the pattern <str1> in its full length.

Then, the statement replaces the first occurrence of the pattern <str1> in field <c>with the string
<str2>. If a length <l> was specified, only the relevant part of the pattern is replaced.

REPLACE STR1 WITH STR2 INTO STRING.


Here whole string is searched for string1 and is replaces with str2.
REPLACE ‘&’ WITH ‘M’

39
ABAP BASICS

Here the system searches string for & and replaces it with ‘M’.

TRANSLATE command
Syntax
TRANSLATE<c> TO UPPER CASE.
TRANSLATE<c> TO LOWER CASE.
These statements convert all lower case letters in the field <c> to upper case or vice versa.

You can use TRANSLATE to substitute the characters in a string like replace. But the main
difference between Translate and Replace is that Replace statement replaces only one occurrence
of particular character while Translate replaces all the occurrences of the character.

When using substitution rules, use the following syntax:


Syntax
TRANSLATE <c> USING <r>.

STRLEN command
To determine the length of a character string up to the last character other than SPACE, use the
built-in function STRLEN as follows:
Syntax
N = STRLEN ( STR ).
Here N is defined in DATA statement as type i.
STRLEN processes any operand <c> as a character data type, regardless of its real type. No
conversions are performed.

CONDENSE command
To delete superfluous blanks in character fields, use the CONDENSE statement:
Syntax
CONDENSE <c> [NO-GAPS].

This statement removes any leading blanks in the field <c> and replaces other sequences of
blanks by exactly one blank. The result is a left-justified sequence of words, each separated by
one blank. If the addition NO-GAPS is specified, all blanks are removed.

CONCATENATE command
To concatenate separate character strings into one, use the CONCATENATE statement:
Syntax
CONCATENATE <c1> …<cn> INTO <c> [SEPARATED BY <s>].
This statement concatenates the character fields <c1> to <cn> and assigns the result to <c>.
Trailing blanks are ignored during this operation.

40
ABAP BASICS

CONCATENATE STR ‘:’ STR2 INTO STRING.


Here str, str2 and ‘:’ is concatenated and result is stored in string.

SPLIT command
To split a character string into two or more smaller strings, use the SPLIT statement:
Syntax
SPLIT <c> AT <del> INTO <cl>….<cn>.

This statement searches the character field <c> for delimiter strings <del> and the parts before
and after the delimiters are placed in the target fields <c1>….<cn>.
To place all fragments in different target fields, you must specify enough target fields.
Otherwise, the last target field is filled with the rest of the field <c> and still contains delimiters.

SPLIT STRING AT ‘,’ INTO P1 P2 P3 P4.

Here the string is split at ‘,’ and is put into strings p1, p2, p3, p4.

♦ In ABAP/4, you can specify offset values for elementary data objects in all statements,
which process these data objects.

To do so, specify the name of a data object in a statement as follows:

Syntax

<f>[+<o>][(<l>)]

The operation of the statement is performed for the part of the field <f> that begins at position
<o>+1 and has a length of <l>.

If the length <l> is not specified, the field is processed for all positions between <o> and the end
of the field.

String = string1+3(4).

Assuming that string1 = ‘abcdefgjk’.


Here string will contain ‘defg’.

41
ABAP BASICS

OPEN SQL

In the R/3 System, long-life data is stored in relational database tables. Structured Query
Language (SQL) was created for accessing relational Database. SQL has two statement types:
Data Definition Language (DDL) statements and Data Manipulation Language (DML)
statements.

TO include SQL statements in an ABAP/4 program, use Native SQL. To avoid incompatibilities
between different database tables and also to make ABAP/4 program independent of the
database system in use, SAP has created a set of separate SQL statements called Open SQL.
Open SQL contains a subset of standard SQL statements as well as some enhancements, which
are specific to SAP. Using Open SQL enables you to access any database tables available to the
SAP system regardless of the manufacturer be it Oracle, Informix etc.

The difference between Open SQL and Native SQL is as follows:

A database interface translates SAP’s Open SQL statements into SQL commands specific to the
database in use. Native SQL statements access the database directly.

Open SQL keywords

Keywords Used for


• SELECT: Reading Data from Database Tables
• INSERT: Adding Lines to Database Tables
• UPDATE: Changing Lines in Database Tables
• MODIFY: Adding or Changing Lines
• DELETE: Deleting Lines from Database Tables

When using Open SQL statements in an ABAP/4 program, you must ensure the following:

1) The database system being addressed must be supported by SAP.


2) The database tables being addressed must be defined in the ABAP/4 Dictionary.

42
ABAP BASICS

Select statement

The following system fields play an important role in Open SQL operations:

SY-SUBRC

As with other ABAP/4 statements, the return code value in the system field SY-SUBRC
indicates after each Open SQL operation whether or not the operation was successful. If an
operation is successful, SY-SUBRC = 0. If an operation is unsuccessful – SY-SUBRC <> 0

SY-DBCNT

The value in the SY-DBCNT field indicates how many lines were affected by the operation or
how many lines have already been processed.

To read data from a database table, use the SELECT command.

Syntax

SELECT<what> FROM <table name> [INTO <variable, another table>] [WHERE


<condition>].
This statement has several basic clauses. Each clause is described in the following table.

SELECT<what> FROM <table name> INTO <variables or another table> WHERE <condition>

The SELECT clause defines whether the result of the selection is a single line or a whole table,
or few columns.

FROM <table name>

The FROM clause specifies the database table or view <source> from which the data is to be
selected.

INTO <variable, another table>

The INTO clause determines the target area <target> into which the selected data is to be read. It
can also be placed before the FROM clause. If you do not specify an INTO clause, the system
uses the table work area. The table work area is a header line, which is automatically
created by the TABLES statement.

WHERE <condition>

43
ABAP BASICS

The WHERE clause specifies which lines are to be read by specifying conditions for the
selection. Choosing the Lines to be Read.

For Selecting All data from table:

i.e., read all columns and all the rows from database table

Syntax

SELECT * FROM <table>.

(Here you are not specifying WHERE condition)

Selecting All Data from a Single Line

To read all columns of a single line from a database table, use the SELECT statement as
follows :

Syntax

SELECT SINGLE * FROM <table> …… WHERE <condition> ……

The result of this statement is a single line. To make sure you retrieve desired unique single
record, you must link all the fields which form the primary key of the database table by AND in
the WHERE condition.

Prerequisite for SELECT SINGLE

1. Use all primary keys in WHERE condition.


2. Always check for SY-SUBRC.
3. Clear work-area for table.

Aggregate Expressions

By using aggregate expressions, you can extract characteristic data from a column <a> of the
database table.
.MAX: returns the maximum value of the column
.MIN: returns the minimum value of the column
.AVG: returns the average value of the column
.SUM: returns the sum value of the column

44
ABAP BASICS

.COUNT: counts values or lines as follows:


-COUNT( * ) returns the total number of lines in the selection.

You must include spaces between the parentheses and the arguments. The arithmetic operators
AVG and SUM can only work with numeric fields.

Sometimes you retrieve few columns form database table i.e. you have list in the SELECT
Clause and INTO Clause.

If there is a list in the SELECT clause, you must use the INTO clause with the SELECT
statement. You can use either a work area <wa> or an internal table <itab> or list of variables as
an argument,

Syntax
TABLES: SFLIGHT.
DATA : CARRIDI LIKE SFLIGHT -CARRID,
CONNID LIKE SFLIGHT –CONNID.
SELECT CARRID CONNID FROM SFLIGHT INTO (CARRID1, CONNID1). WRITE: /
CARRIDl,CONNID1.
ENDSELECT.

Many times you retrieve related data from two or more tables. In such cases you use nested
selects by linking tables with common primary keys. But as far as possible avoid using nested
selects as time required to access nested table is very high.

Syntax

TABLES: SFLIGHT, SBOOK.


SELECT * FROM SFLIGHT WHERE CARRID = 'LH'.
SELECT * FROM SBOOK WHERE CARRID = SFLIGHT -CARRID AND
CONNID = SFLIGHT -CONNIID.
WRITE: / SFLSIGHT-CARRID,SFLIGHT-CONNID,SBOOK-BOOKID,
ENDSELECT.
ENDSELECT.

Some performance hints for Open SQL statements

♦ Keep the selected dataset small

Keep the number of selected data as small as possible to avoid unnecessary network
transports. Use the respective Open SQL statements always with the WHERE clause. Avoid

45
ABAP BASICS

complex WHERE clauses. The system must split up those into single statements for the
database system.
Do not use the logical NOT in WHERE clauses but inverted operators instead.
The logical NOT is supported by the database indexes.

♦ Keep the transferred data small

♦ Transfer only those columns of a database table that you really need. Avoid SELECT* if
you do not want to read all columns of a database. Use a list in the SELECT clause instead.
Use aggregate expressions in the SELECT clause to perform calculations instead transporting
great amounts of data and calculating thereafter.

♦ Keep the number of database accesses small

♦ Use operations on packages of data instead of operations on single data if you want to
analyze selected data more than once. To do so, transfer the data in a single operation
between tables and internal tables.

♦ Avoid nested SELECT loops. Instead, work with internal tables and SELECT statements
using the FOR ALL ENTRIES addition.

Insert statement

INSERT statement inserts a single record into the database table.

Syntax

Tables: sflight.
Sflight-carrid = ‘LH’.
Sflight-connid = ‘234’.
Insert sflight.

Table sflight is inserted with the record. The SY_SUBRC is returned for this statement. If the
entry already exists then the SY_SUBRC is set to non-zero value and you can do processing for
existing record by giving some error message.

46
ABAP BASICS

Update statement

To update database table UPDATE statement is used. This allows you to change either a single
record or several records.

You can use UPDATE when you know which record you want to change. But if you do not
know whether the primary key of the line you want to insert already exists or not, you can use
the MODIFY statement. The MODIFY statement changes existing lines and inserts lines which
do not exist.

Sflight-carrid = ‘MN’.
Sflight-connid = ‘454’.
UPDATE SFLIGHT where CARRID = ‘LH’.
Or
TABLES SFLIGHT.
UPDATE SFLIGHT SET PRICE = 1100
WHERE CARRID = ‘LH’.

Here price of sflight will get updated with new price 1100.

Delete statement

To delete records from a database table, you use the DELETE statement.

DELETE FROM SFLIGHT WHERE CARRID = ‘LH’ AND CONNID = ‘454’.

Will delete the single record where conditions are met from SFLIGHT.

You can delete the multiple records from database table by putting all the records, which you
want to delete in internal table. For example

DELETE SFLIGHT FROM TABLE ITAB.

In this case whatever you have in internal table will be deleted from SFLIHT.
Note: append internal table with all the entries, which you want to delete.

47
ABAP BASICS

EXERCISES

SIMPLE WRITE STATEMENTS

1 Write a program, which generates the model list as shown


Use these system fields in your program.
SY-DATUM, SY-UZEIT, SY-UNAME
Maintain the list headings

12/12/97 FIRST PROGRAM


______________________________________________________

This list is generated


on: 12/12/1997
at: 13:40:35
by: ABAP 1
______________________________________________________

2 Create a list as shown

---------------------------------------------------------------------------------------------------
XYZ Co. Pvt. Ltd.
Date: Today’s date Page No. 1
---------------------------------------------------------------------------------------------------

Program name: ZDEMO

48
ABAP BASICS

SYMBOLS, ICONS AND FORMATTING

1 Write a program to show the following using system variables


(hint: use include <symbol> and include <icon>

Symbols: Icons:
Telephone Checked; okay,
Fax machine Delete,
Hand pointing left, Print
Hand pointing right,
Caution,

Eg : Write sym_phone as symbol, ‘telephone’.

2 Write a program to show a string with different background colours.

eg.
write ‘HEADER’ color col_heading.
(col_heading is abap/4 name for grayish blue colour. Other colours are
col_key for bluish green, col_normal for bright gray, col_background for
gray, col_positive for green, col_negative for red, col_group for violet and
col_total for yellow)

3 Use Format intensified – format intensified off.


Format color <color_name> - format color off.
Format inverse – Format inverse off

4 Show current time and today’s date.

5 Show a value ‘123456’ as 12:34:56 using ‘using edit mask’.

6 Take a number as ‘0000011’. Suppress all leading zeros.

7 Suppress a sign before a number.

49
ABAP BASICS

GENERAL PROBLEMS

1 Create an adding machine for numbers.


The two values to be added must be entered on the selection screen as
parameters. Output the result.

2 Create the dividing machine for numbers.


The two values must be entered on the selection screen as parameters.
Output the result.

3 Create your output as shown below.

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

4 Write a program to accept the two numbers from the user and swap the values.

5 Declare a string ‘echo’ and design your output

e
e c
e c h
e c h o
e c h
e c
e

50
ABAP BASICS

DO-ENDDO, IF-ELSEIF-ELSE-ENDIF, CASE-ENDCASE

1 Write a program with Do – Enddo loop.


Display squares of numbers 1 to 10

1 1
2 4
3 9

2 Write a program to accept a number (say 2) from user and create a multiplication table.

2x1=2
2x2=4
…………
2 x 10 = 20

3 Accept a number from user and find Factorial of the same. If the number is negative then
display some message.

4 Write a program with Do – Enddo loop for first 20 numbers.


- Output should contain only Even number
- Odd numbers should not be displayed

5 Accept numbers and choice ‘EVEN’ or ‘ODD’ from the user and display the numbers in
that range according to user’s choice.

6 Write a program with Do – Enddo loop for first 20 numbers.


- Odd numbers & Even numbers should be displayed with alternate intensities. (Use
Format intensified – on – off)

7 Create a calculator, which performs the four basic types of calculations on two whole
numbers. The two values and the option are to be entered on the selection screen as
parameters. Output the result with 2 decimal places.

8 Write separate programs using ‘CONTINUE’ and ‘EXIT’ statements in DO-LOOP.

51
ABAP BASICS

STRING OPERATIONS

1 Accept a string and determine its length

2 Accept a string & number. Write the string that many number of times.

3 Accept two strings and swap their contents.

4 Accept two strings and concatenate into one string.

5 Accept one string with delimiter ( , or ; ) and split it into two strings.

6 Accept a string ‘abcdef’ and use shift <string>, shift <string> right, shift <string> up to
‘def’.

7 Accept a string eg. Apple. Change first occurrence of ‘p’ to ‘b’.


(use ‘replace’ command)

8 Accept a string eg. Apple. Change all occurrences of ‘p’ to ‘b’.


(use ‘translate’ command)

9 Accept two strings and compare the two strings using ‘co’, ‘ca’, ‘cs’
‘cp’ (out put shall be ‘true’ or ‘false’ for each comparison.)

10 Accept a string ‘ABCDEF’. Output only ‘DEF’ using offset command.

11 Accept first name, last name and middle name


eg. Nandamuri Taraka Ramarao
display as N.T.Ramarao

12 Accept a string. Change all occurrences of a to b.

13 Accept a number and swap first and last digit of the same.

14 Accept a string and display the string in reverse order

15 Accept a string and check for palindrome

52
ABAP BASICS

DATE PROBLEMS

1 Accept a date earlier to today’s date and find the difference in number of days.

2 Accept a date from user and display first day of the month and last day of the previous
month.

3 Accept a date from user and add six months to the date.

4 Accept a date from user and convert month part to ‘jan’, ‘feb’ etc., and display this date.

5 Write a program to accept month. Display number of days in total month.


Make use of
- Text element for your selection screen box.
- Selection text

6 Accept birth date from user and output age in years, months and days.

53
ABAP BASICS

CHECK BOXES AND RADIO BUTTONS

1 Write a program with


- Parameter as checkboxes
- If checkbox 1 is clicked write c.b 1 clicked else c.b 1 not clicked.
- If checkbox 2 is clicked write c.b 2 clicked else c.b 2 not clicked.
- If checkboxes 1 & 2 are clicked write c.b 1 & c.b. 2 are clicked.
- If checkboxes 1 & 2 are not clicked write c.b 1 & c.b. 2 are not clicked.

2 Write a program with


- Parameters as two groups of Radiobuttons (two Radiobuttons in each group).
- Give detailed coding as above, to show the Radiobuttons and groups
- selected

3 Write a program with


- Parameter as checkbox.
- If you click the checkbox then display first day of the next year.
- If the checkbox is not clicked then display last day of the current year.

4. Write a program with


- Parameter as group of 3 radio buttons
- If first radio button is clicked, display last day of the current month.
- If second radio button, display first day of the next month
- If third radio button, display date after six months.

54
ABAP BASICS

SELECT STATEMENTS

1 List all the rows from the table VBAK.

2 List single row from the table BKPF.

3 List up to 5 rows from the table BSIS.

4 List all ERDATs. For better readability create a column heading in the list

5 Display total amount for carrid ‘LH’. (Tables: SFLIGHT)

6 List all the flights for which booking date is greater than ’01.06.1995’.

7 List all the flights for which payments currency is ‘DEM’.

8 List all the flights where carrid is between ‘LH’ and ‘SQ’.

9 Select a single record where carrid = ‘LH’, flight-no = ‘0400’ and


fldate = ’28.02.1998’.

10 Display carrid, connid, fldate and luggage weight multiplied by 2

11 List the maximum capacity, occupied seats and total of current bookings for each flight in
the following format.

Carrier Max. capacity Occupied seats Total of current bookings


id

12 From the given from-city and to-city, list all the available on this route:
From: <from-city> To: <to-city> (say from Frankfurt to Madras)
(Tables: SPFL1)

Carrier Departure Time Start Airport Destination Airport


id

55
ABAP BASICS

OPEN SQL

1 Accept document no. from user and display particulars of Sales document. (Default
document no. ‘0010000031’)
(Table: VBAP)

Created on:xxxxx
Created by:xxxxx
Time: xxxxx

2 Accept Sales Document number from user and display corresponding material
no, description of that material and item category (Table : VBAP)

3 Accept material no. & item category by default PP100 and KMN respectively
Display corresponding details of sales document (Table: VBAP)

4 Display fields from BKPF.


Document type = ‘AB’ and
Document date = ’05.02.1998’.
Also display number of records selected.

5 Display Co. code, doc.no., acc.type, tax code.


Make use of select-options to give range of document type.
Display title of your program at the end of program

6 Accept doc. no from user.


Display doc.no., doc.status, date of doc., doc.type.

7 Display single record for document where date = ’05.02.1998’, type ‘= ‘AB and document
no. = ‘0100000006’.

8 Accept plant from user eg. PLTP.


Display document details for that plant like doc.no., doc.status, date of document etc.,

56

Vous aimerez peut-être aussi