Vous êtes sur la page 1sur 211

ABAP Programming language

1
Première séance :
- Présentation : Introduction à l’ABAP I
- Atelier :
o Prise en main de l’outil / Hello World
o Variables ABAP
o Le dictionnaire de donnée
o Interrogation de la base de donnée et tables internes
o Manipulation chaine de caractère
Deuxième séance :
- Présentation : Introduction à l’ABAP II
- Atelier :
o Utilisation du Perform
o Séparation de code
o Optimisation du code pour plus de performance

o Développement de Rapports et Etats : ALV


Troisième séance :
- Présentation : Les Functions Modules
- Atelier :
o Recherche et appel aux FMs
o Developpement de FMs
Quatrième séance:
- Présentation : Query / Infosets
- Atelier :
o Creation d'Infosets : Manipulation tables/jointures
Cinquième séance :
- Présentation : Sapscript
- Atelier :
o Introduction / Overview
o Eléments du formulaire (Page, fenêtre, format de
paragraphes,…)
o Technique de mise en forme
o Programme d’impression
o Exemple pratique

Sixième séance :
- Présentation : Smartform
- Atelier :
o Introduction / Overview
o Eléments du formulaire (Attribut, interface,
fenêtre, template, table,…)
o Mise en forme / Smartstyle
o Programme d’impression / Module de Fonction
o Exemple pratique
ABAP Programming Language

Advanced Business Application Programming

4
ABAP Workbench

Repository Information
ABAP Editor
System

ABAP Dictionary Test & Analysis Tools

Repository Browser Function Builder

Menu Painter Data Modeler

Screen Painter Workbench Organizer

5
Reporting

• Programs can be written interactively using the


capabilities of the R/3 system. Programs can be
executed both online or in the background.
Background jobs can also be scheduled to run
at specific intervals.
6
Terms to Remember

Program
• A series of ABAP statements

Report:
• An ABAP program whose output is a
list

Module Pool:
• A dialog program which is a collection
of screens

List:
• The output generated by an ABAP
report program
7
Reporting and ABAP Development
Reporting

ABAP
8 Development
Programming Environment -
The ABAP Editor

9
Programming Environment
Online Debugging

10
Basic Functions of the ABAP Editor
Find and
Repeat Find Standard toolbar
Syntax Check
Undo

ABAP Help

Toggles from
display to
change mode
Cut, copy and paste
to and from a buffer

Program source entry area

11
The PROGRAM Menu Option

12
The EDIT Menu Option

13
The GOTO Menu Option

14
The UTILITIES Menu Option

15
The BLOCK/BUFFER Menu Option

16
The SETTINGS Menu Option

To set Editor mode,


use the menu path
Settings-> Editor
mode

Preferred settings:
· PC mode with
line numbering
· With
compression logic
· Key word large

17
Basic ABAP Program Syntax

DATA COUNT TYPE I.


DATA TITLE(25).
MOVE 1 TO COUNT.
MOVE ‘President’ TO TITLE.
WRITE TITLE.
ABAP Program
WRITE COUNT.
Statement.

Word 1 Word 2 Word 3 Word 4

Key word Parameter, field, or constant

18
Chaining Statements in ABAP

DATA COUNT TYPE I.


DATA TITLE(25).
MOVE 1 TO COUNT.
MOVE ‘President’ TO TITLE.
WRITE TITLE.
DATA: COUNT TYPE I,
WRITE COUNT.
TITLE(25).

MOVE: 1 TO COUNT,
‘President’ TO TITLE.

WRITE: TITLE, COUNT.

19
Comments in ABAP
A double quotation mark
(“) anywhere on a line
makes everything that
follows a comment.

An asterisk (*) in column


1 makes the entire line
a comment line.

20
ABAP Program Structure

Program Name Area


Use REPORT for listing programs
Use PROGRAM for online programs
Declaration Section
Used for defining tables, variables
and constants
Statement Section
Used for coding executable
ABAP statement

21
ABAP Program Attributes

Program title is required

Type:
1 - Executable Program
I - Include Program
M - Module Pool
F - Function Group
S - Subroutine Pool
Application:
S - Basis
U - EDM (Enterprise Data Mode
V - Sales and Distribution
Y - Customer Head Office
Z - Customer Branch
22
* - For all Applications
Running an ABAP Program

An Alternative
Method:
From the System
Menu, choose
From the ABAP Editor: Services® Reporting
With the program to launch
displayed, the program
Program®Execute
One Final Method:
From the ABAP Editor: Initial Screen,
type the program name, then click on
the Execute push-button
23
The ABAP “WRITE” Statement
WRITE ‘********************’.
SKIP 2.
WRITE: ‘The date today is:’, SY-DATUM,
‘The current time is:’, SY-UZEIT.
SKIP 2.
WRITE ‘********************’. Notice that there is an
automatic space between the
fields written to the list.
<program title> 1
----------------------------------------------------------------------------------
-
********************

The date today is: 12/30/1996 The current time is: 12:32:06
********************
24
ABAP Format Specifications

WRITE 10 ‘***** City of Philadelphia *****’.


SKIP 2.
WRITE: 10 ‘Ticket Date’, SY-DATUM.
WRITE: /10 ‘Ticket Time’, SY-UZEIT.
ULINE /10(60).
SKIP 2.
WRITE 10 ‘***** Department of Public Safety *****’.
***** City of Philadelphia *****

Ticket Date 01/01/1997


Ticket Time 18:01:00
-----------------------------------------------------

***** Department of Public Safety *****


25
ABAP Format Options
WRITE 10 ‘***** City of Philadelphia *****’.
SKIP 2.
WRITE: 10 ‘Ticket Date’, 25 SY-DATUM,
/10 ‘Ticket Time’, SY-UZEIT UNDER SY-DATUM.
ULINE /10(60).
SKIP 2.
WRITE 10 ‘***** Department of Public Safety *****’.
***** City of Philadelphia *****

Ticket Date 01/01/1997


Ticket Time 18:01:00
------------------------------------------------------------

***** Department of Public Safety *****


26
“WRITE” Statement Extended
Syntax

WRITE <format> <value> <options> .


<format>
/p(I)
/ = Line Feed <value>
p = Column Position
I = Output Length
Program Field or <options>
Text Literal

Format Options

27
“NEW-PAGE” Statement
WRITE ‘***** City of Philadelphia *****’.
SKIP.
WRITE: / ‘Ticket Date’, 15 SY-DATUM.
WRITE: / ‘Ticket Time’, 15 SY-UZEIT.
SKIP.
WRITE ‘***** Department of Public Safety *****’.
NEW-PAGE.
WRITE: ‘Comments:’.
<program title> 1
--------------------------------------------------------------------------------------
***** City of Philadelphia *****

Ticket Date 01/01/1997


Ticket Time 18:01:00

***** Department of Public Safety *****

28
<program title> 2
---------------------------------------------------------------------------------------
Comments:
Writing Icons and Symbols

INCLUDE <ICON>.
INCLUDE <SYMBOL>.

WRITE: /10 ICON_DATE AS ICON, SY-DATUM,


SYM_LEFT_HAND AS SYMBOL.

Execute programs
“SHOWICON” and
“SHOWSYMB” to
display the system’s
icons and symbols.

29
Maintaining Page Headers

The title comes from


the program’s
attributes.

List header will replace


title on first line of
standard header.

Up to four lines of column


headings can be maintained
for the list.

30
Numbered Texts (Text Symbols)

WRITE: / TEXT-001, BIRTHDAY,


/ TEXT-002, SY-DATUM.

Text symbols are


referenced by a unique
three-character code.
31
ABAP Elementary Data Types

C: Character Text N: Numeric Text

I: Integer D: Date

P: Packed # T: Time

F: Floating Point # X: Hexadecimal #

32
Declaring Variables

DATA: PLAYER(35) TYPE C,


NICKNAME(35),
POINTS TYPE I,
GAMES TYPE I VALUE ‘10’,
AVERAGE(5) TYPE P,
STARTER,
ACQUIRED TYPE D.

33
Initial Values

C: (blank) N: zeroes

I: zero D: 00000000

P: zero T: 000000

F: zeroes X: 00

The “CLEAR” statement sets a field back to its initial value, not
its default value.
34
Assigning Default Values

DATA: PLAYER(35) TYPE C,


NICKNAME(35) VALUE ‘Dr. J’,
POINTS TYPE I VALUE ‘255’,
GAMES TYPE I VALUE 10,
AVERAGE(5) TYPE P VALUE ‘25.5’,
STARTER VALUE ‘Yes’,
ACQUIRED TYPE D VALUE
‘19760610’.

35
Declaring “Like” Fields

DATA: PLAYER(35) TYPE C VALUE ‘Julius Erving’,


NICKNAME(35),
ACQUIRED TYPE D.

Use the “LIKE” addition to declare fields


with the same format (i.e., data type and
length)

DATA: PLAYER(35) TYPE C VALUE ‘Julius Erving’,


NICKNAME LIKE PLAYER,
ACQUIRED LIKE SY-DATUM.

36
Declaring Constants

The “VALUE” addition


is required.

CONSTANTS: TEAM1(20) TYPE C VALUE ‘76ers’,


TEAM2 LIKE TEAM1 VALUE ‘Celtics’,
TOT_GAMES TYPE I VALUE 82.

If you attempt to change the value of a constant, a syntax error


will occur.

37
User-Defined Data Types

TYPES: NAME(35) TYPE C,


TEAMS(20) TYPE C.
DATA: PLAYER TYPE NAME VALUE ‘Troy Aikman’,
NICKNAME LIKE PLAYER.
CONSTANTS: TEAM1 TYPE TEAMS VALUE ‘Cowboys’,
TEAM2 LIKE TEAM1 VALUE ‘Packers’.

A user-defined data type created with the “TYPES” statement is used to


specify a field’s data type in the “TYPE” addition of the “DATA” or
“CONSTANTS” statements.

38
Output Characteristic for Data
Types
Standard Length Justification

C = defined length C = left-justified


I = 12 I = right-justified
P = (2 * defined length) + 1 P = right-justified
F = 22 F = right-justified
N = defined length N = left-justified
D = 10 D = left-justified
T =8 T = left-justified
X = (2 * defined length) X = left-justified

39
Output for Numeric Fields
DATA: FLOAT TYPE FVALUE
‘98.7654321E2’,
PACK TYPE PVALUE 12,
INT TYPE I VALUE 32.

WRITE: / FLOAT,
/ FLOAT EXPONENT 1 DECIMALS 3,
/ FLOAT EXPONENT 0 DECIMALS 2,
/ PACK,
/ PACK DECIMALS 1,
9.876543210000000E+03
/ INT DECIMALS 2.
987.654E+01
9876.54
These fields are not aligned 12
because of the different 12.0
standard output lengths of 32.00
40 the numeric type fields.
Assigning Values to Fields

MOVE <value> TO <field>.


[COMPUTE] <field> = <value or expression>.
ADD <value> TO <field>.
SUBTRACT <value> FROM <field>.
MULTIPLY <field> BY <value>.
DIVIDE <field> BY <value>.
DATA: TITLE(25),
SALARY TYPE P,
CNVSALARY LIKE SALARY,

MOVE ‘President’ TO TITLE.


COMPUTE SALARY = 5000000.
CNVSALARY = SALARY * 3.
ADD 1000 TO SALARY.
41
Arithmetic Expressions

Operators Functions
+ - * / ** SQRT, EXP, LOG,
DIV and MOD SIN, COS, STRLEN, . . .

COUNTER = COUNTER + 1.
SALARY = BASE * BONUS_PERCENT.
LENGTH = STRLEN( NAME ).
ANSWER = ( 10 + SQRT( NUM1 ) ) / ( NUM2 - 10 ).

Spacing is very important when using arithmetic expressions!!!

42
Sub-Fields in ABAP

DATA: CUSTOMER(10) TYPE C, Use an offset and length


INV_DATE LIKE SY-DATUM. to display or change
portions of a field.
CUSTOMER = ‘1234567890’.
INV_DATE = ‘19960626’.

WRITE: / CUSTOMER+8(2), ‘xx’,


INV_DATE(4).
90 xx 1996
* Start of Month 123456ABCD ----- 06/01/1996
INV_DATE+6(2) = ‘01’.
CUSTOMER+6 = ‘ABCD’.
WRITE: / CUSTOMER, ‘------’, INV_DATE.
43
Date Calculations in ABAP

DATA: DAYSOLD TYPE P, Date fields store values as


DOB TYPE D, “YYYYMMDD”.
TODAY LIKE SY-DATUM.

DOB = ‘19621230’.
TODAY= SY-DATUM.

DAYSOLD = TODAY - DOB.

WRITE: ‘You are’, DAYSOLD, ‘days old.’.

You are 12410 days old.

44
Declaring Fields with PARAMETERS

PARAMETERS: NUM TYPE I,


NAME(20) DEFAULT ‘AARON’.

ADD 10 TO NUM.

WRITE: / NUM,
‘----’,
NAME.

“Selection Screen”

32 ---- AARON
45
Selection Texts

These selection texts will


be used on the selection
screen instead of the
parameter names.

46
Working with Field Symbols in
ABAP
DATA: NUM TYPE I VALUE 12.
FIELD-SYMBOLS: <F1>,
<F2> TYPE I, A field symbol is a
<F3> LIKE NUM. “pointer” that assumes a
field’s address, not a
ASSIGN: NUM TO <F1>, field’s value.
NUM TO <F2>,
NUM TO <F3>.

WRITE: / ‘Line 1:’, NUM, <F1>, <F2>,


<F3>.

<F1> = 32.

WRITE: / ‘Line 2:’, NUM, <F1>,


Line 1: 12 12
<F2>, 12 12
<F3>. Line 2: 32 32 32 32
47
Dynamic Assignment of Partial
Strings
DATA: TEXT_LINE(30) VALUE ‘ABCDEFGHIJK’.

FIELD-SYMBOLS <FSYMBOL>.
ASSIGN TEXT_LINE+2(5) TO <FSYMBOL>.
* this assigns 5 characters of text_line starting at
* position 3 to the field string.

WRITE: / ‘text line =‘, TEXT_LINE.


ULINE.
WRITE: / ‘field symbol=‘, <FSYMBOL>.
ULINE.
<FSYMBOL> = ‘1234567890’.
WRITE: / ‘field symbol =‘, <FSYMBOL>.
ULINE.
WRITE: / ‘text line =‘, TEXT_LINE.
48
Dynamic Field Assignment
PARAMETERS FIELD(8) DEFAULT ‘SY-UZEIT’.
FIELD-SYMBOLS <FSYMBOL>.

ASSIGN (FIELD) TO <FSYMBOL>.

IF SY-SUBRC = 0.
WRITE: / ‘The contents of field’, FIELD, <FSYMBOL>.
ELSE.
WRITE: / ‘Failure assigning field’, FIELD, ‘to field symbol’.
ENDIF.

FIELD SY-UZEIT Selection Screen

The contents of field SY-UZEIT 12:32:06 List


49
Open SQL

Open SQL - a subset of standard SQL

Portable across various databases

50
Example Using the SELECT
Statement

TABLES: KNA1.

SELECT *
FROM KNA1.
WRITE: / KNA1-KUNNR, KNA1-NAME1.
ENDSELECT.

51
The SELECT Statement with a
WHERE Clause

TABLES: KNA1.

SELECT *
FROM KNA1
WHERE KTOKD = ‘0001’.
WRITE: / KNA1-KUNNR, KNA1-NAME1.
ENDSELECT.

52
SY-SUBRC
TABLES: KNA1.

SELECT *
FROM KNA1
WHERE KTOKD = ‘0001’.
WRITE: / KNA1-KUNNR, KNA1-NAME1.
ENDSELECT.

IF SY-SUBRC <> 0.
WRITE: / ‘No records found.’.
ENDIF.

53
The INTO Clause
TABLES: KNA1.

DATA : VL_KUNNR like KNA1-KUNNR,


VL_NAME1 like KNA1-NAME1.

SELECT KUNNR
NAME1
FROM KNA1
INTO (VL_KUNNR,
VL_NAME1).
WRITE : / VL_KUNNR , VL_NAME1.
ENDSELECT.

IF SY-SUBRC <> 0.
WRITE: / ‘No records found.’.
ENDIF.
54
INTO CORRESPONDING-FIELDS
TABLES: KNA1.

DATA : BEGIN OF WT_KNA1,


KUNNR like KNA1-KUNNR,
NAME1 like KNA1-NAME1,
TEMP like sy-datum
End of WT_KNA1.

SELECT KUNNR
NAME1
FROM KNA1
INTO CORRESPONDING-FIELDS
OF WT_KNA1.
ENDSELECT.

IF SY-SUBRC <> 0.
WRITE: / ‘No records found.’.
ELSE.
LOOP at WT_KNA1.
WRITE WT_KNA1-IKUNNR.
ENDLOOP.
ENDIF.

55
Basic Flow Control in ABAP

56
The IF Statement
IF X =5.
WRITE :/ ‘The value of X is
5’.
ELSEIF X =6.
WRITE :/ ‘The value of X is
6’.
ELSE .
WRITE :/ ‘X is neither 5 nor
6’.
ENDIF.

57
Logical Expressions
Logical Expressions use :

RELATIONAL OPERATORS
LOGICAL OPERATORS
STRING COMPARISON
OPERATORS

58
Relational Operators

Comparison Syntax
Is Equal to =, EQ
Is not equal to < >, ><, NE
Greater than >, GT
Greater than or equal to > =, = >, GE
Less than <, LT
Less than or equal to <=, =<, LE

59
Logical Operators

AND
OR
NOT

The hierarchy of the logical


operators is:
NOT, AND and then OR.
60
(ie different from creating views)
Bad
Good Programming Practice with
Logical Operators

If not ( X = 0 )
or not ( Y = 1 and
Z = X or X = 3
and ( Z = 5 )

61
String Comparison Operators

Comparison Syntax
Contains only CO
Contains any CA
Contains string CS
Contains pattern CP
Contains not only CN
Contains not any NA
Contains no string NS
Contains no pattern NP

62
The CASE Statement

e n .
h ’
W AVE
‘S en
CASE Wh TA’.
SY-UCOMM. ‘S R

When
‘SRTD’.

Whe
n
Wh ‘GET
D’.
‘PI e n
CK
Don’t forget ’.
those periods!

63
The DO Loop

J =4.
DO.
DO J TIMES.
WRITE :/ ‘Hello
WRITE :/ ‘Hello
world!’.
world!’.
ENDDO.
ENDDO.

64
The WHILE Loop

If expression evaluates to
If expression evaluates to FALSE, code in loop is
TRUE, code in loop is NOT executed, and
executed. control moves to after
ENDWHILE.

65
Nested Loops and Control
Structures

DO 2 TIMES.
WRITE :/ SY-INDEX.
DO 3 TIMES.
WRITE : / ‘ ‘, SY-INDEX.
ENDDO.
ENDDO.

66
The ON CHANGE OF Statement

SELECT * FROM YCUSTOMER.


ON CHANGE OF YCUSTOMER-
COUNTRY OR YCUSTOMER-STATE.
[….]
ENDON.
ENDSELECT.
67
The CHECK Statement
DO 10 TIMES.
CHECK SY-INDEX <=
4.
WRITE :/ SY-INDEX.
ENDDO.

68
The EXIT Statement

IF SY-SUBRC <>0.
EXIT.
ENDIF.

69
The CONTINUE Statement
DO 10 TIMES.
IF SY-INDEX >4.
CONTINUE .
ENDIF.
WRITE :/ SY-INDEX.
ENDDO.

70
Data Structures

Structure Internal Table

Address List Address List

LN FN City ST. LN FN City ST.

LN FN City ST.

LN FN City ST.

71
Declaring a Structure - Method #1
Is this statement
1 REPORT YN1C0008.
2
necessary for the Basic Syntax:
3 TABLES: TABNA. code? DATA: BEGIN OF <name>
4 DATA: BEGIN OF ADDRESS,
5 FLAG TYPE C, <field1> . . .
6 ID LIKE TABNA-ID,
7 NAME1 LIKE TABNA-NAME1, <field2> . . .
8 CITY LIKE TABNA-CITY,
9 END OF ADDRESS.
...
10 MOVE ‘X’ TO ADDRESS-FLAG. END OF <name>.
11 MOVE ‘0001’ TO ADDRESS-ID.
12 MOVE ‘Smith’ TO ADDRESS-NAME1.
13 MOVE ‘Philadelphia’ TO ADDRESS-CITY.
14
15 WRITE ADDRESS.
16 Address Structure
17 Flag ID Name1 City
18
19
20
21
22
23
72
Declaring a Structure - Method #2
REPORT Yxxxxxxx. Basic Syntax:
TYPES: BEGIN OF ADDR,
TYPES: BEGIN OF <name1>,
FLAG,
<field1> . . . ,
ID LIKE EMPLOYEE-ID,
NAME1 LIKE EMPLOYEE-NAME1,
<field2> . . . ,
CITY LIKE EMPLOYEE-CITY, ... ,
END OF ADDR. END OF <name1>.
DATA: ADDRESS TYPE ADDR. DATA: <name2> TYPE
<name1>.
MOVE: ‘X’ TO ADDRESS-FLAG,
‘00001’ TO ADDRESS-ID,
Address Structure
‘Smith’ TO ADDRESS-NAME1,
Flag ID Name1 City
‘Philadelphia’ TO ADDRESS-CITY.

WRITE ADDRESS.

73
Populating a Structure with
Field-by-Field Transport
REPORT Y170DM37.
EMPLOYEE
TABLES: EMPLOYEE. ID Name1 City
DATA: BEGIN OF ADDRESS, 000000001 Electronics Inc. Waldorf
FLAG, MOVE-CORRESPONDING EMPLOYEE
ID LIKE EMPLOYEE-ID,
Address TO ADDRESS.
Flag ID Name City
NAME LIKE EMPLOYEE-NAME1,
000000001 Waldorf
CITY LIKE EMPLOYEE-CITY,
END OF ADDRESS. Clear <f1>.

SELECT * FROM EMPLOYEE.


MOVE-CORRESPONDING EMPLOYEE TO
ADDRESS.
WRITE: / ADDRESS-FLAG, ADDRESS-ID,
ADDRESS-NAME, ADDRESS-CITY.
CLEAR ADDRESS.
ENDSELECT.

74
Internal Table Types

• Standard
• Sorted
• Hashed

75
Creating an Internal Table
with Header Line
REPORT Y170DM38. The TYPES statement defines the
TABLES: EMPLOYEE. structure and data type for the
TYPES: BEGIN OF EMP, internal table.
ID LIKE EMPLOYEE-ID, The DATA statement with an
NAME1 LIKE EMPLOYEE-NAME1, INITIAL SIZE creates the actual
COUNTRY LIKE EMPLOYEE-COUNTRY, internal table capable of storing
END OF EMP. data. Because of the WITH
HEADER LINE addition, this
internal table is created with a
DATA: EMPTAB TYPE STANDARD TABLE
header line.
OF EMP INITIAL SIZE 10 WITH HEADER
LINE. ID NAME1 COUNTRY
Header Line
SELECT * FROM EMPLOYEE.
MOVE-CORRESPONDING EMPLOYEE TO
EMPTAB.
APPEND EMPTAB.
ENDSELECT.
76
Internal Table Keys

• Implicit Key
– All character fields
• Explicit Key
– User-defined
• e.g. … WITH [ UNIQUE/NON-UNIQUE ] KEY
FIELD1 FIELD2 ...

77
Size of an Internal Table

78
Loading an Internal Table with a
Header Line
REPORT Y170DM42. With both versions of the
TABLES: EMPLOYEE. APPEND statement, memory
space for ten records is allocated
TYPES: BEGIN OF EMP,
when the first record is written to
COUNTRY LIKE EMPLOYEE-COUNTRY, the internal table.
ID LIKE EMPLOYEE-ID,
SALARY LIKE EMPLOYEE-SALARY,
END OF EMP. Example 1
DATA: EMPTAB TYPE STANDARD TABLE
More than ten entries can be
OF EMP INITIAL SIZE 10 WITH HEADER saved in the internal table.
LINE.

SELECT * FROM EMPLOYEE.


Example 2
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. A maximum of ten entries can
be saved in the internal table.
APPEND EMPTAB.
OR MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
Any entries that exceed the
top ten will
APPEND EMPTAB SORTED BY SALARY. be deleted.
ENDSELECT.

79
Loading an Internal Table with a
Header Line

APPEND <int. table>. APPEND <int. table>


SORTED BY <field>.
Department Salary Department Salary
Header
R&D 400,000 R&D 400,000
1 PROD 7,800,000
MKTG 1,000,000
2 MKTG 1,000,000
SALES 500,000
3
PROD 7,800,000 SALES 500,000
4
IT 50,000 5
HR 140,000
HR 140,000 6 IT 50,000

80
Internal Table with Header Line

EMPLOYEE

A COUNTRY ID FORMA NAME1 SORTL . . .

ID NAME1
COUNTRY
B Header Line

81
Internal Table with Header Line

1 EMPLOYEE

COUNTRY ID FORMA NAME1 SORTL . . .


USA 00000001 CompanyBaker Distributors BAKER . . .

ID NAME1
COUNTRY
Header Line

82
Internal Table with Header Line

1 EMPLOYEE

COUNTRY ID FORMA NAME1 SORTL . . .


USA 00000001 CompanyBaker Distributors BAKER . . .

2
ID NAME1 COUNTRY
00000001 Baker Distributors USA Header Line

83
Internal Table with Header Line

1 EMPLOYEE

COUNTRY ID FORMA NAME1 SORTL . . .

USA 00000001 Company Baker Distributors BAKER . . .

2
ID NAME1 COUNTRY
00000001 Baker Distributors USA Header Line

3 00000001 Baker Distributors USA 1


This header line
2 is attached to
the body of the
3. internal table.
. .
. .
.
10
84
Internal Table with Header Line
4 EMPLOYEE

COUNTRY ID FORMA NAME1 SORTL . . .


USA 00000002 Company Diversified Indust.. DIVERS . . .

5 ID NAME1
COUNTRY
00000002 Diversified Indust... USA Header Line

00000001 Baker Distributors USA 1


6 2
00000002 Diversified Indust... USA
3.
. .
. .
.
10
85
Creating an Internal Table without a
Header Line
The TYPES statement defines
REPORT Y170DM40. the structure and data type
TABLES: EMPLOYEE. for the internal table and its
TYPES: BEGIN OF EMP, work area statement with an
The DATA
ID LIKE EMPLOYEE-ID, INITIAL SIZE creates the
NAME1 LIKE EMPLOYEE-NAME1, actual internal table without
COUNTRY LIKE EMPLOYEE-COUNTRY,
a header line. The DATA
END OF EMP.
statement without the
INITIAL SIZE creates the
DATA: EMPTAB TYPE STANDARD TABLE
work area for the internal
OF EMP INITIAL SIZE 10,
table.
EMPTAB_WA TYPE EMP.
Work Area
SELECT * FROM EMPLOYEE. ID NAME1 COUNTRY
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB_WA.
APPEND EMPTAB_WA TO EMPTAB.
ENDSELECT.

86
APPEND <work area> to <EMPTAB>.
Internal Table without a Header
Line WHY???

Separate Internal Table Work Area

Performance Issues

Nested Internal Tables

87
Internal Table without a Header
Line

EMPLOYEE

A COUNTRY ID FORMA NAME1 SORTL . . .

ID NAME1
COUNTRY
B Work Area

88
Internal Table without a Header
Line
1 EMPLOYEE

COUNTRY ID FORMA NAME1 SORT . . .


USA 00000001 Company Baker Distributors BAKER . . .
ID NAME1
2 COUNTRY
00000001 Baker Distributors USA Work Area

ID NAME1
COUNTRY
3 00000001 Baker Distributors USA 1 This work
area is not
2 attached to the

3. body of the
internal table.
.
.
10
89
Transferring ABAP Dictionary
Table Structures

REPORT Y170DM41.
TABLES: EMPLOYEE.
DATA: EMPTAB LIKE STANDARD TABLE OF
EMPLOYEE INITIAL SIZE 10 WITH HEADER LINE.
The internal table EMPTAB
will have the exact same
SELECT * FROM EMPLOYEE.
structure as the dictionary
MOVE EMPLOYEE TO EMPTAB. table EMPLOYEE.
APPEND EMPTAB.
ENDSELECT.

Notice the MOVE statement


instead of a MOVE-
CORRESPONDING.

90
Automatic Field Conversion

• MOVE-CORRESPONDING or MOVE field to


field
– Individual field type conversion
• MOVE
– Structure to structure
– Field to structure
– Structure to field
• Intermediate C type
• Followed by adoption of new types

91
Mass Reading from Database Tables
into Internal Tables

REPORT Y170DM69. SELECT * FROM


<table> . . .
TABLES: EMPLOYEE. 1. INTO TABLE
<EMPTAB>.
DATA: EMPTAB LIKE STANDARD TABLE
2. APPENDING TABLE
EMPLOYEE INITIAL SIZE 10 WITH HEADER LINE.
<EMPTAB>.

SELECT * FROM EMPLOYEE INTO TABLE EMPTAB


WHERE COUNTRY = ‘USA’. Notice no ENDSELECT is
needed here because no
loop processing occurs.

92
Processing an Internal Table
REPORT Y170DM45.
TABLES: EMPLOYEE.
This LOOP AT <EMPTAB>
TYPES: BEGIN OF EMP, statement allows for a logical
COUNTRY LIKE EMPLOYEE-COUNTRY, expression in a WHERE clause to
NAME1 LIKE EMPLOYEE-NAME1, limit the processing of the internal
SALES LIKE EMPLOYEE-SALES,
table.
END OF EMP.
DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE
10 WITH HEADER LINE.
SELECT * FROM EMPLOYEE.
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
APPEND EMPTAB.
ENDSELECT. If no internal table entries
LOOP AT EMPTAB WHERE COUNTRY BETWEEN ‘A’ AND ‘D’. qualify under the logical
WRITE: / EMPTAB-COUNTRY, EMPTAB-NAME1,
expression, the statement
EMPTAB-SALES. within the loop is not
ENDLOOP. executed and SY-SUBRC is
IF SY-SUBRC NE 0. WRITE: / ‘NO ENTRIES’. ENDIF. set to 4.

93
System Field SY-TABIX

REPORT Y170DM46.
TABLES: EMPLOYEE.

TYPES: BEGIN OF EMP,


COUNTRY LIKE EMPLOYEE-COUNTRY,
NAME1 LIKE EMPLOYEE-NAME1,
END OF EMP.
DATA: EMPTAB TYPE STANDARD TABLE OF EMP
INITIAL SIZE 10 WITH HEADER LINE.

PARAMETERS: START LIKE SY-TABIX DEFAULT 10, screen output


END LIKE SY-TABIX DEFAULT 20.
SELECT * FROM EMPLOYEE.
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
APPEND EMPTAB.
ENDSELECT.
SY-
LOOP AT EMPTAB FROM START TO END. TABIX
WRITE: / SY-TABIX, EMPTAB-COUNTRY, EMPTAB-NAME1.
ENDLOOP.

94
Accumulating Data within an
Internal Table
REPORT Y170DM43.
TABLES: EMPLOYEE. COLLECT <EMPTAB>.
TYPES: BEGIN OF EMP, Country Sales
COUNTRY LIKE EMPLOYEE-COUNTRY, Header
D 400,000
SALES LIKE EMPLOYEE-SALES, Line
USA 1,000,000
END OF EMP.
DATA: EMPTAB TYPE STANDARD TABLE OF EMP GB 500,000
INITIAL SIZE 10 WITH HEADER LINE. D 7,800,000

SELECT * FROM EMPLOYEE. screen output


MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. A 371,065.00
COLLECT EMPTAB. CH 45,305.00
ENDSELECT. D 8,200,000.00
LOOP AT EMPTAB. F 0.00
WRITE: / EMPTAB-COUNTRY, EMPTAB-SALES. GB 500,000.00
ENDLOOP. NL 577,000.00
NO 234.00
USA 1,000,000.00
95 HK 0.00
Sorting an Internal Table
REPORT Y170DM44.
TABLES: EMPLOYEE. Sorting options:
TYPES: BEGIN OF EMP,
1) SORT <EMPTAB> - sorts the
COUNTRY LIKE EMPLOYEE-COUNTRY,
entries of the internal table
NAME1 LIKE EMPLOYEE-NAME1,
<EMPTAB> in ascending
SALES LIKE EMPLOYEE-SALES, order.
END OF EMP.
2) SORT <EMPTAB> BY
DATA: EMPTAB TYPE STANDARD TABLE OF EMP
INITIAL SIZE 10 WITH HEADER LINE.
<field> - sorts the table on
SELECT * FROM EMPLOYEE.
one or more fields within the
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
table.
APPEND EMPTAB.
ENDSELECT.
SORT EMPTAB BY SALES DESCENDING.
LOOP AT EMPTAB. screen output
WRITE: / ITAB-COUNTRY, ITAB-NAME1, ITAB-SALES.
ENDLOOP.

96
Control Level Processing

• AT FIRST
• AT NEW < field >
• AT END < field >
• AT LAST

97
Reading a Single Table Entry

READ TABLE <EMPTAB> options:


1) READ TABLE <EMPTAB>.
2) READ TABLE <EMPTAB> WITH KEY <k1> = <v1>…
<kn> = <vn>.
3) READ TABLE <EMPTAB> WITH TABLE KEY <k1> = <v1> ...
<kn> = <vn>.
4) READ TABLE <EMPTAB> WITH KEY = <value>.
5) READ TABLE <EMPTAB> WITH KEY . . . BINARY SEARCH.
6) READ TABLE <EMPTAB> INDEX <i>.
7) READ TABLE <EMPTAB> COMPARING <f1> <f2> . . . .
8) READ TABLE <EMPTAB> COMPARING ALL FIELDS.
9) READ TABLE <EMPTAB> TRANSPORTING <f1> <f2> . . . .
10) READ TABLE <EMPTAB> TRANSPORTING NO FIELDS.

98
Maintaining Internal Tables
SELECT * FROM EMPLOYEE.
MOVE-CORRESPONDING EMPLOYEE TO
EMPTAB.
APPEND EMPTAB. INSERT <EMPTAB> INDEX <i>.
ENDSELECT. MODIFY <EMPTAB> INDEX <i>.
DELETE <EMPTAB> INDEX <i>.
READ TABLE EMPTAB INDEX 1.
MOVE ‘ABC’ TO EMPTAB-NAME1.
MODIFY EMPTAB INDEX SY-TABIX.
IF SY-SUBRC NE 0.
WRITE / ‘Attempt to modify failed.’.
ELSE.
Check SY-SUBRC after
WRITE: / EMPTAB-COUNTRY, EMPTAB-
NAME1. every attempt to change
ENDIF. an internal table entry.
INSERT EMPTAB INDEX 1.
DELETE EMPTAB INDEX SY-TABIX.

99
Working with an Internal Table
without a Header Line

APPEND <work area> TO <internal table>.

COLLECT <work area> INTO <internal table>.

INSERT <work area> INTO <internal table>.

MODIFY <internal table> FROM <work area>.

READ TABLE <internal table> INTO <work area>.

LOOP AT <internal table> INTO <work area>.


100
Deleting an Internal Table

CLEAR <internal table>


• Initialises the header
line.
REFRESH <internal table>
• Internal table lines • Deletes all
remain unchanged. table lines. FREE <internal table>
• Storage space
• Deletes all
is not released. table lines.
• Paging is released. • Storage space
is released.
• Header line
• Header line
remains unchanged.
remains unchanged.

101
Information about an Internal Table
REPORT Y170DM49.
TABLES: EMPLOYEE.
TYPES: BEGIN OF EMP,
COUNTRY LIKE EMPLOYEE-COUNTRY,
NAME1 LIKE EMPLOYEE-NAME1,
END OF EMP,
DATA: EMPTAB TYPE STANDARD TABLE OF EMP
INITIAL SIZE 10 WITH HEADER LINE,
LINE_COUNT TYPE I,
INITIAL_COUNT TYPE I. DESCRIBE TABLE <internal table>
SELECT * FROM EMPLOYEE. LINES <var1>
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
APPEND EMPTAB.
OCCURS <var2>.
ENDSELECT.
DESCRIBE TABLE EMPTAB
LINES LINE_COUNT
OCCURS INITIAL_COUNT.
WRITE: / ‘ lines:’, LINE_COUNT,
/ ‘occurs:’, INITIAL SIZE_COUNT.
screen output

102
Calling the SAP Table Editor
REPORT Y170DM50.
TABLES: EMPLOYEE.
TYPES: BEGIN OF EMP,
COUNTRY LIKE EMPLOYEE-COUNTRY,
NAME1 LIKE EMPLOYEE-NAME1,
END OF EMP,
DATA: EMPTAB TYPE STANDARD TABLE OF EMP
INITIAL SIZE 10 WITH HEADER LINE,
SELECT * FROM EMPLOYEE.
MOVE-CORRESPONDING EMPLOYEE TO EMPTAB.
APPEND EMPTAB.
ENDSELECT.
EDITOR-CALL FOR EMPTAB.
CHECK SY-SUBRC EQ 0.
LOOP AT EMPTAB WHERE NAME1 EQ ‘Maurice Cheeks’.
WRITE: / EMPTAB-COUNTRY, EMPTAB-NAME1. screen output
ENDLOOP.
IF SY-SUBRC NE 0. WRITE: / ‘No records.’. ENDIF.

103
What Are Subroutines

REPORT YDEMOSB7. REPORT YDEMOSB8.

Calculate tax Call calculate_tax

Calculate tax Call calculate_tax

Subroutine
Calculate_tax

104
Modularization

REPORT YDEMOSB1. REPORT YDEMOSB2. REPORT YDEMOSB3.


Perform sub
Call Function ZZCALC
Perform sub(YDEMOSB1)
Form sub

External FunctionModule
Call Call
REPORT YDEMOSB1. ABAP Function Builder
Function module
Form sub ZZCALC

105
Actual / Formal Parameters

Main 99 1
Program a1 a2 a3
Call Calculate_tax
Transfer values of fields a1 a2
Get value of field a3
Actual parameters a1 a2 a3

Parameter transfer

o u tine Formal parameters f1 f2 f3


Su b r
Subroutine calculate_tax
99 1
f1 f2 f3
f3 = f1 +f2 . . . .
106
Methods of Passing Parameters

Pass by Value a1

b ro u tine
Su
Pass by Value and Result
f1
a1
Subro
utine

Pass by Reference a1 f1

b ro u tine
Su
f1

107
Declaring and Calling a Subroutine -
Pass by Value(1) & Reference(2)
REPORT Y170D091.
TABLES: ....
DATA: .…
.
.
.
PERFORM <name> USING
<a1> <a2>
<a3> <a4>.
.
.
.
FORM <name> USING
VALUE(<f1>) Pass by value
VALUE(<f2>)
Pass <f3>
by reference
<f4>.

ENDFORM.

108
Declaring and Calling a Subroutine -
Pass by Value and Result(3)
REPORT YSDEM000.
TABLES: ... .
DATA: ... .
.
.
.
PERFORM <name> USING
<a1> <a2>
CHANGING<a3>.
.
.
.
FORM <name> USING
VALUE(<f1>)
VALUE(<f2>)
CHANGING VALUE(<f3>).
.
.
Pass by value
.
f 3 =“A”.
.
Pass by value and result
.
.
ENDFORM.

109
Global versus Local Data
report y170dm86.

data: num(9) value ‘999999999’.

data: id like tabna-id, Global Data


name like tabna-name1.
. . . <statements>
perform sub1.
. . . <statements>

Local Data
* ------------------------------------------------------------------------------------------------------
* FORM SUB1 *
* ---------------------------------------------------------------------------------------------------------------------------
form sub1.
data: begin of tab occurs 10, “ <----------- local data
id like tabna-id,
name1 like tabna-name1,
end of tab.
local: num . “ <----------- local data
. . . <statements>
endform.
110
Local Data in Subroutines
Statement Value Upon Entering Value Upon Value Upon Entering
between Subroutine First Time Returning to Subroutine Next
FORM… Main Program Time
ENDFORM
DATA Whatever the local If declared Re-initializes based
DATA statement globally, returns on local DATA
initializes to old value, statement
otherwise not
recognized

STATICS Whatever the local If declared Last set value from


STATICS statement globally, returns inside subroutine
initializes to old value,
otherwise not
recognized

LOCAL Last set value from Last set value Last set value from
main program from main main program
program
111
Passing Structures as Parameters

This is passing the TABNA


REPORT Y170D095.
work area only
TABLES: TABNA.
DATA: ZTAB LIKE TABNA.
DATA: FLAG.
.
.
PERFORM SUB1 USING TABNA. This is passing the
PERFORM SUB1 USING ZTAB. ZTAB structure
.
.
.
FORM SUB1 USING
REC STRUCTURE TABNA.
WRITE: / REC-COUNTRY,
REC-NAME1.

ENDFORM.
112
Passing Internal Tables as
Parameters
REPORT Y170D093.
DATA : BEGIN OF TAB OCCURS 10,
F1 LIKE TABNA-COUNTRY,
F2 LIKE TABNA-NAME1,
.
.
.
END OF TAB.
DATA : X.
.
.
.
PERFORM SUB1 TABLES TAB
. USING X.
.
.
FORM SUB1 TABLES FRED STRUCTURE TAB
USING Z.
LOOP AT FRED.
WRITE: / FRED-F1
FRED-F2.
ENDLOOP.
ENDFORM .
113
External Subroutines

PERFORM <name>(<prog name>) USING . . .

REPORT Y170D096. REPORT Y170D097.


TABLES : TABNA, TABLES : TABNA,
T001, T005. T001, T001G.
. . Roll Area
. .
. . TABNA
START-OF-SELECTION. START-OF-SELECTION T001
. . T005
. .
. . T001G
PERFORM FORM SUB1 . . . . Y170D108
SUB1(Y170D097) . . . . .
Y170D109
. .
. .
. NEW-PAGE. Storage Allocation
.
.
114 .
ENDFORM
Function Modules

Function Builder

FM Group : FIBU
FM_01 ...
Program 1 FM_02 ... Program 2
FM Group : XYZ
CALL FM_03 ... CALL
FUNCTION FM_04 ... FUNCTION
‘FM_0’ ‘FM_02’
... Program 3 ...

CALL FUNCTION
‘FM_02’
115
...
Function Module Parts

FM -02
Section I … Administration FM Group :
Section II … Interface
FIBU
FM_01 ...
Chapter 1 … Import
Chapter 2 … Changing
FM_02 ...
Chapter 3 … Export
Chapter 4 … Tables
Chapter 5 … Exceptions

Section III … Documentation


FM Group :
XYZ
FM_03 ...
Section IV … Source Code
FM_04 ...
Section V … Global Data

Section VI … Main Program

116
Creating a Function Group

117
Administration

118
Interfaces
Program XYZ.

Call function
‘Y_DEMO_FUNC’
Import
Changing
Export
Tables
Exceptions Function Module
Y_DEMO_FUNC

119
Import/Export Parameter Interface

Parameter name Default value Flag parameter


as optional

‘LIKE’
Pass parameter
‘TYPE’ by reference

120
Table Parameters/Exceptions
Interface & Documentation
Parameter name Flag parameter
as optional

‘LIKE’ ‘TYPE’

121
Function Module Source Code
function y_demo_function_module.
*”--------------------------------------------------------------------------------------------------
*” Local interface:
*” IMPORTING
*” REFERENCE(FIELD1) LIKE TABNA-COUNTRY
*” EXPORTING
*” VALUE(FIELD3) LIKE TABNA-NAME1
*” TABLES
*” TAB STRUCTURE TABNA
*” CHANGING
*” VALUE(FIELD2) LIKE TABNA-ID
*” EXCEPTIONS
*” INVALID_DATA
*” SYSTEM_ERROR
*” -------------------------------------------------------------------------------------------------
endfunction.
122
Exceptions

INVALID_OPERATOR

Function Module

...

IF...
RAISE INVALID_OPERATOR.
* MESSAGE. . . RAISING
INVALID_OPERATOR.
ENDIF.
...
123
Example - Raising Exceptions

case operator.
when ’+’.
result = operand1 + operand2.
when ’-’.
result = operand1 - operand2.
when ’/’.
if operand2 <> 0.
result = operand1 / operand2.
else.
raise division_by_zero.
endif.
when ’* ’
result = operand1* operand2.
when others.
raise invalid_operator.
endcase.
124
Calling a Function Module
report ymodemo message-id yj.
parameters: operand1 type i,
operator,
operand2 like operand1.
data: result type p decimals 2.
call function ’Y_CALCULATOR’
exporting
operand1 = operand1
operator = operator
operand2 = operand2
importing
result = result
exceptions
invalid_operator = 1
division_by_zero = 2
others = 3.
125
Calling a Function Module
(Continued)

exceptions
invalid_operator = 1
division_by_zero = 2
others = 3.

case sy-subrc.
when 1.
message e001.
when 2.
message e005.
when 3.
message e007.
endcase.

126
Program Organisation

SAPL <gr>
L<gr>TOP
*System-defined include files
FUNCTION-POOL <gr>
INCLUDE L<gr>TOP. Message-ID ZZ.
INCLUDE L<gr>UXX DATA: “Global DATA
*User-defined include files

L<gr>UXX
INCLUDE L<gr> U01.
L<gr>U01 INCLUDE L<gr> U02.
FUNCTION FA. .
.
L<gr>U02 .
FUNCTION FB.

127
Subroutine Includes for Function
Groups
Main Program

• System-defined include files INCLUDE L<gr> TOP.’ Global Data


• User defined include files INCLUDE L<gr> F01.’ Subroutines

ABAP program L<gr> F01 Call


FORM SUB1 USING . . . . FUNCTION . . .
. .
. .
. .
ENDFORM. PERFORM SUB1 USING . . .
FORM SUB2 USING . . . . .
. .
. .
. ENDFUNCTION.
ENDFORM.
.
.
128
.
Global Data / Local Memory in the
Function Group
Global Data

L <gr> TOP
FUNCTION-POOL <gr>.
DATA: X
TABLES: . . .

Program Subroutines
FUNCTION . . . L <gr> F01
DATA: . . . FORM SUB1 USING...
MOVE X TO . . . DATA: . . .
ENDFUNCTION. MOVE. . . TO X.
ENDFORM.

129
Test Environment

Import parameters Tables

FM: Y170 DEMO


Does it work?

Export Parameters

130
Remote Function Call (RFC)

Program
ABAP \/4
CALL FUNCTION. . .
DESTINATION. . .
EXPORTING. . . Function
Function Module
Module
IMPORTING. . .
TABLES. . . FUNCTION REMOTE_CALL
EXCEPTIONS. . . ...
RAISE ERROR.
...
ENDFUNCTION.

External program
RFCLid
External Program. . .
RfcOpen (. . .)
RfcCallReceive (. . .)
RfcClose (. . .)
131
Modularization:
The Include Technique

132
SQL (SELECT)

ABAP Programs

REPORT: YNEWAPPL. Database


TABLES...
TABNA
SELECT * FROM TABNA.
LFA1 LFC1
ENDSELECT.
Data

ABAP
Reports

133
WHERE Clause: Single Access
*& *
* & ------------------------------------------------------------------------------------------
*
In the return-code field
report y170dm64. (SY-SUBRC),
0 = successful and
4 = entry does not exist.
tables: tabna.

* Syntax of a select single


* statement for single access. ----------
select single
* from tabna The SELECT SINGLE* statement
where country eq ’D’ requires the full primary key of the
and id eq ’00000002’.
table in the WHERE clause.

if sy-subrc = 0.
write: tabna-country, tabna-id,
tabna-name1.
endif.
134
Syntax: Restricted Loop Processing

SELECT * FROM <table>


WHERE <table field 1> <relational operator> <field 1>
AND <table field 2> <relational operator> <field 2>
OR <table field 3> <relational operator> <field 3>
AND <table field 4> <relational operator> <field 4>
:
:
OR <table field n> <relational operator> <field n>.

ENDSELECT. EQ =
GE >= =>
LE <= =<
NE <> >< Relational
GT > Operators
LT <
135
Syntax: Between Values,
Templates and Lists

SELECT * FROM <table> WHERE <table field>...

BETWEEN <field 1> AND <field 2>

LIKE <with ‘%’ and ‘_’ masked literal>

IN (<field 1, field 2,......field n>)

136
WHERE Clause: Loop Processing
with Restricted Selection

report y170md65.

tables: tabna.
* The result of the select statement is limited by the conditions of
* the where clause.
The result set is limited by the
select * from tabna
where country eq ‘USA’
conditions in the
and id between ‘0000001’ WHERE clause.
and ‘0000002’ .
write: / tabna-country, tabna-id.
tabna-name1.
endselect.
if sy-subrc ne 0.
write: / ‘The conditions cannot be satisfied’.
endif.

137
LIKE: Example of a Template (%_)

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

report y170dm66.
The ‘_’ is an any character
tables: t001.
positional parameter.
* Using a template during selection.-----------------------------------------------
The ‘%’ allows for any string
of any length.
select* from t001
where bukrs like ‘__01’
and butxt like ‘SAP%’.
write: / t001-bukrs, t001-butxt.
endselect.
if sy-subrc ne 0.
write: / ‘The conditions cannot be satisfied’.
endif.

*
138
IN: Example of a Comparison
Value List

tables: tabna.

parameters: country1 like tabna-country.


country2 like tabna-country.

select* from tabna


where country in (country1, country2).

* where country = country1 or country = country2.


½
write:
/ tabna-country, tabna-id,
tabna-name1.
endselect.

if sy-subrc ne 0.
write: / ‘The conditions cannot be satisfied’.
endif.

139
IN: Example of a Range
tables: lfa1.
data: begin of tab occurs 10. This internal table is the same one
sign (1), that is created automatically when
option (2),
a selection screen is processed. The
low like lfa1-lifnr,
high like lfa1-lifnr, RANGES statement builds the
end of tab. structure of the table
move:‘I’ to tab-sign, automatically.
‘BT’ to tab-option, RANGES <name> FOR <field>.
‘0000000001’ to tab-low,
‘9999999999’ to tab-high.
append tab. DATA: BEGIN OF <name>
select from lfa1 OCCURS <n>,
tables: lfa1.
where lifnr in tab. SIGN(1),
Ranges: tab for lfa1-lifnr.
write: / lfa1-lifnr, lfa1-name1. OPTION(2),
move:‘I’ to tab-sign,
endselect. LOW LIKE <field>,
‘BT’ to tab-option,
HIGH LIKE <field>,
‘0000000001’ toEND
tab-low,
OF <name>.
‘9999999999’ to tab-high.
append tab.
select* from lfa1
where lifnr in tab.
write: / lfa1-lifnr, lfa1-name1.
140 endselect.
The ORDER BY Clause
SELECT * FROM <table>

WHERE <condition>
½*&-----------------------------------------------------------------------------------------------
*
*& Report Y170DM71 ORDER * BY <table field 1>
*& <table* field 2>
*&-----------------------------------------------------------------------------------------------
<table* field 3>
*& : *
*& *
:
*&-----------------------------------------------------------------------------------------------
*
<table field n>.
report y170dm71.
PRIMARY KEY.
tables: lfa1.
ENDSELECT.
* Notice the order by clause below.----------------------------------------------
*
select* from lfa1
order by name1.
write: / lfa1-lifnr, lfa1-name1.
endselect.

141
The SELECT DISTINCT Statement

REPORT Y170DM72.

TABLES: TABNA.

DATA: CNTRY LIKE TABNA-COUNTRY.

SELECT DISTINCT COUNTRY


FROM TABNA INTO (CNTRY).
Using SELECT
WRITE: / CNTRY.
DISTINCT, it
ENDSELECT.
is possible
to eliminate
duplicate rows
from the
result set.
142
SELECT Using Aggregate Functions

REPORT Y170DM73.
TABLES: TABNA.
DATA: TOTAL TYPE I,
MAX_SALES LIKE TABNA-SALES,
AVG_SALES LIKE TABNA-SALES,
MIN_SALES LIKE TABNA-SALES.

SELECT COUNT( DISTINCT COUNTRY )


MAX( SALES )
AVG( SALES )
MIN( SALES )
FROM TABNA
INTO (TOTAL, MAX_SALES, AVG_SALES, MIN_SALES)
WHERE COUNTRY <> SPACE.

WRITE: / ‘Table TABNA Statistics’,


/ TOTAL, ‘Different Countries’,
/8 MIN_SALES, ‘Lowest Sales’,
/8 AVG_SALES, ‘Average Sales’,
/8 MAX_SALES, ‘Highest Sales’.

143
The Dynamic WHERE Clause
The parameters
REPORT Y170DM74. entered make up the
TABLES: TABNA. contents of the
PARAMETERS:
WHERE clause. The
WHERECL1(72) DEFAULT ‘COUNTRY = ‘ ‘USA’ ’ ’,
WHERECL2(3) DEFAULT ‘OR’, user has the option of
WHERECL3(72) DEFAULT ‘COUNTRY = ‘ ‘GB’ ’ ’.changing the
TYPE: BEGIN OF ITAB_RECORD, TEXT(72), conditions and
END OF ITAB_RECORD. dynamically effecting
DATA: WHERE_ITAB TYPE STANDARD TABLE OF
ITAB_RECORD INITIAL SIZE 3 WITH HEADER which way the
LINE. program will execute.
An internal table is created
WHERE_ITAB-TEXT = WHERECL1.
APPEND WHERE_ITAB.
which holds the WHERE
WHERE_ITAB-TEXT = WHERECL2. clause until it is used in the
APPEND WHERE_ITAB. SELECT statement.
WHERE_ITAB-TEXT = WHERECL3.
APPEND WHERE_ITAB.

SELECT * FROM TABNA WHERE (WHERE_ITAB).


WRITE: / TABNA-COUNTRY, TABNA-ID.
144 ENDSELECT.
CONCATENATE Statement
REPORT Y170DM74. CONCATENATE <source field 1>
TABLES: TABNA. <source field 2>
PARAMETERS: <source field 3>
:
WHERECL1(72) DEFAULT ‘COUNTRY = ‘ ‘USA’: ’ ’,
WHERECL2(3) DEFAULT ‘OR’, <source field n>
WHERECL3(72) DEFAULT ‘COUNTRYINTO
= ‘ ‘GB’ ’<target
’. field>
SEPARATED BY <constant>.

TYPE: BEGIN OF ITAB_RECORD,


TEXT(72),
END OF ITAB_RECORD.

DATA: WHERE_ITAB TYPE STANDARD TABLE OF


ITAB_RECORD INITIAL SIZE 3 WITH HEADER LINE.

CONCATENATE WHERECL1 WHERECL2 WHERECL3


INTO WHERE_ITAB-TEXT SEPARATED BY SPACE.

APPEND WHERE_ITAB.

SELECT * FROM TABNA WHERE (WHERE_ITAB).


WRITE: / TABNA-COUNTRY, TABNA-ID.
ENDSELECT.
145
Variations on the INTO Clause

SELECT * FROM <dbtable>


REPORT Y170DM75. INTO TABLE <internal table>
PACKAGE SIZE <n>.
TABLES: TABNA. ENDSELECT.

DATA: ITAB LIKE STANDARD TABLE OF


TABNA INITIAL SIZE 5 WITH HEADER LINE.

SELECT * FROM TABNA


INTO TABLE ITAB
PACKAGE SIZE 5.

LOOP AT ITAB.
WRITE: / ITAB-COUNTRY, ITAB-ID.
ENDLOOP.

146
ENDSELECT.
Specifying the Table Name at
Runtime

REPORT Y170DM76.

PARAMETERS: TAB_NAME(5) DEFAULT ‘TABNA’.

DATA: TABLE_LINE(240).

SELECT * FROM (TAB_NAME) INTO TABLE_LINE.

WRITE: / TABLE_LINE.

ENDSELECT.

147
Joins: Why We Should Use Them
• Joins are more efficient than logical databases and nested selects.
• They access multiple tables with one select statement.

148
Inner Joins

SCARR SFLIGHT

149
Inner Joins Syntax
SELECT <table1~field1 table1~field2
table2~field3. . . >
INTO (<target >)
FROM <table1 > INNER JOIN <table2 >

ON <table1~keyfield1 > = <table2~keyfield1 >


AND <table1~keyfield2 > =
<table2~keyfield2 >
AND . . .
WHERE . . .
ENDSELECT.

150
The Driving table
SELECT scarr~carrname sflight~carrid sflight~connid
sflight~fldate
INTO (carrid, connid, date, carrname)
FROM scarr INNER JOIN sflight
ON scarr~carrid = sflight~carrid.
WRITE: / carrid, connid, date, carrname.
ENDSELECT.

151
Left Outer Joins
SCARR SFLIGHT

152
Left Outer Join Syntax
SELECT <table1~field1 table1~field2
table2~field3. . . >
INTO (<target >)
FROM <table1 > LEFT OUTER JOIN <table2 >

ON <table1~keyfield1 > = <table2~keyfield1 >


AND <table1~keyfield2 > =
<table2~keyfield2 >
AND . . .
WHERE . . .
ENDSELECT.

153
Open SQL Syntax Restrictions
The syntax for joins have been given certain restrictions in order to insure that they
produce the same results for all SAP supported databases.

154
Redundancy

LFA1 BSIK

155
Joins Accessing More than Two
Tables
SELECT <table1~field1 table1~field2 table2~field3. . .
>
INTO (<target >)
FROM (<table1 > INNER JOIN <table2 >
ON <table1~keyfield1 > = <table2~keyfield1 >
AND <table1~keyfield2 > = <table2~keyfield2 >
AND . . .)
INNER JOIN <table3 >
ON <table1~keyfield > = <table3~keyfield >
AND . . .
WHERE . . .
ENDSELECT.
156
Aliases

SELECT A~carrname
B~carrid
B~connid
B~fldate
INTO (carrid, connid, date, carrname)
FROM scarr AS A INNER JOIN sflight AS B
ON scarr~carrid = sflight~carrid.
WRITE: / carrid, connid, date, carrname.
ENDSELECT.

157
Subquery

SCARR SFLIGHT

Which airlines are not found in the sflight table?

158
Subquery Syntax/Example

SELECT * FROM scarr


WHERE NOT carrid IN
( SELECT carrid FROM sflight ).
WRITE:/ scarr-carrid, scarr-carrname.
ENDSELECT.

159
Having Clause

List all Luftansa CONNIDs where the sum of


LUGGWEIGHT is < 20,000.

160
Having Clause Syntax/Example

SELECT carrid connid COUNT( *) SUM( luggweight )


INTO (carrid, connid, count, sum_weight) FROM sbook
WHERE carrid = 'LH'
GROUP BY carrid connid
HAVING SUM( luggweight ) > 25.
WRITE:/ carrid, connid, count, sum_weight.
ENDSELECT.

161
Authority Objects in SAP

162
The AUTHORITY-CHECK Statement

AUTHORITY-CHECK OBJECT ‘S_DEVELOP’


ID ‘DEVCLASS’ FIELD ‘YLJS’
ID ‘OBJTYPE’ DUMMY
ID ‘OBJNAME’ DUMMY
ID ‘P_GROUP’ DUMMY
ID ‘ACTVT’ DUMMY.

The AUTHORITY-CHECK The option DUMMY


lists the fields to be checked and suppresses the check for
verifies what the user is the specified field. The net
attempting to do against what effect is that the user can
the user is authorised to do. perform any activity on
development class YLJS.
163
Reacting to the AUTHORITY-
CHECK Statement

AUTHORITY-CHECK OBJECT ‘S_DEVELOP’


ID ‘DEVCLASS’ FIELD ‘YLJS’
ID ‘OBJTYPE’ DUMMY
ID ‘OBJNAME’ DUMMY
ID ‘P_GROUP’ DUMMY
ID ‘ACTVT’ DUMMY.
IF SY-SUBRC <> 0.
WRITE: / ‘You are not authorised to development’,
‘class YLJS.’.
EXIT.
ENDIF.

164
Nested SELECT Loops
TABLES: KNA1, KNB1, BSID.
SELECT * FROM KNA1.
WRITE: / KNA1-KUNNR, KNA1-NAME1.
SELECT * FROM KNB1
WHERE KUNNR = KNA1-KUNNR.
WRITE: / ' ', KNB1-BUKRS.
SELECT * FROM BSID
WHERE KUNNR = KNB1-KUNNR
AND BUKRS = KNB1-BUKRS.
WRITE: / ' ', BSID-BELNR, BSID-BUDAT, BSID-DMBTR.
ENDSELECT.
ENDSELECT.
ULINE.
ENDSELECT.

165
Logical Database Programs

Logical Database Program

CT
SELE ECT
SEL ECT
SEL LECT
E
ENDS CT
D S ELE
EN
S EL ECT
END
Security
Checks
166
Event-Driven Programming

START-OF-SELECTION.
GET <table>.
GET <table> LATE.
END-OF-SELECTION.

167
Attaching Code to an Event

Event

168
The START-OF-SELECTION Event

169
The GET Event

170
The GET LATE Event

171
Behaviour of a Logical
Database Program

Logical Database Program

EL ECT
S CT
SELE CT
SELE LECT
E
ENDS ECT
N D S EL
E CT
E L E
Security ENDS
Checks
172
Selection Screens with Logical
Database Programs

173
The END-OF-SELECTION Event

174
Selection Screens

175
The SELECT-OPTIONS Statement

SELECT-OPTIONS <selection name> FOR <field name>


[DEFAULT <value> [TO <value>]]

???

176
Selection Tables

SIGN OPTION LOW HIGH

I BT 3 10

I EQ 1

E GE 7

177
Multi-Row Selection Tables

Click Here
To get Here

178
Creating User-Friendly Selection
Texts

Maintain Text
Elements

Selection Screen

179
Creating Parameters as Radio
Buttons
TABLES: KNA1
SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME
TITLE TEXT-001.
PARAMETERS: ONE_TIME RADIOBUTTON GROUP GP1,
REGULAR RADIOBUTTON GROUP GP1,
BOTH RADIOBUTTON GROUP GP1
DEFAULT ‘X’.
SELECTION-SCREEN END OF BLOCK B1.
IF ONE_TIME = ‘X’.
PERFORM WRITE_ONE_TIME_CUST.
ELSEIF REGULAR = ‘X’.
PERFORM WRITE_REG_CUST.
ELSE.
PERFORM WRITE_CUST.
ENDIF.

180
Attaching Matchcodes to
Parameters
PARAMETERS: CUSTNO LIKE KNA1-KUNNR
MATCHCODE OBJECT DEBI.

181
Formatting the Selection Screen

SELECTION-SCREEN <option>.

SELECTION-SCREEN SKIP <n>.

SELECTION-SCREEN ULINE [ [/]<pos(len)>].

SELECTION-SCREEN COMMENT [/]<pos(len)> <name> [FOR FIELD <f>].

SELECTION-SCREEN BEGIN OF LINE.


:
:
SELECTION-SCREEN END OF LINE.

SELECTION-SCREEN POSITION <pos>.


182
User Message

183
Error Message at the Selection
Screen

Using the AT SELECTION-SCREEN


event, access to the output can be
prevented until valid data is
entered on the selection screen
AT SELECTION-SCREEN.
AUTHORITY-CHECK OBJECT ‘F_KNA1_BUK’
ID ‘ACTVT’ DUMMY
ID ‘BUKRS’ FIELD BUKRS.
IF SY-SUBRC <> 0.
MESSAGE E000 WITH BUKRS.
ENDIF. The selection screen is
continuously redisplayed until
valid data is entered or the
program is terminated

184
Table T100: Messages

185
Table T100: Messages

REPORT <report name> MESSAGE-ID <message-ID>.

MESSAGE <type><number> [WITH <up to four variables>].

Example
MESSAGE E001 WITH KNA1-KUNNR KNA1-BUKRS.

Message Types
A Abend
E Error
I Information
S Success
W Warning

186
Creating Message IDs and
Messages
1. Double-click on the newly
entered Message ID.

REPORT Z1_KB MESSAGE-ID zkb. 2. After being prompted


to create the message class,
3. After maintaining the message the Maintain Message
class and clicking on the Class screen appears.
MESSAGE tab, the Maintain
Message screen appears.

187
The Online Debugging Tool

188
The Online Debugging Display
Execution control
buttons. Click to display
current statement.

Source Code The program and the


event the debugger is processing.

189
Online Debugging Display Modes
Use these buttons
to page through
the code

Online debugging
navigation buttons

190
Displaying Field Contents

Buttons for
hexadecimal display

Area for watch variables. These are user chosen variables that can
be monitored as they change value during execution.

191
Displaying the Contents of an
Internal Table

Contents of
internal table

192
Replacing Field Values at Runtime

The ‘change’ button

193
Changing Internal Tables at Runtime

Initial Values of an Internal Table

Debugger

New Values of an Internal Table


194
Deleting a Row from an Internal
Table
The Delete Button

195
Editing a Row of an Internal Table

The Change button

196
Adding a Row to an Internal Table

The Insert and Append Buttons

197
Debugging Strategies

198
Using Breakpoints

199
Setting Static Breakpoints

CASE WORLD_SERIES.

WHEN COLORADO_ROCKIES.
WRITE ‘WORLD’S GREATEST TEAM’.
WHEN OTHERS.
WRITE ‘MAYBE NEXT YEAR’.
BREAK-POINT. Setting a static
breakpoint
ENDCASE.

200
Setting Dynamic Breakpoints
Use menu
path to add
break point

Double click here to


add break point

201
Displaying Dynamic Breakpoints

Double click on the “Stop” icon to


delete a break-point

202
Setting Breakpoints at Keywords or
Events

Menu path to create / change /


delete a break-point

203
Setting Watchpoints

Create watchpoint
buttons

Create
watchpoint
screen

Logical Operators to compare watch point variable’s value

204
Watch points overview screen
Button to
display watch
point overview
screen

Watch point
change/delete

Logical Operators
between watch points
205
Deleting and Deactivating
Breakpoints

206
Deleting and Deactivating
Dynamic Breakpoints

207
Debugging Without Breakpoints

208
Switching to the ABAP Editor from
within the Debugger

@#!##?*&% No Problem!

Debugging Editing
209
Releasing the Database During
Debugging

210
211

Vous aimerez peut-être aussi