Go Back   Wiki NewForum | Latest Entertainment News > Career Forum & Tips


ABAP/4 Development Workbench


Reply
Views: 3830  
Thread Tools Rate Thread
  #1  
Old 01-02-2009, 08:24 PM
Sumathi
Guest
 
Posts: n/a
Default ABAP/4 Development Workbench

FULL Material in Attachment with screen shots.
  • The development environment of SAP R/3 system is fully integrated set of various development tools, data dictionary, and programming language. Full integration of all components means that changes in any part have direct and immediate effect on all application using those components.
The screen of ABAP/4 development workbench look like

Tools of ABAP/4 workbench

For programming

  • ·ABAP/4 dictionary: Defining, maintaining and storing the data dictionary of the SAP R/3 system stores all the dictionary objects including tables relationship and help information. Transaction code for this is SE11
  • ·ABAP/4 editor: Creating and maintaining the ABAP/4 program editing function modules, logical database, and screens. Transaction code is SE38
  • ·Function library: Defining and maintaining the ABAP/4 function modules. Transaction code is SE37
  • ·Screen painter: Designing and maintaining the screens in transaction. Transaction code is SE51.
  • ·Menu painter: Designing and maintaining the menus for graphical user interface Transaction code SE41
For navigation
  • ·Object browser Managing and organizing the development object in a hierarchical form. Transaction code is SE80
  • ·ABAP/4 repository information Navigating and searching for the dictionary objects, development objects and relationship objects. Transaction code SE84.
  • ·Data browser Navigating in the data tables of the database. Transaction code is SE16.
For debugging
  • ·SQL trace: Tracking the database calls form the system transaction and programs. Transaction code is ST05.
  • ·Debugger: Stopping the program and analyzing the results of the execution of every program statements.
  • ·Runtime Analysis: Analyzing the performance the system calls. Transaction code is SE30.
Organizing development
  • ·Workbench organizer controlling and keeping track of development work and team related development projects and managing versions of development objects. Transaction code is SE09.
  • ·Transport system Performing and managing the transport development object across different system. Transaction is SE01.

Last edited by Sumathi; 01-02-2009 at 08:36 PM.
Reply With Quote
  #2  
Old 01-02-2009, 08:25 PM
Sumathi
Guest
 
Posts: n/a
Data dictionary objects:

·Tables A table is two dimensional data matrix. A table contains rows and columns. Rows contains data while column indicates fields. Table can contain 0 or multiple rows.

·Structures The object structure refers to the definition of object that does not have any contents. It is like table or view, but it never has entries i.e. it is only a structure. The basic difference between structure and table is that the structure does not exist at the underlying database system level. Structure exists as definition in the dictionary.

·Views A view is an imaginary table. It contains data, which are really stored in other tables. The contents for the view are dynamically generated when called from program.

·Data element They are definition of the properties and type for a table field. It is an intermediate object between the object type domain and the table field. A field in R/3 system is always associated with a data element, which at the same time is related to domain.

·Domains They are formal definition of the data types from a technical point of view. They set attributes such as data type, length, possible value range and so on.

·Lock objects These types of objects are used for looking the access to database records in table. This mechanism is used to enforce data integrity that is two users cannot update the same data at the same time. With lock object you can lock table-field or whole table.

·Matchcode objects are similar to table index, which gives list of possible values for either primary keys or non-primary keys.

Tables in ABAP/4 dictionary

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

Transparent tables

Pool tables

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

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

In any RDBMS, tables are related to each other. But to relate table to each other it is necessary that one of the tables contain some information of other table. Mostly tables are related to each other through primary keys. The primary key of one table, if it exists in other table then it is called foreign key. This type of database management system means that there is some redundancy of data. But it can minimize by using normalization procedures available. One of the most important function foreign key is to ensure data integrity. For example say you have EMP table, which has fields emp.no., emp.name, dept. code, salary and you have DEPT table which has dept.code and dept.desc. then in DEPT table dept.code is primary key while dept.code in EMP table is foreign key. If you enter dept.code for particular employee in EMP table the dept.code should exists in DEPT table, and if does not exists then will flash error. In this case DEPT is called check table while EMP foreign key table.

Creation of table

Steps to create a table

·Create a domain
·Create data element
·Create actual table

Creating Domain

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

(Data type) where you need to enter the data type available in SAP
Field length: Field length is the number of valid position.
Value table Name of the table to be entered. The fields referring to this domain may only assume values contained in the value table.

Once the domain is created, save and activate it, so that it can be used for further objects (basic rule of dictionary)


Creating Data Element

The second step of table creation is to create data element. It assigns a certain meaning to the table fields, which are defined using that data element.

A Data element always needs to be defined over a domain and field is always defined over a data element. This allows all fields with same technical properties to use the same data element.

Parameters to be passed when creating a data element
Short text. Mandatory field.
Domain: A mandatory field. If the domain does not exist, SAP can take you directly to domain definition screen.

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

Creation of actual table.

Parameters to be passed for creation of a table.
Short description. Mandatory field.
Delivery class.
Table fields: Specify whether primary key. In this case it is mandatory to enter data element.
Data class: Establishes the physical area of the database.
Size category: Allows you to specify estimated space requirement for the table.

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

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

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

General introduction to ABAP/4

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

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

ABAP/4,a fourth generation language, contains all usual control structures and modularizing concepts for structured programming. The three parts of the ABAP/4language are:
Structure and execution of ABAP/4 programs
Basic language elements
Programming reports
Programming dialogs

Structure and execution of APAP/4 programs are essentially different form entirely sequential programming languages such a s FORTRAN, PASCAL, or C, ABAP/4 instead shares certain similarities with modular, event –oriented programming languages such as Visual Basic or JAVA.

The two most important statements concerning structure and execution are:

An ABAP/4 program has a modular structure.
For execution, you need a special runtime environment.

This means, that ABAP/4 source texts always consist of a collection of program modules (one single module in the easiest case) or the sequential set of statements. The individual program modules consist of sequential statements. The set of statements of a program module is also called processing block.

The runtime environment is responsible for calling the individual program modules one after the other. The runtime environment is the ABAP/4 processor, which can communicate with the list processor or the dialog processor, depending on the program type.


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

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

Reports

You use reports to databases and represent the results in list. Reports are collections of processing block that the system calls depending on events.

Dialog programs

Your use dialog programs to execute transitions, which usually read and change databases. Dialog programs are collection of processing blocks (so-called module pools) that are called by screen flow logic. The third part of the user’s Guide describe dialog programming in detail.

Report can call dialog programs and vice versa.

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


Characteristics of the ABAP/4 programming language:

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


Reports

·Reports are ABAP/4 programs.
·You use reports to evaluate data form database tables. The results of such an evaluation can be displayed on the screen or printed from.
·Reports are stand-alone programs.
·The user can execute reports directly via the program name, for example, by choosing System ® Utilities ® Reporting.
·Reports are controlled by events.
·A report program contains a collection of processing blocks for different events that are always triggered externally. In a report, you can react on events by programming the corresponding processing blocks or ignore the events by not writing the corresponding processing blocks or ignore the vents by not writing the corresponding processing blocks. A report itself never creates events.
·Reports can use logical databases or select statements defined by developer.
·For each application, SAP supplies logical databases. Or you can easily create logical databases yourself.
·Event control of a report corresponds to a certain scheme.


When a report is executed, the ABAP/4 processor creates together with the logical database use (if any) a sequence of certain events for which you can program processing block. The chronology of the events is (more or less):




Steps involved in creating a Report:

1.Processing the selection screen.

After starting a report, the selection screen allows the user to enter limits or control values for further report processing.
The report can contain several processing block for events during selection screen processing, for example, for checking the input values.
2.Reading the database

After selection screen processing come the events for reading the database. Either the report reads data from relational databases it using the corresponding APAP/4 statements (OPEN SQL) or leaves this task to a logical database. In the latter case, the logical database creates a sequence of events to allow the report to copy the data.

3.Evaluating data and creating lists

During or after the database the report creates the output list. During list creation, several events allow you to layout the output list (for example, layout the page header).

4.Outputting a list

The last part of the processing sequence controlled by the ABAP/4 processor is the list output on the screen or printer.

When displaying the list on the screen, the report user can trigger a number of other, interactive, events, for example, by clicking the mouse. By programming processing blocks for these events, you can change a normal report to a so-called interactive report.

If a report does not contain event keywords, the entire coding of the report belongs to a single processing block, which is called by a standard event. This standard event is triggered directly after processing the selection screen.

DIALOG PROGRAMS

Characteristics of a Dialog Program:

·You use dialog programs to execute transactions. The users of dialog programs in dialog session are read and change database tables. Apart form the actual data processing (Open SQL), update and en-queue concepts are of great importance when programming dialogs.
·Dialog programs are not stand-alone.
·To execute dialog programs, they must be linked to at least one screen that itself is linked to a transaction code. The transaction code determines the initial screen with which the dialog session starts.
·Dialog programs are controlled by screen flow logic.
·The actual ABAP/4 dialog program is a so-called module pool. A module pool contains a collection of dialog modules that are called by the screen flow logic.
·To each module pool, at least one but usually several screens are allocated. Each screen has flow logic. The flow logic contains of BPO (Process Before Output) and PAI (Process After Input) blocks. This flow logic does not use the ABAP/4 programming language and the ABAP/4 Editor tool, but a special statement set and the Screen Painter tool, which you also use to layout screens. The flow logic mainly contains the chronologically ordered calls of the modules in the corresponding module pool.
·The Collection of PBO flow logic, screen and PAI flow logic is called “Dynamic Program” (Dynpro). A module pool must have at least one dynpro. Each screen of a dialog session thus is the visible part of a dynpro, to which also the flow logic belongs. The processing logic of a dialog session is stored in the corresponding module pool in the form of ABAP/4 modules.
·The ABAP/4 modules in the module pool are separated into PBO and PAI modules. The PBO or PAI blocks of the flow logic of each dynpro of a module pool can call each PBO or PAI module of this module pool.
·You can use ABAP/4 statements in the processing logic of the module pool to control the chronology of the different dynpros. After starting a dialog session via the transaction code, which is firmly connected to a dynpro of the module pool, the screen flow logic passes user entries to the processing logic in the ABAP/4 module pool. The processing logic processes the user entries (database accesses) and, if required, defines the appropriate subsequent screens.
Reply With Quote
  #3  
Old 01-02-2009, 08:26 PM
Sumathi
Guest
 
Posts: n/a
Data Types and Data Objects

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


Data Types

·Are pure descriptions
·No memory is associated with data types.
·Describes the technical properties of data objects.

Structure and definition classify data types. Can be of:

1.Elementary or structures
2.Predefined or use4r defined.


Predefined
User-defined
ELEMENTARY
C, D, F, I, N, P, T, X

You can use directly
Based upon elementary Data types
Ex. TYPES: number type i. Cannot allocate memory to types.
STRUCTURED
Predefined types are TABLES
User defined structured types are Field String and internal tables.


Data Objects

·Data objects are units created during runtime.
·Data object cannot exist without data type.
·Occupies memory space.





Kinds of Data Objects

1. INTERNAL DATA OBJECTS

·Literal
A literal has a fixed value.
Ex. WRITE ‘WORK HARD’.

·Variables

DATA statement is used to create variables.
Ex. DATA: NUM TYPE I.
NUM is a variable declared by DATA statement. Any variable, which you use in program, need to be declared before you use it and can be done by DATA statement.
Here variable is declared by referring to existing data type.

Variable can also be declared by referring existing data object.
Ex. We have already declared NUM by DATA statement.
DATA : PRICE LIKE NUM.
Here variable is declared by using LIKE parameter, which tells system that price has all the attributes of data object NUM i.e., PRICE is also of type I.
The main difference between TYPE and LIKE parameter when defining or declaring the object is that TYPE is used to refer existing DATA TYPE (elementary or structured or user defined) while LIKE is used to declare data objects with reference to existing DATA OBJECTS.

·Constant

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

Ex. CONSTANT: INT TYPE I VALUE 15.

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

2.EXTERNAL DATA OBJECTS

Are defined in tables i.e., In ABAP/4 dictionary. You can access this data from table.
TABLES: SFLIGHT.
DATA: SEATS LIKE SFLIGHT-SEATSMAX.

3.SYSTEM-DEFINED OBJECTS

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

4.SPECIAL DATA OBJECTS

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

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

Need for Data types:

Consider the following example.

DATA: fname(20),
mname(20),
Iname(20),
add1(20),
add2(20),
add3(20)

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

But consider the following case where TYPES has been used.

TYPES: string(20)
DATA: fname type string
Mname type string
Lname type string
Add1 type string
Add2 type string
Add3 type string

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

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

Parameters

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

Syntax.

Parameters : num type i.


Here parameter statement declares the variable and creates the selection screen on which user enters the data i.e., in this case num is declared of type I and user can enter any number. Entered value is stored in the same variable and can be used in program.

Data : m type I
Parameters : num type I
M = num + 5
Write : / ‘The number is m.

You can define default values with parameter statement for example

Parameter : num type I default 12.

In this case when selection screen is displayed the default value is displayed. User can either use same value or overwrite the value.

Parameter of type character and length one, can be displayed as checkboxes and radio ****ons.

Parameter : C1 as checkbox
C 2 as checkbox

Parameter : R1 radio****on group g1
R2 radio****on group g1

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

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

WRITE STATEMENT

About WRITE statement

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

Syntax :

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

PROGRAM ZDEMO
WRITE : /’HELLO’

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

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

Write : ‘HELLO’
Write : ‘WORK HARD’

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

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

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



Formatting output

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

Syntax

WRITE AT [/][][()]
Where

.the slash ‘/’ denotes a new line,
is a number or variable denoting the position on the screen,
is a number or variable long denoting the output length.

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

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

This produces the following output on the screen :
The text – 1234567890 – appears in the text.

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

DATA : NUMBER TYPE I VALUE 1234567890,
TEXT (10) VALUE ’abcdefghij’

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

This produces the following output :
7890
adcde

In the default setting, you cannot create empty lines with the WRITE statement.

WRITE : ‘One’
/ ‘ ‘,
/ ‘Two’

The output looks as follows :

One
Two

The system suppresses lines that contain nothing but empty spaces.

You can use various formatting options with the WRITE statement.

Syntax

WRITE …..

Formatting options for all data types

Option
Purpose
LEFT-JUSTIFIED
CENTERED
RIGHT-JUSTIFIED
UNDER
NO-GAP
USING EDIT MASK
USING NO EDIT MASK

NO-ZERO
Output is left justified
Output is centered
Output is right justified.
Output starts directly under the field
The blank after the field is omitted.
Specifies a format template
Deactivates a format template specified in the ABAP/4 Dictionary.
Zeros, these are replaced by blanks. For type C and N fields, leading zeros are replaced automatically.


Formatting options for numeric fields

Option
Purpose
NO-SIGN
DECIMALS

EXPONENT

ROUND

CURRENCY

UNIT
The leading sign is not output.
defines the number of digits after the decimal point.
In type F fields, the exponent is defined in
Type P fields are multiplied by 10**(-r) and then rounded.
Format according to currency in table TCURX.
The number of decimal places is fixed according to the unit.
specified in table T006 for type P fields.

Horizontal lines

You can generate horizontal lines on the output screen by using the following syntax :

Syntax

ULINE

Will draw a horizontal line.

ULINE (10)

Will start drawing horizontal line from 10th column position.

WRITE at 10(40) SY-ULINE

This statement draws a horizontal line from 10th position.

Vertical lines

You generate vertical lines on the output screen by using the following syntax :

Syntax

WRITE [AT [/][]] SY-VLINE.

Blank lines

You can generate blank lines on the screen by using the following syntax :

Syntax


SKIP []

Starting on the current line, this statement generates blank lines on the output screen. If no value is specified for , one blank line is output. In the standard setting, you cannot create empty lines with the WRITE statement alone.

To position the output on a specific line on the screen use :

Syntax

SKIP TO LINE

This statement allows you to move the output position upwards or downwards.
Branches

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

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

·Branching (IF, CASE)
·Looping (DO, WHILE)

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

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

Branching with IF statement

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

Syntax

IF

ELSE

ENDIF

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

To introduce alternative conditions, you can use ELSEIF statements. If the first condition is false, the system processes the following ELSEIF statement in the same way as the IF statement, ELSE begins a statement block which is processed if none of the IF or ELSEIF conditions is true. The end of the last statement block must always be concluded by ENDIF.

IF

ELSEIF

ELSEIF

ELSE

ENDIF

ABAP/4 allows unlimited nesting of IF – ENDIF statement blocks, but they must terminate within the same processing block. In other words, an IF – ENDIF block cannot contain an event keyword.

Branching with CASE statement

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

Syntax

CASE
WHEN

WHEN

WHEN


………
WHEN OTHERS

ENDCASE.

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

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


LOOPING

Looping with DO statement

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

Syntax

DO 5 times
Write :/ name
ENDDO

The system continues processing the statement block for 5 times the loop has been processed so in this case when the loop is over value of sy-index will be 5.

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

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

Exit and stop takes you out of that loop.
Reply With Quote
  #4  
Old 01-02-2009, 08:26 PM
Sumathi
Guest
 
Posts: n/a
Looping with WHILE loop

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


Syntax

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


The system continues processing the statement block introduced by WHILE and concluded by ENDWHILE statements as long as M is less than 10 or until the system finds an EXIT, STOP.
The system field SY-INDEX contains the number of times the loop has been processed.
You can nest WHILE loops any number of times and also combine them with other loops.


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

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

String Operations

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

Shift command

To shift the contents of a field, by one position or one character you can use the SHIFT statement. Using SHIFT allows you to shift field contents byte by byte or character by character.
With the SHIFT statement, you can execute the following :

String = ‘HELLO’
String1 = ‘ALL OF YOU’
String3 = ‘WORK HARD’


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

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

Replace command

You use the REPLACE statement.

Syntax

REPLACE WITH INTO [LENGTH <1>].

ABAP/4 searches the field for the first occurrence of the first <1> positions of the pattern . If no length is specified, it searches for the pattern in its full length.


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

REPLACE STR1 WITH STR2 INTO STRING

Here whole string is searched for string1 and is replaced with str2.

REPLACE ‘&’ WITH ‘M”

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


TRANSLATE command

Syntax

TRANSLATE TO UPPER CASE.
TRANSLATE TO LOWER CASE.

These statements convert all lower case letters in the field to upper case or vice versa.

You can use TRANSLATE to substitute the characters in a string like replace.
But the main difference between Translate and Replace is that Replace statement replaces only occurrence of particular character while Translate replaces all the occurrences of the character.
When using substitution rules, use the following syntax:

Syntax

TRANSLATE USING


OVERLAY command

Syntax

OVERLAY WITH [ONLY ].

This statement overlays all positions in field containing letters which occur in with the contents of . remains unchanged. If you omit ONLY , all positions of

SEARCH command

Syntax

SEARCH FOR

This statement searches the field for the character string in . If successful, the return code value of SY-SUBRC is set to 0 and SY-FDPOS is set to the offset of the string in the field . Otherwise SY-SUBRC is set to 4.

STRLEN command

To determine the length of a character string up to the last character other than SPACE, use the built-in function STRLEN as follows:

Syntax

N = STRLEN (STR)

Here N is defined in DATA statement as type i.
STRLEN processes any operand as a character data type, regardless of its real type. No conversions are performed.


CONDENSE command

To delete superfluous blanks in character fields, use the CONDENSE statement.

Syntax

CONDENSE [NO-GAPS]

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

CONCATENATE command

To concatenate separate character strings into one, use the CONCATENATE statement :

Syntax

CONCATENATE INTO [SEPARATED BY ]

This statement concatenates the character fields to and assigns the result to
Trailing blanks are ignored during this operation.

CONCATENATE STR ‘:’ STR2 INTO STRING

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

SPLIT command

To split a character string into two or more smaller strings, use the SPLIT statement :

Syntax


SPLIT AT INTO ….

This statement searches the character field for delimiter strings and the parts before and after the delimiters are placed in the target fields

To place all fragments in difference target fields, you must specify enough target fields. Otherwise, the last target field is filled with the rest of the field and still contains
Delimiters.

SPLIT STRING AT ‘,’ INTO P1 P2 P3 P4


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

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

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

Syntax

[+][(<1>)]

The operation of the statement is performed for the part of the field that begins at position +1 and has a length of

If the length is not specified, the field is processes for all positions between and the end of the field

String = string l + 3(4)

Assuming that string 1 = ‘abcdefgjk’
Here string will contain ‘defg’


OPEN SQL

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

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

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

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

Open SQL keywords

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

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

1.The database system being addresses must be supported by SAP
2.The database tables being addressed must be defined in the ABAP/4 Dictionary.

Select Statement

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

SY-SUBRC

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

SY-DBCNT

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

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

Syntax

SELECT FROM table name> [INTO ] [WHERE
This statement has several basic clauses. Each clause is described in the following table.

SELECT FROM table name> [INTO ] [WHERE

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

FROM

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

INTO

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

WHERE

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

For Selecting All data from table.

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

Syntax

SELECT * FROM


(Here you are not specifying WHERE condition)

Selecting All Data from a Single Line

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

SELECT SINGLE * FROM
….. WHERE ……

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

Prerequisite for SELECT SINGLE

1.Use all primary keys in WHERE condition
2.Always check for SY-SUBRC
3.Clear work area for table

Aggregate Expressions

By using aggregate expressions, you can extract characteristic data from a column of the database table.

MAX : returns the maximum value of the column
MIN : returns the minimum value of the column
AVG : returns the average value of the column
SUM : counts values or lines as follows.
COUNT (*) : returns the total number of lines in the selection.

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

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

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

Syntax

TABLES : SFLIGHT
DATA : CARRID1 LIKE SFLIGHT-CARRID,
CONNID LIKE SFLIGHT-CONNID
SELECT CARRID CONNID FROM SFLIGHT INTO CARRIDI, CONNIDI)
WRITE :/ CARRIDI, CONNIDI
ENDSELECT

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


Syntax :

TABLES : SFLIGHT, SBOOK
SELECT * FROM SFLIGHT WHERE CARRID =’ LH’
SELECT * FROM SBOOK WHERE CARRID = SFLIGHT – CARRID AND
CONNID = SFLIGHT – CONNID
WRITE : / SFLIGHT – CARRID, SFLIGHT – CONNID, SBOOK – BOOKID.
END SELECT
END SELECT

Some performance hints for Open SQL statements.

·Keep the selected dataset small

Keep the number of selected data as small as possible to avoid unnecessary network transports. Use the respective Open SQL statements always with the WHERE clause. Avoid complex WHERE clauses. The system must split up those into single statements for the database system.
Do not use the logical NOT in WHERE clauses but inverted operators instead.
The logical NOT is supported by the database indexes.

·Keep the transferred data small

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

·Keep the number of database accesses small

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

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

Insert Statement

INSERT statement inserts a single record into the database table.
Syntax

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

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


Update Statement

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

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

Sflight-carrid = ‘MN’
Sflight-connid = ‘454’
UPDATE SFLIGHT where CARRID = ‘LH’

Or

TABLES SFLIGHT
UPDATE SFLIGHT SET PRICE = 1100
WHERE CARRID =’LH’

Here price of sflight will get updated with new price 1100


Delete statement


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

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

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

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

DELETE SFLIGHT FROM TABLE ITAB.

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



EXERCISES

SIMPLE WRITE STATEMENTS


1.write a program which generate the model list as shown.
Use these system fields in your program.
SY-DATUM, SY-UZEIT, SY-UNAME
Maintain the list headings.
12/12/97 FIRST PROGRAM


This list is generated
On : 12/12/1997
At : 13:40:35
By : ABAP1



2. Create a list as shown
---------------------------------------------------------------------------------------------------------------------------------

XYZ Co. Pvt. Ltd.
Date: today’s date Page No.1
------------------------------------------------------------------------------------------------------------program name: ZDEMO.



SYMBOLS, ICONS AND FORMATTING


1.Write a program to show the following using system variables
(hint :use include and include)

Symbols:
Telephone,
Fax machine,
Hand pointing left,
Hand pointing right,
Caution,

Egg: write sym _phone as symbol, ’telephone’.

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

Ex :
Write ‘HEADER’ color col_heading.
(Col_heading is abap/4 name for grayish blue color. Other colors are col_key for bluish green, col_normal for bright gray, col_background for gray, col_positive for green, col_negative for red, col_group for violet and col_total for yellow)

3. Use Format intensified-format intensified off,
Format color-format off,
Format inverse-Format inverse off.

4.Show current time and today’s date

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

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

7.suppress assign before a number.

GENERAL PROBLEMS


1.Create an adding machine for numbers
The two values to be added must be entered on the selection screen as parameters. Output the result.
2.Create the dividing machine for numbers.
The two values must be entered on the selection screens as parameters.
Output the result.
3.Create your output as shown below.

*
**
***
****
*****

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


5.Declare a string ‘echo’ and design your output

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



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


1.Write a program with Do-Enddo loop,
Display squares of numbers 1 to 10.
11
24
39
2.Write a program to accept a number(say 2)from user and create a multiplication table.
2*1 = 2
2*2 = 4

2*10 =20
3.Accept. a number from user and find Factorial of the same. If the number is
negative then display some message
4.Write a program with Do-Enddo loop first 20 numbers.
-Output should contain only Even numbers
-Odd numbers should not be displayed
5.Accept numbers and choice ‘EVEN’ or ‘ODD’ from the user and display the numbers in that range according to user’s choice.
6.Write a program with Do-Enddo loop for first 20 numbers.
-Odd numbers &Even numbers should be displayed with alternate intensities.(Use
Format intensified-on-off)
7. Create a calculator which perform the four basic types of calculations on two
whole numbers. The two values and the option to be entered on the selection
screen as parameters. Output the result with 2 decimal places.

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

STRING OPERATIONS


1.Accept a string and determine its length.

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

3.Accept two strings and swap their contents.

4.Accept two strings and concatenate into one string.

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

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

7.Accept a string eg. Apple. Change first occurrence of ‘p’ to ‘b’. (use ‘replace’ command)

8.Accept a string eg. Apple. Change all the occurrences of ‘p’ to ‘b’. (use ‘translate’ command)

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

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

11.Accept first name, last name and middle name. Eg. Nandamuri Taraka Ramarao display as N.T.Ramarao.

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

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

14.Accept a string and display the string in reverse order.

15.Accept a string and check for palindrome.



DATE PROBLEMS

1.Accept a date earlier to today’s date and find the difference in number of days.
  • Accept a date from user and display first day of the month and last day of the previous month.
  • Accept a date from user and add six months to the date.
  • Accept a date from user and convert month part to ‘jan’. ‘feb’ etc., and display this date.
  • Write a program to accept month. Display no. of days in that month.
Make use of
-Text element for your selection screen box.
-selection text.
  • Accept birth date from user and output age in years, months and days.


CHECK BOXES AND RADIO ****ONS


  • Write a program with
-Parameter as checkboxes
-If checkbox 1 is clicked write c.b 1 clicked else c.b 1 not clicked
-If checkbox 2 is clicked write c.b 2 else c.b not clicked.
-If checkboxes 1 & 2 are clicked write c.b 2 are clicked.
-If checkboxes 1 & 2 are not clicked write c.b 1 & c.b 2 are not clicked.

  • Write a program with
-Parameters as two groups of Radio****ons(two radio****ons in each group).
-Give detailed coding as abov, to show the Radio****ons and groups
-Selected.

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

  • Write a program with
-Parameter a group of 3 radio****ons
-If first radio****on is clicked, display last day of the current month.
If second radio****on, display first day of the next month.
If third radio ****on, display date after six months.


SELECT STATEMENTS


1.List all the rows from the table VBAK.
2.List single row from the table BKPF.
3.List up to 5 rows from the table BSIS.
4.List all ERDATs. For better readability crate a column heading in the list.
5.Display total amount for carrid ‘LH’. (Tables : SFLIGHT)
6.List all the flights for which booking date is grater than’01.06.1995’.
7.List all the flights for which payments currency is ‘DEM’.
8.List all the flights where carrid is between ‘LH’ and ‘SQ’.
9.Select a single record where carrid = ‘LH’, flight-no = ‘0400’ and fldate = ’28.02.1998’.
10.Display carrid, connid, fldate and luggage weight multiplied by 2.
11.List the maximum capacity, occupied seats a total of current bookings for each flight in the following format.

[IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image001.gif[/IMG]






12.From the given from-city and to-city, list all the available on this route:
From: To: (say from Frankfurt to Madras)
[IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image002.gif[/IMG][IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image002.gif[/IMG][IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image002.gif[/IMG] Carrier id Departure time Start Airport Destination Airport


C

  #5  
Old 01-02-2009, 08:28 PM
Sumathi
Guest
 
Posts: n/a
OPEN SQL


1.Accept document no. from user and display particulars of sales document. (default no. ‘001000031’)
(Table : VBAP)


Created on : xxxx
Created by : xxxx
Time : xxxx

  • Accept sales document no. from user and display corresponding material no. description of that material and item category (Table : VBAP)
  • Accept material no. & item category by default PP100 and KMN respectively. Display corresponding details of sales document (table : VBAP)
  • Display fields from BKPF.
Document type = ‘AB’ and
Document date = ’05.02.1998’.
Also display no. of records selected.

  • Display Co.code. doc.no., acct.ttype. tax code.
Make use of select-options to give range of document type.
Display title of your program at the end of program.

  • Accept doc.no. from user.
Display doc.no., doc.status, date of doc., doc.type.
  • Display single record for document where date = ’05.02.1998’, type = ‘AB’ and document no. = ‘0100000006’.
  • Accept plant from user eg. PLTP.
Display document details for that plant like doc.no., doc.status, date of document etc.,











DEBUGGING



Many times an error free program doesn’t give desired output. Behavior of program is different in different situation, with different values of variable. Such program needs additional testing, by which you can test the program by stopping each point where you feel program is behaving abnormally.

The ABAP/4 debugger is the development workbench tool, which allows you to stop a program during its execution when a particular condition is met. When the program is stopped, you can use the debugger to display the contents of the table and variable being used by the program. It allows you to execute the program step by step, reviewing exactly the real flow of the program execution.

There are many occasions during normal system operation during which the ABAP/4 automatically started when the system encounters a breakpoint.

Starting the ABAP/4 debugger


There are many ways to start debugger
-By clicking the Execute ****on and selecting the debugging mode.
[IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image001.gif[/IMG] -From the ABAP/4 editor, by executing a program choosing Program Execute
[IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image002.gif[/IMG] Debugging from the menu.
-Setting breakpoint in the program.







Components of ABAP/4 debugger


The debugger shows the program information using six different views.

·O Presents the program structure, events, subroutines and modules.
·S displays the calling sequence within a particular event, up to the current breakpoint.
·V it is the default view, which displays the contents up to four field.
·F Displays the field contents and in this view you can define values for the watch points.
·T Allows modifying the contents of internal table.


·P displays all program, which are needed for program debugging including system program.



All these options are shown in the following screen.
















[IMG]file:///C:/DOCUME%7E1/Chinna/LOCALS%7E1/Temp/msohtml1/01/clip_image004.gif[/IMG]

Arrow indicates the breakpoint of the program i.e., where user has stopped the program.


Breakpoints


A breakpoint is the signal, which is specified in the program, tells the system to stop the program execution and to start the debugger. Following types of breakpoint are available with ABAP/4.

·Static are set up with the BREAKPOINT keyword inside the program, which you can directly display with the ABAP/4 source code editor. To set the breakpoint in the program enters the keyword BREAKPOINT.
·Dynamic this breakpoint is not visible in the code. Position the cursor over the source code line to have the breakpoint and then select utilities -> breakpoint -> set. You can delete them or display them from breakpoint list. Or you can execute the program in the ABAP/4 debugger i.e., in debugging mode.
·Watch points are field specific. The program is stopped when the field reaches the value specified in the watch point. Execute the program in debugging mode. Position the cursor over the needed field. Press the F ****on to get the view of field. Select the checkbox for the needed watch point. Click on the continue ****on.
·Keywords / events . The program stops just before executing a specific event / keyword. To set breakpoint at particular event from initial screen of debugger, select Breakpoint -> Breakpoint at -> at event at keyword. Enter the name of the keyword or event. Click on the OK.

Navigating through the breakpoint

Following ****ons are used to navigate through the program and debugger.

·Single step Executes a single program command.

·Execute Similar to single step, but when a program calls a subroutine, it executes the whole subroutine unlike single step.

·Continue Executes the program until it is finished or until it finds next breakpoint.

·Return Allows for executing the program instruction up to the end of a routine and stops in the line of code where the subroutine gives back control to the main program.

·Tables switches the debugger to the table view.

Displaying and modifying values


Every time the program is stopped within a debugger, you can display and modify the contents of table field and fields.
To display the fields, click on V and you can view the contents of system field, program field, ABAP/4 dictionary fields, and external program fields.


Displaying and modifying internal tables


When you click on the Table ****on from the initial ABAP/4 debugger screen, the system will display the table debugger view. Here you need to enter the name of the internal table to be displayed. You can modify or delete or add i.e., insert the internal table contents. These changes are applicable only for the debugging and do not affect the structure of internal table in the program.

Setting WATCHPOINTS


·Execute a program in debugging mode.
·Position the cursor over the needed field.
·Press the F ****on to get a view of the fields.
·Select the checkbox for the needed watch point.
·Click on the CONTINUE ****on.
·To display the active watch point select
Goto -> Breakpoint

INTERNAL TABLES

Consider the following cases :

·You want to reorganize the contents of table .
·You want to modify few details of table and then display the contents of table to user.
·You want to perform table calculations on subset of database table.

In above cases you need to reorganize or to change the database table contents.
In ABAP/4 you work mainly with tables. Long life data is stored in database tables. You cannot afford to lose data from database table. In such cases where you can not work directly with database table (where you are modifying contents of table or reorganizing the contents of table or any other case where you are altering contents of table and then displaying output to the user) hence need of intermediate table where you put in all the data from database table and work with this data thus avoiding accidental loss of data.

These intermediate tables are called INTERNAL TABLES in ABAP/4 and are
Created only during runtime i.e., no memory is reserved for internal tables.

When you use Internal Table in program, three steps are associated with it.

  • Declaration of Internal Table.
  • Populating internal Table.
  • Processing Internal Table.

DECLARATION OF INTERNAL TABLE


Depending upon how you create, internal tables are of two types.

  • Internal tables with header line

When you create internal tables with header line, then default workarea or header is created. And you can work with this header.

  • Internal Table without header line.

In this case you need to create explicit workarea to work with table. Only advantage of internal tables without header line is that you can nest them i.e., you can have table within table. Which is not possible in internal tables with header line.



Internal table can be declared in following ways.

  • Data : itab like sflight occurs 0 with header line.

Here you are declaring internal table which is similar to sflight i.e., itab like sflight i.e., you are referring to existing table (like). (By default internal table created with this declaration is without header line)

  • Data : Begin of itab occurs 0.
Include structure sflight.

  • Data : End of itab.

(Internal Table created with this type of declaration is similar to declaration done in ‘a’ type the only difference is by default internal table created by this type is with header line)

  • Data : begin of itab occurs 0.
carrid like sflight-carrid,
connid like sflight-connid,
fldate like sflight-fldate,
end of itab.

By default internal table created by this type of declaration is with header line. In this type of declaration, you are using only those fields from databvase table which you require for processing.

  • Data : begin of itab occurs 0,
carrid like sflight-carrid,
connid like sflight-connid,
bookid like sbook-bookid,
id like scustom-id,
end of itab.

Here you are combining fields from three different tables in one internal table.

  • Data : begin of itab occurs 0.
Carrid like sflight-carrid.
End of itab.






POPULATING INTERNAL TABLE


  • Itab-name = ‘ABCD’
Append Itab.
(In this case itab is filled with one name i.e., ‘ABCD’)

  • Do 5 times.
Itab-number = sy-index.
Append itab.
Enddo.
( In this case itab is filled with sy-index for 5 times)

  • Select * from sflight into itab.
Append itab.
Endselect.

  • Select * from sflight into table itab.
(note that with one addition of ‘TABLE’ into select statement, you omit append itab and endselect)

  • Select * from sflight.
Move-corresponding sflight to itab.
Append itab.
Endselect.
(Note that when you use move-corresponding, field names of your database table
and internal table should be same)

  • Select * from sflight.
Move sflight to itab.
Append itab.
Endselect.
(In this case structure of sflight and itab should be similar).

  • Select carrid1 connid1 from sflight into (itab-carr1,itab-connid1).
Append itab.
Clear itab.
End select.



PROCESSING INTERNAL TABLES


Processing of internal table includes:

  • Writing : write: / itab-carrid. (will write only one field) loop at itab. (to write whole internal table)
Write itab.
Endloop.

  • Reading : You can read internal table by Read table itab with key carrid = ‘LH’. (here you are reading table with key)
Or Read table itab index 3. (Here you read table with index 3)
(Note : Reading of internal table can be done inside the loop or outside the loop)

  • Modifying : You can modify contents of internal table by specifying key or index.
Itab-carrid = ‘LM’
Modify table itab index 3.

  • Delete : delete table itab index 3.
(will delete record with index 3)

Commands associated with clearing of internal tables are as follows:

  • Clear itab : Will clear header of internal table.
  • Clear itab[] : Will clear body of table.
  • Refresh itab : Will remove contents of internal table.
  • Free itab : Will deallocate memory associated with internal table.

Sorting of Internal tables


To sort contents of internal table you can use

SORT ITAB

This command will sort internal table on all non-numeric primary keys in Ascending order.

To specify internal table for given key the syntax is.

SORT ITAB BY CARRID ASCENDING.

In this case the table itab is sorted with carrid key in ascending order.
You can sort table in either ASCENDING or DESCENING order. The default order is ASCENDING.

You can sort table with multiple keys also. The number of SORT key fields is restricted to 250. If you specify more than one field then the system sorts the records first by f1, then by f2 ad so on. (Here f1,f2 are the fields)
Control Break Statements


Control break statements are used to create statement blocks which process only specific table lines inside the LOOP – ENDLOOP block.

You open such a statement block with the control level statement AT and close it with the control level statement ENDAT. The syntax is as follows:

Table should be sorted when you use control-break statements.

You can break the sequential access of internal tables by using these statements.

SYNTAX


At first.

endat.


This is the first statement to get executed inside the loop (remember control break statements are applicable only inside the loop)

So in this block you can write or process those statements which you want to get executed when the loop starts.

At new carrid
Write : / carrid.
Endat.

In this case whenever the new carrid is reached. Carrid will be written.

At end of carrid.
Uline.
Endat.

In this case whenever the end of carrid is reached a line will be drawn.

At last.
Write : / ‘all records over’.
Endat.

Processing of statements within this block is done when entire processing of entire internal table is over. Usually used to display grand totals.

You can use either all or one of the above control break statements with in the loop for processing internal table.

At end of carrid.
Sum.
Endat.

In above case the statement SUM (applicable only within AT-ENDAT) will sum up all the numeric fields in internal table and result is stored in same internal table variable.



SUBROUTINES

The process of breaking down a large program into smaller modules is supported by ABAP/4 through subroutine also called forms.

Subroutines are programs modules which can be called from ABAP/4 programs. Frequently used parts of program can be put into subroutines and these subroutines can be called explicitly from the program. You use subroutines mainly to modularize and structure your program.

DEFINING SUBROUTINES


A subroutine is block of code introduced by FORM and concluded by ENDFORM. Following syntax is used to define a form or subroutine:

FORM
……… ………
………. ………
ENDFORM.

Here parameters is optional. You can have plain subroutine without the parameters for example.

FORM SUB1.
……
……
ENDFORM.

CALLING SUBROUTINE


You can call subroutines from program by following statement:

PERFORM []
Parameters are optional. i.e, You can call subroutine without passing any parameter.
Perform SUB1.

PASSING DATA TO SUBROUTINES


When you work with global data in subroutines, you can put a copy of the global data on a local data stack and use it to avoid accidental loss of data (In this way you protect global data)

You can pass data between calling program and subroutines by using parameters.

  • Parameters which are defined during definition of a subroutine with FORM statement are called ‘formal parameter’.
  • Parameters which are specified during the call of a subroutine with PERFORM statement are called ‘actual parameter’.
Parameters are passed to the form either:
    • By Value.
    • By Reference.
    • By Value and return.
BY VALUE
Data: a type I value 20.
Perform sub1 using a.
Write a.
FORM sub1 using value (p_a).
P_a = 15.
ENDFORM.
In this case during subroutine call, the formal parameter are created as copies of actual parameter.
The formal parameter have their memory of their own. Changes made to formal parameter have no effect on the actual parameter.
Like in this case, through value of p_a is changed to 15, it has no effect on ‘a’ which remains as 20.

BY REFERENCE.

DATA : A TYPE I VALUE 20.
PERFORM SUB1 USING A.
WRITE A.

FORM SUB1 USING (P_A).
P_A = 15.
ENDFORM.

By default system calls all the form by reference.

In this case ,only the address of the actual parameter is transferred to the formal parameters. The formal parameters has no memory of its own .if you change the formal parameter, change is visible in actual parameter also.

BY VALUE AND RETURN.
Data: a type I value 20.
Perform sub1 changing value (p_a).
P_a = 15.
Endform.

In this case if you change formal parameter ,then the value of actual parameter is changed when the control is transferred back to the main program.
Assuming A is declared by DATA statement and has value 20 and subroutine SUB1 is called by passing A.
























CALLING A FORM VALUE OF A IN VALUE OF A
PROGRAM FORM
(p_a = 15)



BEFORE CALLING A = 20
FORM

BY VALUE A = 20 P_A = 100
(changing value of p_a)

(USING) AFTER RETURNING A = 20
FROM FORM
A = 20



BY REFERENCE BEFORE CALLING A = 20
FORM

(USING) A = 20 P_A = 100
(changing value of p_a)

AFTER RETURNING A = 100
FROM FORM

A = 100



BY VALUE AND BEFORE CALLING FORM A = 20
RETURN A = 20 P-A = 100
(changing value of p_a)

(CHANGING) AFTER RETURNING FROM A = 20
FORM

A = 100







































































Passing Table To The Subroutine


You can pass internal tables as parameters by using or changing in the form and perform statements. If you want to access the components of the internal table, you must specify the type of the corresponding formal parameter.

You also must distinguish between internal tables with or without header lines. For internal tables with header lines, you must specify the table body by using square brackets [ ], after the table name to distinguish it from the header line.

With internal subroutines, you can use TYPE or LIKE to, refer to the internal table you want to pass directly.

You can pass all internal tables as parameters in this list after TABLES in the FORM and PERFORM statement. Internal tables passed with TABLES are always called by reference.

If you can pass an internal table with header line, the table body and the table work area are passed to the subroutine. If you pass an internal table with out a header line, a header line is created automatically as a local data object in the subroutine.
PROGRAM ZDEMO.

DATA: Begin of itab occurs 0,
Number type I,
End of itab

PERFORM SUB1 TABLES ITAB.

LOOP AT ITAB
WRITE:/ itab-number.
ENDLOOP

FORM SUB1 TABLES F_ITAB LIKE ITAB[ ].
DO 3 TIMES
F_itab-number = SY-INDEX
APPEND F_ITAB
ENDDO.
ENDFORM.
























After starting ZDEMO the output appears as follows:


1
2
3

In this example, an internal table ITAB is declared with a header line. ITAB is passed to the subroutine SUBI, where it is filled using the table work area F_ITAB. And itab is written in main program.


FUNCTIONS


About function

Function modules are special external subroutine stored in a central library. The R/3 system provides numerous predefined function modules that you can call from your ABAP/4 programs, and plus you can create you own functional modules.

The main difference between a function module and normal ABAP/4 subroutine is as follows:
Functions are stored in central library and have global presence while subroutine is confirmed to a particular program. Subroutine cannot return values while functions can return values. Unlike functions subroutines cannot handle exceptions. And last but not least, the difference in the way the parameters are passed to the functions.

Declaring data as common parts is not possible for function modules. The calling program and the called function module have separate work areas in ABAP /4 dictionary tables.
You use the ABAP/4 workbench to call and maintain functional modules.

You can combine several function modules to form a function group in the function library. Since you can define global data that can be accessed from all function modules of one function group, it is reasonable to include function modules that operate with the same data, for example internal table for sales module can be grouped, in one function group.

Via the ABAP/4 development workbench screen, choose development à Function library or select function library in the application toolbar or use se37 transaction code.
Reply With Quote
Reply

Latest News in Career Forum & Tips





Powered by vBulletin® Version 3.8.10
Copyright ©2000 - 2024, vBulletin Solutions, Inc.