You are on page 1of 178

INTRODUCTION TO ABAP

Who ? Why ?

Introductions Your objectives

Course Objective

To introduce the structure and syntax of the ABAP language so that attendees gain an appreciation of its capabilities To introduce the ways data is held in the SAP system and demonstrate how to report this data via ABAP To provide enough hands-on examples to allow the

attendees to be able to write their own reports

What is SAP?

System Application Products in Data Processing

1972 Founded by 4 IBM employees in a small German Town (Walldrof). SAP AG R/2 (Real Time / Two Tier)

1992 R/3 was introduced.


1995 SAP ranked fifth independent software vendors.

SAP Modules

SD
Sales and Distribution Materials Management

FI
Financial Accounting

MM

CO
Controlling

PP
Production Planning

R/3
HR
Human Resources

AM
Fixed Assets Accounting

QA
Quality Assurance

Plant Maintenance

Client/Server PS PM OC ABAP
Project System

IS
Industry Solutions

Office & Communication

Course Outline

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

System Architecture

MM, SD, FI, CO, PA, PS etc.

Informix, Oracle, SQL/Server etc.

Application Interface Database Engine Hardware

IBM, HP, SUN, HP etc.

System Architecture
APPLICATION SERVERS DATABASE SERVER PRESENTATION SERVERS

DATA BASE

DATA FLOW

Architecture of ABAP applications


Client/Server architecture

First level Presentation level (SAP Gui). Contains the user interface whereby an end user can access an application, enter new data and receive the results of a work process.

Second level
Application level. ABAP program runs in this level, consists of both the applications provided by SAP and the ones you develop yourself. ABAP programs work with data called up from the database level and store new data there as well. Third level

Database level. Data in here is managed with the help of a relational database management system (RDBMS). In addition to master data and transaction data, programs that describes the R/3 System are stored and managed here.

COURSE OUTLINE

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

A Powerful Tool

Advanced Business Application Programming


NB Before version 4.0 (1998), the official name was ABAP/4

The system is written in it SAP can be shaped to the Clients particular needs Adds value to the implementation ?

A Dangerous Weapon
Avoid changing the source code
SAP will not support a system that has been improperly changed.

Poor design = poor performance


Many projects get a reputation based on the performance of a small number of ABAPs

Is your ABAP really necessary?

Reporting Alternatives
Performance - time to develop compared to time to run. Standard SAP
Existing Reports SAP (ABAP) Query Report Writer LIS

Extended SAP
Business Information Warehouse

Third Party - though ABAP code often needed for data extraction

Data Loading Alternatives

Standard SAP
Data Transfer Workbench
Data reformatting and conversion ABAPs still need to be written

Extended SAP
Legacy System Migration Workbench (LSMW)
Data reformatting and conversion ABAPs are generated by the tools provided

(AB)uses of ABAP

Paper Reporting Interactive Reporting Data Export Data Import Batch Input

Transaction Development

COURSE OUTLINE

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

The Development Environment

Navigation

Eg on setting up a new server

Logging on
The logon screen

To change password:

1.

The system will prompt the change password box at initial logon screen (first time logging into the system)
Click on New password at the logon screen if you wish to change again

2.

The Development Environment

SAP Easy Access Menu

The Development Environment


Favorite list and user menu

The Development Environment

Command field

SAP Easy Access & Favorite lists

The Development Environment


List of useful commands:
1. /n To cancel the current transaction
2. /nxxxx To call transaction (where xxxx is your t-code name) directly from another transaction.

3. /o To open a new session.


4. /oxxxx To open a transaction in a new session (where xxxx is your t-code name) directly from another transaction. 5. /nend To end the logon session with a confirmation dialog box. 6. /nex To end the logon session without a confirmation dialog box. 7. /i To delete the session.

The Development Environment


Display F1 help

The Development Environment


Display F4 help

The Development Environment


Where-use list

Exercise 01
Task 1:
Logon to the system. Try to change the password. Once in the system, try to familiarize with the screen. Navigate to a transaction code (e.g. SE11) and return to the SAP easy access menu.

Task 2: What is the maximum number of parallel sessions that you can open using System -> Create session?

Task 3: What is the name of the function you reach if you choose Tools -> Administration -> Monitor -> System Monitoring -> User Overview?

Exercise 01

Task 4:

Familiarize with F1 and F4 help uses and do a where-used list on a


table via SE11. Sample of tables that can be used (e.g. MARA, MARC)

Task 5: Add a new transaction to the SAP easy access menu into the

favorites. Any transaction codes like (SM04, SE11, SE80) could be


added. Delete it once this is added.

COURSE OUTLINE

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

Packages and transports


ABAPs are examples of Development Objects. Other examples are:
Table Definitions
Screens

Development Objects are organized into Development Classes.

This enables objects to be assigned to Transports for transport to other systems.

Local Objects are not transportable, but can be reassigned to


development classes

Packages and transports

Ver 4.6 Tools > ABAP Workbench > Overview > Object Navigator -

this is transaction SE80


Note that in earlier releases the menu path was different, but the transaction was the same. You are then faced with a choice of view options, the most useful are:
Development Class Local Objects - defaults to objects local to your ID

Program

Press display to see the list of components

Creating package

A package can be created via SE80. When creating, it will prompt to enter
description (meaningful names) and assigning a transport number to it.

Creating transport
A transport can be created via transaction SE10 / SE01.

Transport Request types


Workbench Request
Request that involves changes to cross-client Customizing and Repository Objects. The objects are independent of the client. Therefore

the requests are used for transferring and transporting changed


Repository objects and changed system settings from cross-client tables.

Customizing Request
Request that involves changes recorded to client-specific Customizing objects .These client specific requests are used for copying and transporting changed system settings from client-specific tables.

Releasing transport
To release a transport, click on the truck button. Note: Do NOT click on this unless instructed to do so Note: If accidentally created a TR, click on the trash button to delete the transport.

COURSE OUTLINE

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

Program Outline

A program does something - divided up as follows:


INPUT (from the screen, the system etc)

PROCESS (calculate, manipulate)


OUTPUT (to the screen, to the system etc)

INPUT

PROCESS

OUTPUT

Program Structure I

Typical Report :

REPORT ...... * DECLARATION SECTION TYPES: ...... DATA: ...... * STATEMENT SECTION SELECT BUKRS BUTXT FROM T001 ........

Lets write an ABAP


From the Object Browser (SE80) Choose the Development Class or develop as a Local Object. If this is the first program in this category, then double click on Development class object type, then the Program tab. If programs already exist in this category, choose the Program folder and Right Mouse Click - Create Disable the option With Top Include - otherwise you will be creating the wrong kind of ABAP.

Names - an ABAP name can be up to 30 characters long


To keep SAP and client-written ABAPs separate, all client-written ABAPs should begin with Y or Z

Creating new program

To create a new ABAP program, we can do it via transaction


SE38 (ABAP editor) SE80 (Object Navigator)

Enter program name

Creating new program access key

To be able to create ABAP programs, you will need to be given an access key. Normally, you request this from the Basis team.
The developer access key is 20 characters in length. You only need to enter this key ONCE.

Creating new program


Description

Type
Executable program

Include program
Module pool Function group etc.

The Development Environment


In SE80
Right Mouse Click on a folder or object within a folder. This activates a Context Menu - different options depending on what the context is - folder or type of

object.

Creating transaction code

Going into the editor

Save (Ctrl-S)

Display/Change mode(Ctrl-F1)

Syntax check (Ctrl-F2)

Save/activate (Ctrl-F3)

Execute (F8)

Display object list

Exercise 02
Task 1:
Create an ABAP program via SE38 or SE80 which will be called Zuu_exNN_<meaningful description>

uu is your ABAPER number


NN refers to the exercise number Please stick to these rules FOR THIS COURSE ONLY - ALL ABAPS SHOULD BE LOCAL PRIVATE OBJECTS - NO TRANSPORT

Task 2:
Write a simple program (eg. Write: / Hello World. ). Perform syntax check,
save, activation and execute the program. Get yourself familiar with the shortcut keys and the screen.

Exercise 02

Task 3:
Copy program Z00_TEST_TCODE, create a transaction code for the
program. Name your transaction Zuu_NN_tcode uu is your ABAPER number NN refers to the exercise number

Task 4:
Add the newly created transaction code to the favourites in the SAP easy access menu.

COURSE OUTLINE

Client/Server Architecture

Uses of ABAP
The Development Environment Packages and Transport request

ABAP program structure


Debugging

PROGRAM DEBUGGING

A powerful tool to show what a program is doing Enables us to walk through code step-by-step

Enables us to check values of certain fields at each step


Debugging of standard SAP is also possible The downside is the impact it has on response

Starting
You have no idea where the error is:
Switch on Debugger in the Editor initial screen via Program =>

Execute => Debugging


Execute the program You may find yourself debugging SAP standard code eg selection-screen processing.

You have an idea where the program is starting to go wrong


Set a Break Point - the program will process up to that point then stop in the debugger.

Break Points
BREAK POINTS are points at which we want to stop the program to start debugging. There are 2 types: DYNAMIC
These are session specific - you loose them when you sign off

Set on Active programs via the icon


Can be cleared via the menu or within the debugger

STATIC.
Set directly into code via the Editor
User-independent - visible in program code MUST BE REMOVED FOLLOWING TESTING

Screen Display I
7 Different Views - same basic structure

Fields (default) - Displays a fields contents and technical characteristics Table - Displays the contents of an internal table Breakpoints - Gives a scrollable display of up to 30 breakpoints defined in the program Watchpoints - Displays up to 5 watchpoints Call Stack - Displays an active event chain up to the current breakpoint Overview - Displays the structure of the program being debugged Settings -

Screen Display II
There are a number of ways of stepping through the
program code using the debugger:
SINGLE STEP - executes a program statement by statement EXECUTE (subroutines treated as a single step) CONTINUE - up to the next BREAK or WATCH POINT RETURN - to the calling program. Used from within a subroutine call

Field contents
To display the contents of critical fields used in the program
Use Fields view Double Click on the field name to bring it into the display Click on Click on to display Hexadecimal value to replace the value - this can be used to force the program

through pathways that it is difficult to find data for.

Watchpoints
Set a WATCH POINT to check when a field contents changes

Conditional WATCH POINT - e.g. stop execution when the document


number is 4900012345 Execute by choosing CONTINUE - program will stop when the

chosen field contents change or hit a certain value

Debugging 1

An important tool for ABAP programmers. This can be done in various

ways.
1. Click on Stop icon.

Debugging 2

2. Using keyword break-point or break <user-id>

Debugging 3

3. Enter /h in the command field in the standard toolbar and press enter.

Help

SAP provide 2 forms of help:


CD ROM / Library Help HELP <KeyWord>
then type in the keyword F1 on the key word

On the web: https://www.sdn.sap.com/irj/sdn https://websmp206.sap-ag.de/

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types Data: Tables

Data Access: The SELECT statement


Internal tables

ABAP Syntax I

Not unlike other major programming languages (e.g. COBOL)

Similar commands
WRITE PERFORM

MOVE

Similar structures
IF/ELSE DO/WHILE CASE etc.

ABAP Syntax II

A program is made up of statements which must end with a .


DATA MY_FIELD(1) TYPE C.
MOVE MY_FIELD TO YOUR_FIELD. YOUR_FIELD = MY_FIELD.

The words in a statement must be separated by at least 1 space

Statements can be indented for easy reading


Make use of the Pretty Printer push-button to auto-indent your codes.

Statements can spread over several lines

The first word in a statement is often a key word

ABAP Syntax III- Chaining


Where several statements use the same key word, they can be chained (via a colon :) - the statements being separated by commas. WRITE My name is. WRITE first_name.

WRITE family_name.
Equivalent to: WRITE: My name is,

first_name,
family_name.

System Fields I

Automatically available to you

SY-DATUM - Date
SY-UZEIT - Time SY-UNAME - Your Logon ID

SY-REPID - The ABAP being run


SY-SUBRC - Return Code (0 = Success)

Format color

In a list, we can design the screen by adding colors. Below are the

attributes that we can add.

Exercise 03

Task 1:
Create an ABAP program which will be called Zuu_exNN_<meaningful
description>

Task 2:
Display your Logon ID, Date and Time

Write Statement II

WRITE:/p(w) Text.
Text - Better to use numbered texts (see later)
/ - New Line (or use syntax NEW-LINE)

p - Position on the Screen (w) - Field Width

Example:
WRITE:/2(3) HELLO. => HEL

Other examples in HELP WRITE

Exercise 03

COPY Exercise 2

Line up the columns of data

Control Statements
LOGIC FLOW
IF ... ENDIF. ON CHANGE OF ... END ON. CASE ... ENDCASE.

LOOPS
DO ENDDO. WHILE ENDWHILE.

OTHERS
CHECK
CONTINUE EXIT

The IF Statement

The basic syntax is:

IF <Logical Expression> .
.... ELSE. Processing done when true Optional

....
ENDIF.

Processing done when false

Conditionals - the IF statement


IF <field1> NE <field2>.
IF <condition1> AND <condition2>. IF <condition1> OR <condition2>. IF NOT ( <condition1> ). IF <condition1>. ... ELSEIF <condition2>. ...

IF Operations
These operations can be used within IF clauses to compare
certain values: Relational Operators (Letters or Symbols) EQ = GT > LT < NE <> >< GE >= => LE <= =<

BETWEEN <value1> AND <value2> IS INITIAL (The initial value for that data type)

String Comparisons
As well as comparing values, we can also use the IF
statement to check character strings against certain criteria using the following:

CO CA CS CP

CONTAINS ONLY CONTAINS ANY CONTAINS STRING CONTAINS PATTERN

THE CASE STATEMENT

CASE <FIELD>. WHEN <VALUE1>


...

WHEN <VALUE2>

...
WHEN OTHERS - CATCH ALL ...

ENDCASE.

Do, While
DO <N> TIMES . <N> can be a constant or
.... ENDDO. field.

DO. .... ENDDO.

Must have an EXIT inside.

WHILE

<LOGICAL EXPRESSION>.

.... ENDWHILE.

The EXIT statement


TERMINATES PROCESSING OF CURRENT LOOP OUTSIDE A LOOP - TERMINATES THE ABAP Used to prevent program behaving unpredictably or crashing under certain conditions Example:

IF <undesirable condition>.

- processing, e.g. error message


EXIT. ENDIF.

The CHECK Statement


Check a condition is satisfied before continuing processing Syntax:
CHECK <LOGICAL EXPRESSION>. CHECK: <F1>, <F2>. AND implied CHECK: <F1> OR <F2>.

IF THE CHECK SUCCEEDS:


CONTINUE PROCESSING

IF THE CHECK FAILS:


SUBSEQUENT STATEMENTS IN PROCESSING BLOCK NOT EXECUTED

The CHECK Statement


CHECK within loop
WHILE COUNTER LT 100.

FALSE

statements CHECK Entry NE SPACE.

TRUE
statements ENDWHILE.

CHECK outside loop


TOP-OF-PAGE. CHECK SY-PAGNO GT 1.

TRUE
statements

FALSE

CONTINUE

This is a version of CHECK that has no logical expression

It is used to move on to the next iteration within the loop without


having to process the rest of the code in the loop In older ABAPs the same function was achieved by:

CHECK 0 = 1. Always false

Comments

* - Marks a complete line as a comment

- Marks the remainder of a line as a comment (USE THEM!)

You can comment / uncomment blocks of code: Select > Block/Buffer > Insert or Delete Comment

PATTERN - useful for code template generation


Pattern XANSA is a sample template for the start of the ABAP

Write Statement I

Displays data on the screen which can be printed out.

Basic Syntax:
WRITE <FIELDNAME>.

Fields are automatically separated by 1 space


An output list will be wrapped around automatically

Check and Save

Do this as you go.

The syntax checker stops at the first error.


Remember the Scales of Justice.

Activation

For ABAPs this is new in version 4.6

When code is changed in an ABAP it is set Inactive


To Activate an ABAP press Note: You can activate an ABAP with syntax errors, but it is not

advised. You can only release and transport an active ABAP


Other users in the system can only access the active version of your ABAP - ABAPs are client independent.

Activate <=> Deactivate

Copy an ABAP - The Active source goes to an Inactive target

Rename - does not change the status


Save - makes the program Inactive Activate - also saves

Breakpoints - can only be set on an Active program


You can toggle between Active and Inactive versions In Active mode, you can delete the Inactive Version. Utilities >

Versions > Return to Active Version

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types Data: Tables Data Access: The SELECT statement Internal tables

Parameters

Defines fields to be filled on the Selection Screen

Names must have a maximum of 8 characters


Example:

PARAMETERS: pa_name(8) TYPE C.


DEFAULT - Value preset OBLIGATORY - Must be entered

Parameters
PARAMETERS are one way of supplying values to a program at run time PARAMETERS: pa_plant TYPE mard-werks DEFAULT READ OBLIGATORY.

SELECT werks lgort labst INTO stockstr FROM MARD WHERE werks = pa_plant. ... ENDSELECT.

REPORT SPECIFIC SELECTION

To cause a selection range to appear on the Selection Screen: SELECT-OPTIONS: <SO_OPT> FOR <Field_Name>. This is a special kind of internal table containing 4 fields:
<SO_OPT>-SIGN <SO_OPT>-OPTION <SO_OPT>-LOW <SO_OPT>-HIGH I(nclusive) E(xclusive) Value (EQ, BT etc) Start of the range End of the range

SELECT-OPTIONS
SELECT-OPTIONS <SO_OPT> FOR <Field_Name>.

DATA: WA_COUNTRY TYPE Z9A01-COUNTRY. SELECT OPTIONS: SO_CNTRY FOR WA_COUNTRY DEFAULT GB TO US.

Internal table
Sign
I

Option Low
BT GB

High
US

Screen:
S_CNTRY GB US

VALUE SETS
VALUE SETS ALLOW FOR MULTIPLE SELECTIONS
Screen:
C_CNTRY (Press on )

...
Internal table SO_CNTRY
Sign Option EQ EQ Low BE FR High

Extended selections for COUNTRY: Single Value Selections: BE OR IMPLIED FR Ranges: GB US

I I

BT

GB

US

REPORT SPECIFIC SELECTION


Using these to select data:
SELECT <field_1> <field_2> <field_n> INTO (<new_fld_1>, <new_fld_2>, <new_fld_3>) FROM <TABLE> WHERE <Field_Name> IN <S_OPT>.

If a SELECT-OPTIONS is left empty on the selection screen, the ABAP will select all data.

Select-options
In select options, there are a few options that is available

The POWER and the GLORY

POWER Small amount of ABAP coding necessary


Define SELECT-OPTIONS Code the IN Add in Selection Texts

GLORY You have provided a very flexible selection tool to the user

PARAMETERS vs SELECT-OPTIONS
PARAMETERS PO_PARM TYPE <Field> Support only a single value SELECT-OPTIONS

SO_OPT FOR <Field> Allow for flexible data selection / exclusion

Both follow the rules: Maximum of 8 characters as a name Screen Description via Selection Texts Initial value set by DEFAULT option

Exercise 04
Task 1:
An ABAP Calculator Define 3 PARAMETERS 2 input integer numbers 1 input operand ( + , - , * , / ) Output the result to 2 decimal places Allow for invalid operators and division by zero

This can be achieved using ifelse..endif, caseendcase. Try using both methods

Exercise 05
Task 1:
Write an ABAP program to display contents of SFLIGHT table using a parameter selection. The program will prompt the user to enter (CARRID) carriage ID as the parameter selection criteria. Display all flights with the following information:
SFLIGHT-CARRID
SFLIGHT-CONNID SFLIGHT-FLDATE SFLIGHT-PLANETYPE SFLIGHT-SEATSMAX SFLIGHT-SEATSOCC

Exercise 06
Task 1:
Write an ABAP making use of the select-options selection. Distinguish the difference between no intervals and no-extensions usage.

Task 2:
Write an ABAP program to display contents of SFLIGHT table using a select-options selection. The program will prompt the user to enter a range of (CARRID) carriage ID as the selection criteria. Display all flights with the following information:
SFLIGHT-CARRID SFLIGHT-CONNID SFLIGHT-FLDATE SFLIGHT-PLANETYPE SFLIGHT-SEATSMAX SFLIGHT-SEATSOCC Notice the difference using select-options

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types Data: Tables Data Access: The SELECT statement Internal tables

Declarations - Data
Definition of variables (fields) used in the program

You can either:


Define it based on an SAP Dictionary Type. This makes it have the same characteristics as an existing SAP field. Define it based on a Standard Data Type

Based on an SAP Dictionary Type -Syntax


DATA: <fieldname> TYPE <Dictionary Type>.

Declarations- Data

Based on a Standard Data Type

DATA: <fieldname>(l) TYPE t.


l = length in bytes t = data type. Possibilities are:

C - Character
D - Date (YYYYMMDD) P - Packed (2l - 1 digits, decimals)

I - Integer
N - Numeric text (1 byte/digit)

Declarations - Data and numbers

Use Type P for accuracy (decimal places)

Use Type I for speed (counters)


Use Type N for Input/Output only

Declarations - Data field names

Local to the program

Try to select meaningful field names


Avoid:
dashes

spaces

Declarations - Data values

VALUE x - preassigns value x to a field

Example (fixed point):

DATA: TEMP_FIELD(3) TYPE P


DECIMALS 2 VALUE 123.45.

Declarations - Constants

DATA fields may be changed by operations within the ABAP CONSTANT fields cannot be changed within the ABAP Example:

CONSTANTS: PI(3) TYPE P DECIMALS 4 PI = 3.9999. - syntax error

VALUE 3.1428.

Partial Fields
For types C,N,D it is possible to refer to part of a field:

<fieldname>+O(L)

O is the offset (zero is the first position) L is the length Example: TEMP_NAME = JOHN ARMYTAGE TEMP_NAME+5(4) contains ARMY Under certain conditions O and L can be variables

Numbered Texts

WRITE: TEXT-nnn will display the contents of numbered text nnn

(nnn is a 3 character identifier)


Maintained through Text Elements or Double Click on the TEXT in the ABAP

TEXTS are language dependent

Message types
Message tnnn(message class) with v1 v2.
Type I Description Information Behavior Appearance

Program continues after Model dialog box interruption

Success

Program continues w/o interruption

Status bar

Warning

Context dependent

Status bar or dialog box

Error

Context dependent

Status bar or dialog box

A
x

Termination
Short dump

Program cancels
Runtime error triggered

Model dialog box


Short dump

Exercise 07

Task 1:

Copy program from exercise 5. Add additional logic to check when


the user enters invalid data. If the input is invalid, prompt an error message. Else, the program should have a success message

displayed.
Test the other message types namely ( W, S, E, A, and I) to see how the program handles it.

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types
Data: Tables

Data Access: The SELECT statement Internal tables

Data Access I - Tables

Data is stored in SAP as tables

What do they look like?


Help then Table/Structure/View We may need to reference table fields from within our ABAP
e.g. MARD-MATNR = Material Number
Note the dash !

TABLE SFLIGHT

Marked fields form the table key


Fields have a name, data type, length and description (these are all set up in Data Dictionary)

Will be used to introduce the next set of concepts

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types Data: Tables Data Access: The SELECT statement Internal tables

Accessing Data

SELECTED DATA

DATABASE (where the data sits)

APPLICATION SERVER (where the ABAP runs)

The Select Statement

Basic Syntax
SELECT something - a list of table fields
INTO somewhere - a target area in the program FROM a table WHERE selection conditions

The SELECT statement does allow you to retrieve data from more than 1 table, but this is beyond the scope of this course.

Optimising SELECT

Optimising the design of this process is vital to ABAP Design

This section will focus on 2 areas:


SELECTing from a single table Multiple SELECTs

In practice, Basis monitoring is needed to determine if the table


needs:
Buffering - most suitable for small, config type tables not often updated. Indexing - most suitable for large data tables frequently accessed via non key fields.

SELECT from a single table

Small Buffered Tables


Consider reading the table once into an internal table (possibly sorting
it)

Large Tables
Indexes to improve selection on non key fields (e.g. Material Number in table MSEG) New database techniques to extract summarised data from the table on the database

Any Table
Only SELECT the fields you need

Select Endselect
SELECT <field list> INTO <target area> FROM <table> WHERE <selection criteria>. ..... ENDSELECT. Each selected record will be made available in turn within the SELECT ... ENDSELECT SY-SUBRC will not be zero if no data is selected SY-DBCNT will show the number of successful SELECTs

SELECT SINGLE

Retrieve a single record from an external table

Full Key must be specified (apart from the client)


SY-SUBRC must be checked to determine if the access is successful (0 -> success)

No ENDSELECT needed - the read is either a success or it is not.

SELECT INTO TABLE

One Step Build of an Internal Table

No ENDSELECT needed
Avoid the use of INTO CORRESPONDING FIELDS OF - this causes each entry in the database table to be checked in turn

MULTIPLE SELECTs

Many ABAPs need to SELECT data from several tables - there are

several ways of doing this.


Nested SELECTs SELECT INTO & SELECT ... FOR ALL ENTRIES IN Views Logical Databases

In this situation a poorly designed method can cause severe performance problems

NESTED SELECTs
SELECT FROM KNA1. ....

SELECT FROM KNB1 WHERE KUNNR = KNA1-KUNNR.....


SELECT FROM BSID WHERE KUNNR = KNA1-KUNNR AND BUKRS = KNB1-BUKRS. .... ENDSELECT. ENDSELECT.

ENDSELECT.

SELECT INTO TABLE I


SELECT ... FROM KNA1 INTO TABLE CUSTABA.

SELECT ... FROM KNB1 INTO TABLE CUSTABB FOR ALL ENTRIES IN CUSTABA WHERE KUNNR = CUSTABA-CUSTNO.

SELECT ... FROM BSID INTO TABLE DOCTAB FOR ALL ENTRIES IN CUSTABB WHERE BUKRS = CUSTABB-COCODE AND KUNNR = CUSTABB-CUSTNO.

Selecting into a table will NOT require ENDSELECTs

SELECT INTO TABLE II


Use nested LOOPs to report by
LOOP AT CUSTABA. .... LOOP AT CUSTABB WHERE CUSTNO = CUSTABA-CUSTNO. .... LOOP AT DOCTAB WHERE COCODE = CUSTABB-COCODE. ..... ENDLOOP.

ENDLOOP.
ENDLOOP.

Defining a Target Area I

DATA: plant TYPE mard-werks, store TYPE mard-lgort, stock TYPE mard-labst.

* Note where the commas, spaces and brackets are


SELECT werks lgort labst INTO (plant, store, stock)

FROM mard WHERE ...


... ENDSELECT.

Defining a Target Area II - Structures

DATA: BEGIN OF custstr, name TYPE z9a01-name, city TYPE z9a01-city, country TYPE z9a01-country, END OF custstr. NAME CITY COUNTRY

Filling the Structure

FIELD BY FIELD: CUSTSTR-NAME ... (etc) CODING SHORTCUT: MOVE-CORRESPONDING Z9A01 TO CUSTSTR . Using SELECT = Z9A01-NAME.

Select Intro (Structure)

DATA: BEGIN OF stockstr,

plant
store stock

TYPE mard-werks,
TYPE mard-lgort, TYPE mard-labst,

END OF stockstr.
SELECT werks lgort labst INTO stockstr FROM MARD WHERE .... ... ENDSELECT.

Authorization check
Authorization object S_CARRID
Fields: CARRID ACTVT

Change
CARRID = ACTVT = 02

Display
CARRID = ACTVT = 03

E.g. To display all CARRID, you can include * To create authorization object: SU21/SE80

Exercise 08

Task 1:

Create a program to show how a select.endselect works. Retrieve


the following fields (CARRID, CONNID, FLDATE, PLANETYPE, SEATSMAX, SEATSOCC) using the following conditions:
CARRID = P_CARRID
Where P_CARRID is the parameter from the selection screen.

Display the records in a list format. If there are no records found, inform the user that No records have been selected.

Exercise 09

Task 1:

Create a program to show how a select single works. Retrieve the following
fields (CARRID, CONNID, FLDATE, PLANETYPE, SEATSMAX, SEATSOCC) using the following conditions:
CARRID = AA CONNID = 0017 FLDATE = 20070930

Display the records in a list format. If there are no records found, inform the user that No records have been selected. Try to store them in both variable and structure format.

Exercise 10

Task 1:

Create a program to show how a selectinto table works. Retrieve


the following fields (CARRID, CONNID, FLDATE, PLANETYPE, SEATSMAX, SEATSOCC) using the following conditions:
CARRID = P_CARRID
Where P_CARRID is the parameter from the selection screen.

Display the records in a list format. If there are no records found, inform the user that No records found.

Exercise 11

Task 1:

Create a program with parameter CARRID.


Check whether the user has authorization for the airline AA. Use authorization object S_CARRID.

If the user is authorized, display a list of all the airline records.


Else if the user is not authorized, inform the user that he/she is not authorized.

COURSE OUTLINE

ABAP syntax

Report specific selection


Data: Data Types / Message Types Data: Tables Data Access: The SELECT statement Internal tables

INTERNAL TABLES

These are tables internal to an ABAP and are used to store and

process data.

There are 3 parts to their use that we shall consider:


DEFINITION - in the DATA statement
FILLING THE TABLE - APPEND, COLLECT or APPEND SORTED BY PROCESSING THE TABLE - LOOP AT . Only process a table when it has been completely built.

INTERNAL TABLES

Table type

Standard table

Sorted table

Hashed table

Index Access

Key Access

Uniqueness of key Access

Non-unique

Unique/Nonunique

Unique

Primarily index Primarily key access access

Exclusively key access

Exercise 12

Task 1:

Create a program to show how the 3 different table type works.


Standard table Sorted table using non-unique keys of PLANETYPE and SEATSOCC

Hashed table using unique keys of CARRID CONNID FLDATE

INTERNAL TABLE DEFINITION

There are several (over 10) different ways to define these.

Many date from earlier releases and still supported for compatibility
reasons We will focus on the Standard type with Work Area - this is the

default format for ver 4.6

Internal table w/o Header Line


TYPES: BEGIN OF custstr , country TYPE z9a01-country, name city TYPE z9a01-name, TYPE z9a01-city,

turnover TYPE z9a01-turnover,


END OF custstr. *

DATA: wa_cust TYPE custstr,

Work Area

it_cust TYPE STANDARD TABLE OF custstr INITIAL SIZE 100.

Internal table with Header Line

TYPES: BEGIN OF custstr ,

country TYPE z9a01-country,


name city TYPE z9a01-name, TYPE z9a01-city,

turnover TYPE z9a01-turnover, END OF custstr. *

DATA: wa_cust TYPE custstr,

Work Area

it_cust TYPE STANDARD TABLE OF custstr WITH HEADER LINE.

TABLE STRUCTURE
WORK AREA:
CUSTTABCOUNTRY CUSTTAB-NAME CUSTTAB-CITY CUSTTABTURNOVER

FR JP Sartre
INTERNAL TABLE : BE FR FR Tintin Louis XIV JP Sartre
.

Paris

1234

Bruxelles Versailles Paris


. .

1111 2222 1234


.

(100 rows)

FILLING THE TABLE

SELECT customer city country turnover

INTO wa_cust
FROM z9a01 WHERE <condition>.

APPEND wa_cust to it_cust.


ENDSELECT.

FILLING THE TABLE

Fill the fields of the work area then:


APPEND <WORK AREA> TO <TAB> - New records added into the table body at the end.
APPEND <WORK AREA> TO <TAB> SORTED BY <Field> - Sort on Descending Order. The number of entries stored is the value of the INITIAL SIZE.

COLLECT <WORK AREA> INTO <TAB> - Accumulates numeric (type P or I) data.

Where the source of data is an SAP table - the fastest way is an array fetch

SELECT <Field List> INTO TABLE <Internal Table>


FROM <Database Tables> WHERE <Conditions>

Append

1. APPEND

<tab>.

Country Sales

DE

400

AU US

700 200

Country Sales

2. APPEND

<tab>

SORTED BY SALES.

DE

400

AU
US

700
200

Collect

COLLECT <tab>.
Country Sales

DE

400

AU

100

US
DE

200
200 DE 600

INTERNAL TABLES and the DEBUGGER

The debugger can be used to see how an internal table is being

filled.
Can also adjust entries
MODIFY

DELETE
INSERT APPEND

This is for the run of the program only

APPEND v COLLECT

APPEND - entries added at the end of the table. No summarising,

fast table build.


COLLECT - searches the table for an entry for an entry where the table line matches the header for all but P,I type fields.
If it does not find one, a new entry is added at the end of the table.
If it does find one, then it adds the contents of the P,I fields in the header to the body.

Numeric data is summarised; table build is slower

PROCESSING THE TABLE - SORTING

Sort the table only after it has been built


SORT <TAB>. - Sorts by all non-numeric fields in the order specified
SORT <TAB> BY COUNTRY. SORT <TAB> BY COUNTRY CITY DESCENDING.

Note that the field names are not qualified. Try to define table fields in correct order (primary sort field first, etc) to exploit powerful features

PROCESSING THE TABLE - LOOP AT

LOOP AT <TAB> INTO <WORK AREA>.


......

ENDLOOP.

SY-SUBRC NE 0 if the table is empty CHECK within the LOOP goes on to the next entry

LOOP AT <TAB> WHERE - Restrict the range of data selected

AT COMMANDS

AT FIRST - First entry in the Table

AT LAST - Last entry in the Table


AT NEW <FIELD> ) Fields below this in the table are not available

AT END OF <FIELD> )

SUM - Provides control break totals - note these are stored in the
header numeric fields ENDAT to end the block

The order in which these are coded is the order in which they will
take place.

AT FIRST / AT LAST
LOOP AT <internal_table> INTO <work area>.

... (processing)
AT FIRST. ... (processing to be performed during first loop pass through the table)

ENDAT. ... AT LAST.

... (processing to be performed during final loop pass


through the table) ENDAT. ENDLOOP.

AT NEW / AT END OF
These are used as follows within LOOP ENDLOOP: LOOP AT it_cust INTO wa_cust.

AT NEW country.
SKIP. WRITE:/ Country:, wa_cust-country.

ENDAT.
WRITE:/ wa_cust-city, wa_cust-name, wa_cust-turnover. ENDLOOP.

SUM

SUM is used within an AT ENDAT block as follows:

AT FIRST/LAST/NEW <field>/END OF <field>. ... (processing)

SUM.
... (processing relevant to sum) ENDAT.

BRINGING IN THE DATA

WORK AREA: CUSTTAB-NAME CUSTTAB-CITY CUSTTABCOUNTRY CUSTTABTURNOVER

TABLE :
1 2 3

Tintin Louis XIV JP Sartre

Bruxelles Versailles Paris

BE FR FR

1111 2222 1234

Delete table contents


To delete the table contents:
Refresh
Deletes entire content of the table

Clear
Use with internal tables without header lines (have the same effect as

refresh). For internal table with header line, it only clears the header.

Free
Deletes entire content of the table and releases the memory used

Exercise 13
Task 1: Copy program from exercise 11. Using APPEND, insert a new record into the internal table by adding the following values:
CARRID = XX CONNID = 123 FLDATE = SY-DATUM PLANETYPE = 747-400

Task 2: Using DELETE, delete the record which was appended in task 1.

Exercise 13

Task 3:

Using INSERT, insert a new record into the internal table by adding the
following values to position 2 of the internal table content:
CARRID = XX CONNID = 123 FLDATE = SY-DATUM PLANETYPE = 747-400

Task 4: Using MODIFY, modify value for PLANETYPE 747-400 to 123-456.

Exercise 13

Task 5:

Sort the internal table by SEATSMAX (ascending/descending)


Display the list at the end of the program execution.

Exercise 14
Task 1: Create a new program. Retrieve CARRID, CONNID, FLDATE, PLANETYPE, SEATSMAX, SEATSOCC from SFLIGHT using conditions:
CARRID = P_CARRID

Using the records returned from SFLIGHT, retrieve CARRID, CONNID, BOOKID, CUSTTYPE, SMOKER, LUGGWEIGHT from SBOOK into a separate internal table. (Note: use for all entries addition in this select statement) This will base on:
CARRID = I_SFLIGHT-CARRID

CONNID = I_SFLIGHT-CONNID
FLDATE = I_SFLIGHT-FLDATE

Exercise 14
Task 2: The final report should show information of CARRID, CONNID, FLDATE PLANETYPE, SEATSMAX, SEATSOCC from SFLIGHT and CUSTTYPE, SMOKER, LUGGWEIGHT from SBOOK.
Hints:
Sort the tables Loop through the main table and read the next table with matching fields

Task 3: The header should contain (Carriage ID, Connection ID, Flight Date, Plane type, Seats max, Seats occ, Cust type, Smoker and Weight). Use color format on to distinguish the header and the record items. (Hint: use format color on)

COURSE OUTLINE

Events & Sub programs

Function Modules & BAPIs

EVENTS
INITIALIZATION.
AT SELECTION-SCREEN START-OF-SELECTION. GET END-OF-SELECTION. TOP-OF-PAGE. END-OF-PAGE. AT LINE-SELECTION. AT USER-COMMAND. ABAP HAS PASSED THE SELECTION SCREEN

EVENTS

START-OF-SELECTION - the ABAP has passed the Selection

Screen but has not yet tried to GET any data


END-OF-SELECTION - there is no more data for the ABAP to GET These statements should be used in all ABAPs particularly those

using Logical Databases

SUBROUTINES

A subroutine is called by a PERFORM statement as follows:

PERFORM write_hello

A subroutine is a block of code which is tagged between FORM..ENDFORM

PROGRAM MODULARITY

A general programming concept

A MODULE is a discrete, self-contained chunk of code that performs


a specific task A well-designed program will have a high degree of MODULARITY

Advantages:
Code is easier to understand Programs are easier to test Programs are easier to maintain

FORMS I
Internal Subroutines Local DATA declarations are allowed in FORMs Basic syntax: PERFORM <FORM1>. ..... FORM <FORM1> ....... ENDFORM.

Create the skeleton FORM block by double-clicking on the name in the PERFORM block.

FORMS II - USING
Global data (eg Table fields) is known throughout the program,
including in all FORMs We may want to pass different arguments to the FORM under different circumstances. Syntax:
PERFORM ... USING - passing the ACTUAL parameters FORM ... USING - using the FORMAL parameters

Passing BY REFERENCE

PERFORM <FORM1> USING ARG1 ARG2 RES1.


.......... FORM <FORM1> USING A1 A2 R1. R1 = A1 + A2. ENDFORM.

If A1 or A2 are changed in the Form, then ARG1 or ARG2 will

change in the main program


RES1 will be filled with the result

Passing BY VALUE

PERFORM <FORM1> USING ARG1.

........
FORM <FORM1> USING VALUE(A1). ... ENDFORM.

A1 is in a separate storage location to ARG1 - ARG1 will not be changed This method does not allow for any changes in the form to be passed back to the main program.

Passing BY VALUE & RESULT

PERFORM <FORM1> USING ARG1 CHANGING ARG2.

..........
FORM <FORM1> USING VALUE(A1) CHANGING VALUE(A2). ...

ENDFORM.

Only ARG2 will be changed

Exercise 15

Task 1:

Write a program displaying date field to hold SY-DATUM + 7 in the


initial selection screen. Display the value on the list.
Hints: Make use of the events (initialization)

Exercise 16

Task 1:

Create a program utilizing the subroutine. Set up constant data and


use this to simulate pass by value, reference and value-result.

COURSE OUTLINE

Events & Sub programs

Function Modules & BAPIs

FUNCTION MODULES

What they are

How to find them


How to use them How to write them will not be discussed here

FUNCTION MODULES

Standard routines contained in the Function Builder

They are used for a wide variety of tasks:


Currency Conversion Interfaces - File uploads/downloads

Batch Input Control


Address formatting Calendar Functions

Any ABAP can call them

FUNCTION GROUPS

Function Modules are arranged in Function Groups

Groupings determined by whether the modules are logically related


and/or use the same global data variables Function Group ID - up to 26 character code (+ description)

Function Module names - up to 18 characters


Example: Function Group ABCD contains:
Master ABAP: SAPLABCD

Global data stored in LABCDTOP


Function Module code stored in LABCDxxx

Function module
What is FM? Function modules are applied across applications and are available throughout the SAP system. Function modules must be assigned to a function group. A function group is a placeholder which holds specific function modules that are defined in it. Function group can be created via SE37 or SE80 SE37 SE80

A Black Box
ABAP EXPORTS
FUNCTION MODULE
IMPORTS

TABLES

EXCEPTIONS (errors)
EXPORTS

ABAP IMPORTS

Use in ABAP I
Syntax (use the PATTERN button to generate this):
CALL FUNCTION EXPORTING PARM1 = <Field1> FUNCTION_NAME

.......
IMPORTING PARM10 = <Field10> .........

EXCEPTIONS
NOT_FOUND = 1 .

Use in ABAP II
To enter the FM into the ABAP program, use the Pattern push-button. Alternatively, the codes can be typed in as well.

The syntax will be copied into the program. ABAPer needs to fill in the input and/or output variables.

CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT' EXPORTING INPUT = * IMPORTING * OUTPUT =