ABAP TRAINING MATERIAL
Some Facts about SAP
After the Internet, SAP R/3 is one of the hottest topics in the computer industry and the company that developed it. It is targeted to most industries, manufacturing, retail, oil & gas, pharmaceutical, banking, insurance, telecommunication, Transport, chemical and so on. All major hardware Vendors were fully engaged to partner with SAP: AT&T, BULL, Compaq, IBM, Sun have supported and certified R/3 platform.
SAP has list of major consultants all over the world like Anderson Consulting, Price Waterhouse – Cooper & Lybrand, Ernst & Young, KPMG and many more.
The company behind R/3 is SAP AG, founded by four former IBM employees in 1972. The company’s headquarters are in Walldorf, a small German town. The company name, SAP stands for SYSTEMS, APPLICATIONS and PRODUCTS in data processing. In 1992 R/3 was introduced and in 1995 SAP AG was ranked fifth among independent software vendors. One of the reasons for SAP’s success is that since it is a standard package, it can be configured in multiple areas and adapted to specific need of a company. Today, more than 21,600 customers in over 120 countries run more than 69,700 installations of SAP® software. With subsidiaries in more than 50 countries, the company is listed on several exchanges, including the Frankfurt stock exchange and NYSE under the symbol “SAP”.
SAP has two main products in the business software market, Mainframe system R/2 and Client-server R/3. Both are targeted to business application solutions. Here R indicates REAL TIME.
R/2 is SAP AG mainframe software that runs on IBM, Siemens and other compatible equipment. This type of solution cannot be open, but with ALE technology, R/2 can be linked with R/3 system and share data. This system is mainly targeted at enterprises with data-intensive and centralized industries.
R/3 is the product that has really placed SAP AG as the leader in the country. This complex Client/server system is core of our course. The global acceptance of R/3 is not only because it caters all complex needs of business but also this international acceptance is because of R/3’s international applicability. For SAP this does not mean having software available in different languages, but also covering currency, taxes, Legal practice concerning HR, Import/export regulations. SAP also values its customers and it is shown by the comprehensive set of quality services put by SAP to help customers during the process of implementing and supporting the R/3 systems. These services include product information; training, installation and upgrade service like:
OSS: Online Service System is one of the primary sources of service and support provided by SAP. With OSS, customers can search the SAP information database and find solutions for errors and problems with R/3 systems. You can also submit your problems to SAP.
Consulting Service: with remote consulting service customer receives immediate and updated technical support and answers to their questions.
Maintenance service: This is the basic and most common type of support for customers in technical support and answers to their questions.
Information Service: These are the various information sources for receiving detailed information about the R/3 system, marketing brochures, system documentation, training information and many more things.
Preventive services: The primary one is the Early Watch Service, which ensures successful and efficient installation of the R/3 system in all phases. This service makes regular/performance checks and analyzes the system to identify potential problems, help system managers and SAP administrators to tune the system. Soon after the Early Watch session, SAP sends the customer a report with the result of the analysis and recommendations for avoiding potential problems such as database becoming full.
So overall SAP R/3 is an open client/server software system, designed to manage business information needs of an entire enterprise. The whole dataflow of SAP R/3 works in an integrated way, which means the data needs to be entered just once and the system automatically updates other logically related data.
WORKING WITH R/3 system
The SAP R/3 presentation interface behaves very similarly to any other typical window application and is also known as SAPGUI. The first screen that you come across in R/3 system is SAP logon screen.
SAP R/3 logon Screen
This is the first screen that appears when you use SAP logon utility. It has four fields: the client, the user, the password and the language.
Client: Here you enter the client number. The client is group of users who has similar rights. It can be group of users in a business entity or a whole business entity or a whole company.
• User: The name of the SAP user identification. Users of the SAP system are client-specific, which means that user belonging to one client is valid to only the particular client.
• Password: It is the password that has been assigned by the system administrator.
• Language: SAP R/3 system supports multinational language on the same system at the same time, which is very useful for multinational companies with different branches in several countries and possibly using different languages.
After entering all the fields press ENTER key and system will take you to MAIN MENU screen.
User might get different screens when he logs on, depending upon default settings of the user master record i.e., if user is DEVELOPER then the screen which he often works on is editor screen and he can go directly to this screen, if system administrator sets this screen for the user.
Main features of any R/3 window are as follows:
• R/3 standard window elements behave exactly the same, as any other standard window application would, like minimizing a screen, setting the active window etc.
• From TOP to BOTTOM, R/3 window can contain typical elements such as check boxes, push buttons, input fields and following elements:
• Menu bar is the first element of the every R/3 window. It contains the menu item corresponding to the particular R/3 application. The two menu options SYSTEM and HELP are always present in every R/3 window. SYSTEM menu option contains all utilities and functions, and is available to user at all the times. The HELP menu contains all the available options for the different types and methods of obtaining online help in the system.
• Standard tool bar. The second R/3 window element is present in every R/3 window. It is nothing but a collection of icons, which perform common functions like saving the object, exit etc. The various icons on std. Tool bar are as follows (from left to right):
Enter Command Field Save Back
Exit Cancel Print Find
Find Next First Page Previous Page Next Page
Last Page Help
All icons in R/3 window application support FOCUS property. It means, if you place cursor over an icon, the system will show the function of the icon.
• Application tool bar: The next part of the screen contains icons most commonly used in that particular task or transaction.
• Status bar is the bottom line of the screen and usually shows errors or information messages to the user. It also includes other information such as system id, session number, client, server name and the response time.
In between application tool bar and status bar you have working area, which is different for different screens.
Logging Off
User can log off the R/3 system from any screen. There are three ways of logging off the R/3 system, which are as follows:
• From the Menu bar choose SYSTEM LOG OFF. In this case, you get the log off dialog box, which informs the user that any data not saved will be lost if continuing with the log off procedure.
• Use/NEX transaction code in the command field. This is dangerous, since it does not ask if you want to save the data.
• Clicking on the EXIT button on the R/3 initial screen.
Using Transaction Code
The R/3 system provides an alternative and efficient way of selecting menu options for moving around the tasks and functions of the SAP system by using transaction code directly in the command field.
When moving with transaction, you can go to any part of the system by merely typing a transaction code in the command field, provided you have authorization for that. That transaction code is the four-character code associated with any task. By typing the transaction code and pressing ENTER key, the system takes you directly to the initial screen for transaction. Whenever any transaction code is entered in the command field, it gets stored in the buffer memory. If you click on drop down arrow, system displays list of transaction code already entered and you can select from this list or enter new one. There are almost twelve thousand and ninety four transactions in SAP. For every task, transaction code is associated and it can be found by
• SYSTEM STATUS
Status window is popped up which contains the transaction code in the trans field.
• Through DYNAMIC MENU. It gives the list of tasks. If you click on the top line of the application areas and pressing the search and search next button will give you the transaction code. /N will take you to initial screen of R/3
Important transaction codes, which you will be using often, are:
Editors
• SE37 Function Builder
• SE38 ABAP/4 Editor
• SE41 Menu Painter
• SE51 Screen Painter
• SE71 Form Painter
Dictionary
• SE11 Initial ABAP/4 dictionary maintain screen.
Browsers
• SE80 Object browser.
• SE16 Data browser.
Testing Tools
• SE30 Runtime Analysis
• ST05 SQL Trace
Getting help in the R/3 system
R/3 includes many possibilities to get online help for almost every element of the system, users can get help for entire application, for specific function, for definitions of various terms used in SAP, i.e., Glossary, messages, screens, fields etc.
You obtain HELP by using any of the following options:
• Help function from the R/3 window, which is compulsory menu item of every R/3 window.
• ? Icon of standard tool bar.
• F1 function key.
The SAP system provides help on most fields that appear on the R/3 system. To get help on particular field, position the cursor over it and press help button or F1 function key.
Another way in which R/3 system provides help is when system displays error messages in the status bar. Double clicking on the status bar shows additional information about the message.
Working with R/3 user sessions
A very important feature provided by SAP. In R/3 system you can work with more than one task at any given point of time, by means of opening sessions. You can call sessions as independent R/3 window where you can perform other tasks.
By default, a user can open NINE sessions simultaneously and can work or move around with all sessions at the same time. Sessions can be closed at any time, without having to log off the system.
User can create new sessions from anywhere as CREATE SESSION comes under SYSTEM menu which is available in every R/3 window.
SYSTEM CREATE SESSION Or /O in command field
This will open a new session or window and will place it in front of all other windows.
To move among sessions
• Just mouse click on any part of the R/3 window to make that session active.
• Combination of ALT + TAB key.
R/3 Architecture
The overall R/3 system includes the following components:
The UPPER layer, the functional layer contains the different business application. The integration of all application depends upon basis system. Applications are developed in ABAP/4 Lang. (Advanced Business Application – the 4th generation language)
The R/3 basis software is the set of programs and tools, which interfaces with the operating, system, the underlying database, protocols and the presentation interface. This layer enables all the application to work exactly the same way no matter what operating system or database, the system is installed on. It is an independent layer and ensures the integration of all modules. Besides all these specific jobs, BASIS system also contains following components and thus provides more additional features.
• ABAP/4 development workbench, which in turn includes many features like repository, data dictionary, workbench organizer, which will be discussed in later part of the topics.
• ABAP/4 language, system administrative tools, all these components are used to control, tune the R/3 system.
• Spool system manages the formatting of data for printing and passing it to the host spool system.
• Mail system you can send and receive mail from the outside world (Internet).
• Communication interface to external system from R/3 system: Manages communication at the OS level (TCP/IP), at the database level & between applications too. (RFC, EDI, and ALE)
• Database interface – This component supports different Relational databases from different vendors. The main task of database interface is to convert the SQL request from the SAP development environment to the database’s own SQL environment.
• Background processing with this facility you can submit your program for background execution.
BASIS system contains the layered components that facilitate the development of client/server architecture.
Client / Server architecture
Client/Server architecture is mainly a software concept that includes a set of service providers and service requesters. The set of computers acts as service providers and is called as server. The sets of software component, which act as service requester, are called as client.
In the client/server architecture, the database acts like a library clerk retrieving books from the shelf. The user programs have to request database for the data instead of searching for the data themselves. This way there is no risk of the users putting the data out of order. If the desired data is in use, the database makes the user wait until it is free.
The major advantage of the client/server architecture is that the server is available for a number of clients and there is distribution of work between the clients and the server. The user directs the request to the client; the client in turn understands the user’s request and redirects the request to the server. The server retrieves the data, gives it to client.
You can have client and server on the same machine or on different machines. Each client has a corresponding process inside the server.
One of the most used client/server configurations with the R/3 system is the 3 tiered architecture, which separates a system’s computer into 3 functional groups:
Three tier architecture of R/3
Database Server
Application Server
Presentation Server
(Unlike normal Client/server architecture where you have only two layers i.e., client and server.)
Communication among the 3 tiers is accomplished by standard protocol services like TCP/IP or CPIC (Common Programming Interface Communication).
In above case database server stores the data centrally. Basically contains database engine and associated processes. The database layers contain the database system used by all servers.
Application server contains software components to run the program. It contains a SAP kernel, which can run ABAP/4 program.
The presentation server is your client through which you send your request to application server. It is also called as SAP graphical user interfaces known as SAPGUI and is available in windows 3.1, Windows NT, Windows 95, and Macintosh. They all look similar whatever underlying system they are running on.
The SAPGUI includes all graphical capabilities of window interface with menu bars, tool bars, focus property, and the entire mouse clicking operations.
The R/3 system is open system in the sense that it can run on any operating system or any database and any communication technology. It means that:
• R/3 system can run on any operating system platform such as UNIX, NT, 95, AS/400.
• It supports various RDBMS such as SQL server, Oracle, Informix, DB2.
• Standard GUIs supported by R/3 are Windows 95, NT, Windows 3.1, and Macintosh.
• SAP can use standard communication protocols TCP/IP, CPIC, OSF/DCE/DME for network.
ABAP/4 Development Workbench
The development environment of SAP R/3 system is fully integrated set of various development tools, data dictionary, and programming language. Full integration of all components means that changes in any part have a direct and immediate effect on all application using those components.
The screen of ABAP/4 development workbench looks like
Tools of ABAP/4 workbench
For programming:
• ABAP/4 dictionary Defining, maintaining and storing the data dictionary of the SAP R/3 system stores all the dictionary objects including tables relationship and Help information. Transaction code for this is SE11.
• ABAP/4 editor Creating and maintaining the ABAP/4 program, editing function modules, logical database, and screens. Transaction code is SE38.
• Function library Defining and maintaining the ABAP/4 function modules. Transaction code is SE37.
• Screen painter Designing and maintaining the screens in transaction. Transaction Code is SE51.
• Menu painter Designing and maintaining the means for graphical user interface. Transaction code SE41.
For Navigating:
• Object browser Managing and organizing the development object in a hierarchical form. Transaction code is SE80.
• ABAP/4 repository information Navigating and searching for the dictionary Objects, development objects and relationship objects. Transaction code SE84.
• Data browser Navigating in the data tables of the database. Transaction code is SE 16.
For Debugging:
• SOL trace tracking the database calls from the system transaction and programs. Transaction code is ST05.
• Debugger Stopping the program and analyzing the results of the execution of every program statement.
• Runtime Analysis Analyzing the performance the system calls Transaction code is SE30
For Organizing:
• Workbench organizer controlling and keeping track of development work and team related development projects and managing versions of development objects. Transaction code is SE09.
• Transport system performing and managing the transport of development object across different system. Transaction code is SE01
Data Dictionary
The ABAP/4dictionary is central workbench repository utility providing the data definition and the information relationship that are later used in all the business application within R/3
The ABAP/4 dictionary can be seen as a logical representation or a superior layer over the physical underlying database. This database must support the relational data model. This model is strictly followed by data dictionary.
About Data Dictionary
A Data dictionary in computing terms is the source of information in which system data is defined. The data dictionary is the centralized and structured source of information for business applications. You can say that it is core of a well-structured development environment.
The elements that make up a dictionary are known as metadata. Metadata is the term for the data whose function is to describe other data. Data in dictionary is not the actual data like emp. name or emp. address but rather a type of data whose function is to define the properties of the data such as type, length, and relationship.
Advantages
Advantage of using data dictionary is avoiding inconsistencies when defining data type that will later be used in different applications. This avoids redundancies.
When a type is defined in the dictionary, it is available to any program in the application. A change in the definition of a type of data in the dictionary automatically affects any other data or program, which has this data.
Again, data dictionary is a fast and efficient way to answer questions such as which entries exist in a table of the database, what the structure of table is.
Activation of dictionary objects
For a dictionary object to be effective at runtime, that is, for a dictionary object to be available for use within a program, transaction, and so on, it must be in active status. For objects to become active, R/3 includes the ACTIVATION function.
When a table or aggregated object is activated, it is placed at the disposal of the system as a runtime object in a way that makes it available quickly for the application program to access relevant information of new activated objects.
When a dictionary object is modified, that means that the object previously existed and activated. You need to reactivate the object after modification.
When mass activation is performed massively, it might take a quite a long time. Then it should be in the background system. This type of activation is known as background activation.
The ABAP/4 Data dictionary is the central component of ABAP/4 repository. A Data dictionary is centralized and structured source of information for business application. The ABAP/4 dictionary is the core of the R/3 development system. It is the source of every definition, within R/3, from the very basic domain to the company data model. It is totally integrated with other tools of the development environment like screen painter, menu painter, and editor.
Some of the main available functions in the ABAP/4 dictionary are as follows:
• Add, delete, modify, and manage the definition of the dictionary data.
• Preserve the data integrity.
• Be the central source of information e.g. from the dictionary you get the information about the defined relationship between two tables or even the directory tells whether table is active or empty.
• It also permits documentation of system data.
In the R/3 system instead of working with original objects, you work with internal representation of objects. With this type of operation the system performance is enhanced and has the advantage that the development tools, screen interpreters always access current data.
When any of the data dictionary objects are used in other parts of the development workbench for example, in program, programmer only has to enter a table name or field name. The system automatically knows all the properties and information of the field.
To call ABAP/4 dictionary, from the main menu, Tools ABAP/4 workbench data dictionary or enter transaction SE11.
Data dictionary objects:
• Table: is a 2D data matrix containing rows and columns. Rows contain data while column indicates fields. Table can contain 0 or multiple rows.
• Structure: is a skeletal view of a table. It contains the definition of columns and don’t have any contents. Structure is generally a template based on which a table is created. The basic difference between structure and table is that the structure does not exist at the underlying database system level. Structure exists as definition in the dictionary.
• Views: A view is an imaginary table. It contains data, which is really stored in other tables. The contents for the view are dynamically generated when called from program.
• Data element: is definition of the properties and type for a table field. It is an intermediate object between the object type domain and the table field. A field in R/3 system is always associated with a data element, which at the same time is related to domain.
• Domain: is formal definition of the data type from a technical point of view. It sets the attributes such as data type, length, possible value range and so on.
• Lock objects: These types of objects are used for locking the access to database records in table. This mechanism is used to enforce data integrity that is two users cannot update the same data at the same time. With lock objects you can lock table-field or whole table.
• Search Help Objects: , which gives list of possible values for either primary keys or non-primary keys.
Tables in ABAP/4 dictionary
Tables are the basic objects in R/3 application. There are almost 8000 tables in R/3 system. Following types of tables are available
• Transparent tables
• Pool tables
• Cluster tables
From user point of view, all tables are used to store data whatever be the type of table. There is no difference in the behavior or operation of these tables. All of them can be managed by using standard OPEN SQL. However from an administrator point of view transparent table do exists with the same structure both in the dictionary as well as in the database, exactly with the same data and fields. While other two are not transparent in the sense that they are not manageable directly using database system tools. You can access these tables in R/3 environment from the ABAP/4 dictionary. You cannot use native SQL on these tables. Pool or cluster tables are logical tables, which are arranged as records of transparent table.
A table is made up of rows and columns. When the table is created, its columns are named; data type is supplied for each column. There can be only one data value in each column of each row in a table. Record or as it is called in different RDBMS is nothing but group of fields. While a column is a field of a table, a table is an indexed file. The main index is called as primary key, which can be a single field or combination of keys or fields. A primary key can be defined as a field, which indefinites a single unique record of the table. A table cannot have record with duplicate primary key.
In any RDBMS, tables are related to each other. But to relate table to each other it is necessary that one of the tables contain some information of other table. Mostly tables are related to each other through primary keys. The primary key of one table, if it exists in other table then it is called foreign key. This type of database management system means that there is some redundancy of data. But using normalization procedures available can minimize it. One of the most important functions of foreign key is to ensure data integrity. For example say you have EMP table, which has fields: emp. no., emp.name, dept.code, salary and you have DEPT tables, which has dept.code and dept.desc. Then in DEPT table dept.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 exist in DEPT table. System will check the value for dept.code in DEPT table, and if does not exist then will flash error. In this case DEPT is called check table while EMP is foreign key table.
Creation of table
Steps to create a table
• Create domain
• Create data element
• Create actual table
Creating Domain
Domain as already explained defines the technical properties of a field such as type and value range. A domain can be created from initial screen of data dictionary by clicking on create and clicking domain Radiobutton. Parameters to be passed are:
Data type: Where you need to enter the data type available in SAP.
Field length: Field length is the number of valid position.
Value table: Name of a table to be entered. The fields referring to this domain may only assume values contained in the value table.
Once the domain is created, save and activate it, so that it can be used for further objects (basic rule of dictionary).
Creating Data Element
The second step of table creation is to create data element. It assigns a certain meaning to the table field, which are defined using that data element. A Data element always needs to be defined over a domain and field is always defined over a data element. This allows all fields with same technical properties to use the same data element.
Parameters to be passed when creating a data element:
Short text: Mandatory field.
Domain: A mandatory field. If the domain does not exist, SAP can take you directly to domain definition screen.
Text element: You can enter description is short or long text for the field. This text is used when
entering data for these fields.
Save and activate.
Creation of actual table
Parameters to be passed for creation of table:
Short description: Mandatory field.
Delivery class: As per User Requirement
Table fields: Specify whether primary key. In this case it is mandatory to enter data element.
Data class: Establishes the physical area of the database.
Size category: Allows you to specify estimated space requirement for the table.
Further down under buffering square box, the system allows specifying whether table is going to be buffered. When a table is buffered, it is loaded into the table buffer from the application server memory and it will remain there until you switch off or reboot system.
If the table is to be buffered, you need to specify the type of buffering. Full is for entire table while partial is for only those records which are being accessed.
Once the table is created, it has to be generated or activated to be able to access by other objects like programs.
General Introduction to ABAP/4
SAP originally developed the programming language ABAP/4 (Advanced Business Application Programming) for internal use to provide best working conditions for developers. SAP constantly improves the language to adapt to the increasing requirements of the business applications. At present, ABAP/4 is the only tool for developing applications at SAP.
SAP customers use ABAP/4 for their own developments. The ABAP/4 Development Workbench contains all tools you need to create and maintain ABAP/4 programs. ABAP/4 programs are not complied but generated. During generation, the system creates a so-called runtime object from the source code and the program attributes. When you start the program, the system executes the runtime object.
ABAP/4, a fourth generation language, contains all usual control structures and modularizing concepts for structured programming. The three parts of the ABAP/4 language are:
Structure and execution of ABAP/4 programs
Basic language elements
Programming reports
Programming dialogs
Structure and execution of ABAP/4 programs are essentially different from entirely sequential programming languages such as FORTRAN, PASCAL, or C. ABAP/4 instead shares certain similarities with modular, event-orient programming languages such as Visual Basic or JAVA.
The two most important statements concerning structure and execution are:
An ABAP/4 program has a modular structure.
For execution, you need a special runtime environment.
This means, that ABAP/4 source texts always consist of a collection of program modules (one single module in the easiest case) or the sequential set of statements. The individual program modules consist of sequential elements. The set of statements of a program module is also called processing block.
The runtime environment is responsible for calling the individual program modules one after the other. The runtime environment is the ABAP/4 processor, which can communicate with the list processor or the dialog processor, depending on the program type.
Program flow within the individual processing blocks is sequential, as you know it from other sequential programming languages (for example, FORTRAN, PASCAL and C). Within the processing blocks, you can use the general control statements for the program flow, such as IF, DOES, WHILE, ABAP/4 does not contain GOTO elements.
We mainly use programs that consist of a single processing block only and, therefore, behave most likely like programs of other sequential programming languages. For programming applications, the entirely sequential concept is not sufficient. SAP distinguishes between two general types of application programs:
Reports: You use reports to read databases and represent the results in lists. Reports are collections of processing blocks that the system calls depending on events.
Dialog programs: You can dialog programs to execute transactions, which usually read and change databases. Dialog programs are collections of processing blocks (so-called module pools) that are called by a screen flow logic. The third part of the User’s Guide describes dialog programming in detail.
Reports can call dialog programs and vice versa.
In its easiest version, an ABAP/4 program contains one single sequential piece of coding and, thus, one single processing block.
Characteristics of the ABAP/4 programming languages
• Declarative elements for declaring data of different type and structures.
• Operational elements for manipulating data.
• Control elements to control processing flow.
• ABAP/4 is multi-lingual. Text elements such as titles, headings, and text body are stored separately, independent of the program codes. Thus, you can change, translate, and maintain text elements without having no adapt the coding.
• ABAP/4 supports business-related data types and operations. You can execute calculations using special data and time fields. The system automatically executes all necessary type conversions.
• ABAP/4 provides a number of functions for processing character strings.
• ABAP/4 allows you to define and call subroutines. You can even call subroutines of other programs. There are different ways of how to pass parameters to and from the Subroutines.
• ABAP/4 contains a special type of subroutine, called function module. Function modules are stored and maintained in a central library. They have clearly defined data interfaces to the calling program. You can test function modules in a stand-alone mode independent of the calling program.
• ABAP/4 contains an SQL subset called OPEN SQL. OPEN SQL allows you to read and change database tables independent of the underlying database system.
• ABAP/4 allows you to define and process internal tables that exist only for the execution period of the program. Internal tables efficiently support the usage of database tables and allow you to implement complex data structures in a program.
• ABAP/4 allows you to store data not only in databases but also as sequential files on application and presentation servers.
REPORTS
• Reports are ABAP/4 programs.
• You use reports to evaluation data from database tables. The results of such an evaluation can be displayed on the screen or printed form.
• Reports are stand-alone programs.
• The user can execute reports directly via the program name, for example, by choosing System ® Utilities ® Reporting.
• A report program contains a collection of processing blocks for different events that are always triggered externally. In a report, you can react on events by programming the corresponding processing blocks or ignore the events by not writing the corresponding processing blocks. A report itself never creates events.
• Reports can use logical databases or select statements defined by developer.
• For each application, SAP supplies logical databases. Or you can easily create logical database yourself.
• Event control of a report corresponds to a certain scheme:
When a report is executed, the ABAP/4 processor creates together with the logical database used (if any) a sequence of certain events for which you can program processing blocks. The chronology of the events is (more or less)
Steps involved in creating a Report:
1. Processing the selection screen
After starting a report, the selection screen allows the user to enter limits or control values for further report processing. The report can contain several processing blocks for events during selection screen processing, for example, for checking the input values.
2. Reading the database
After selection screen processing come the events for reading the database. Either the report reads data from relational databases it using the corresponding ABAP/4 statements (open SQL) or leaves this task to a logical database. In the latter case, the logical database creates a sequence of events to allow the report to copy the data.
3. Evaluating data and creating lists
During or after reading the database the report creates the output list. During list creation, several events allow you to layout the output list (for example, layout the page header).
4. Outputting a list
The last part of the processing sequence controlled by the ABAP/4 processor is the list output on the screen or printer. When displaying the list on the screen, user can trigger other reports, that are interactive and are event driven. For example, by clicking the mouse. By programming processing blocks for these events, you change a normal report to a so-called Interactive report. If a report does not contain event keywords, the entire coding of the report belongs to a single processing block, which is called by a standard event. This standard event is triggered directly after processing the selection screen.
DIALOG PROGRAMS
• You use dialog programs to execute transactions. The users of dialog programs in dialog sessions read and change database tables. Apart from the actual data processing (Open SQL), update and enqueue concepts are of great importance when programming dialogs.
• Dialog programs are not stand- alone
• To execute dialog programs, they must be linked to at least one screen that itself is linked to a transaction code. The transaction code determines the initial screen with which the dialog session starts.
• Dialog programs are controlled by screen flow logic
• The actual ABAP/4 dialog program is a so-called module pool. A module pool contains a collection of dialog modules that are called by the screen flow logic.
• To each module pool, at least one, but usually several screens are allocated. Each screen has flow logic. The flow logic consists of PBO (process Before output) and PAI (process After Input) blocks. This flow logic does not use the ABAP/4 programming language and the ABAP/4 Editor tool, but a special statement set and the Screen Painter tool, which you also use to layout screens. The flow logic mainly contains the chronologically ordered calls of the modules in the corresponding module pool.
• The collection of PBO flow logic, screen, and PAI flow logic is called Dynamic program (Dynpro). A module pool must have at least one dynpro. Each screen of a dialog session thus is the visible part of a dynpro, to which also the flow logic belongs. The processing logic of a dialog session is stored in the corresponding module pool in the form of ABAP/4 modules.
• The ABAP/4 modules in the module pool are separated into PBO and PAI modules. The PBO or PAI blocks of the flow logic of each dynpro of a module pool can call each PBO or PAI module of this module pool.
• You can use ABAP/4 statements in the processing logic of the module pool to control the chronology of the different dynpros. After starting a dialog session via the transaction code, which is firmly connected to a dynpro of the module pool, the screen flow logic passes user entries to the processing logic in the ABAP/4 module pool. The processing logic processes the user entries (database accesses) and, if required, defines the appropriate subsequent screens.
Data Types and Data Objects
Data types and data objects are essential components of the ABAP/4 type concepts. Both can be declared and maintained by user. Unlike other programming languages in ABAP/4 you can create DATA TYPES independently.
Data Types
• Are pure descriptions
• No memory is associated with data types.
• Describes the technical properties of data objects.
Structure and definition classify data types. Can be of:
1. Elementary or structured
2. Predefined or user defined
Predefined User-defined
ELEMENTARY C, D, F, I, N, P, T, X Based upon elementary Data types.
You can use directly E.g.,
TYPES: number types I. Can’t allocate memory to types.
STRUCTURED Predefined types are 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 DATA OBJECTS
SPACE & SYSTEM VARIABLES like sy-uname, sy-datum, & sy-repid.
4. SPECIAL DATA OBJECTS
PARAMETERS: are variable, which can accept value from user.
SELECTIONS CRITERIA: are special internal tables to accept value range from user.
Need for Data types:
Consider the following example.
DATA: fname(20),
mname(20),
lname(20),
add1(20),
add2(20),
add3(20).
If you have DATA statement like above, and if you need to change the length of all the fields say from 20 to 25, then you need to change all the fields i.e., going through each and every statement.
But consider the following case where TYPES has been used.
TYPES:str(20)
DATA:fname type str,
Mname type str,
Lname type str,
Add1 type str,
Add2 type str,
Add3 type str.
In this case if you need to change the length of all fields from 20 to 25. Then just change the length of STR and change will be reflected for all the fields.
If you define all the types in TYPE-POOL i.e., global definition of all the types, you can use these types anywhere and in any program.
Parameters
Parameter statement is used to accept input from user. PARAMETER statement is used when you want user to enter data and depending upon what he enters you need to take action. The parameter statement declares the variable and also allows system to accept data into that variable.
Syntax.
Parameters: num type I.
Here parameter statement declares the variable and creates the selection screen on which user enters the data i.e., in this case num is declared of type I and user can enter any number. Entered value is stored in the same variable and can be used in program.
Data: m type I
Parameters: num type I
M = num – 5
Write: / ‘The number is’, m.
You can define default values with parameter statement for example
Parameter: num type I default 12.
In this case when selection screen is displayed the default value is displayed. User can either use same value or overwrite the value.
Parameter of type character and length = 1, can be displayed as Checkbox and Radiobutton.
Parameter: C1 as Checkbox,
C2 as Checkbox.
Parameter: R1 Radiobutton group g1,
R2 Radiobutton group g1.
When parameter is defined as Radiobutton, it needs to be attached to one group. Only one Radiobutton of one group can be clicked.
Every parameter can be associated with language dependent text that is displayed on the selection screen. This can be done with the help of text elements.
WRITE Statement
The basic APAB/4 statement for outputting data on the screen is WRITE.
Syntax:
WRITE
.
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, thousands of separators are also output. If a type P field contains decimal places, the default output length is increased by one.
With the data type D, the internal format of a date differs from its output format. When you use the WRITE statement for outputting data, the system automatically outputs dates of type D in the format specified in the user’s master record (e.g. DD/MM/YYYY or MM/DD/YYYY).
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 to mention the AT, for direct values it is not necessary.
DATA: LEN TYPE I VALUE 10,
POS TYPE I VALUE 11,
TEXT (10) VALUE ‘1234567890’
WRITE AT POS (LEN) TEXT.
This produces the following output on the screen;
The text – 1234567890 – appears in the text.
If the output length is too short, fewer characters are displayed. Numeric fields are truncated on the left and prefixed with an asterisk (*). All other fields are truncated on the right, but no indication is given that the field is shorter.
DATA: NUMBER TYPE I VALUE 1234567890,
TEXT (10) VALUE ‘abcdefghij’.
WRITE: (5) NUMBER, /(5) TEXT.
This produces the following output:
7890
abcde
In the default setting, you cannot create empty lines with the WRITE statement.
WRITE: ‘One’,
/‘ ’,
/ ‘Two’
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 Output is left justified.
CENTERED Output is centered.
RIGHT-JUSTIFIED Output is right justified.
NO-GAP The blank after the field is omitted.
NO-ZERO If a field contains only zeros, these are replaced by blanks. For type C and N fields, leading zeros are replaced automatically.
Formatting options for numeric fields
Option Purpose
NO-SIGN The leading sign is not output.
DECIMALS defines the number of digits after the decimal point.
EXPONENT In type F fields, the exponent is defined in
ROUND Type P fields are multiplied by 10**(-r) and then rounded
CURRENCY Format according to currency in table TCURX.
UNIT 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 one 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 language where you have only internal control, ABAP/4 has internal control and external control of the program flow.
• The internal control is steered by standard keywords as mentioned above. You define this in your program code.
• The external control is stored by events. Events are generated either from other ABAP/4 programs or from interactive user input (like, for example, using the mouse to click on the screen). The system does not necessarily process the statements in the same sequence as they are listed in an ABAP/4 program. This makes ABAP/4 an event-driven programming language. The external control plays an important role mainly for report programs.
Branching with IF statement
The IF statement allows you to divert the program flow to a particular statement block, depending on a condition. This statement block consists of all the commands which occur between an IF statement and the next ELSEIF, ELSE, or ENDIF statement.
Syntax
IF
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 and ELSEIF conditions is true. The end of the last statement block must always be concluded with 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 statement is 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, you need to write WRITE statement for 10 times.
When you want to process a statement more than once, you can write this statement within a loop with the DO statement as follows:
Syntax
DO 5 times.
Write : / name.
ENDDO.
The system continues processing the statement block for 5 times introduced by DO and concluded by ENDDO.
The system field SY-INDEX contains the number of times the loop has been processed so in this case when the loop is over value of sy-index will be 5.
In this case you know that, you want to perform WRITE statement for 5 times. But that is not the case always. Many times you need to terminate the loop depending upon certain conditions. This can be done, by using EXIT or STOP statement.
The important point to remember when you don’t you use TIMES option, is to avoid endless loops when working with the DO statement. If you do not use the TIMES option, include at least one EXIT, STOP statement so that the system can leave the loop.
EXIT and STOP takes you out of that loop.
Looping with WHILE Statement
If you want to process a statement block more than once as long as a condition is true, you can program a loop with the WHILE statement as follows:
Syntax
DATA: M TYPE I VALUE 0.
WHILE M < 10.
WRITE: / M.
M = M + 1.
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 for processing data objects of type C, also known as character strings.
Shift command
To shift the contents of a field, by one position or one character you can use the SHIFT statement. Using SHIFT allows you to shift field contents, byte-by-byte or character-by- character.
With the SHIFT statement, you can execute the following:
String = ‘HELLO’.
String 1 = ‘ALL OF YOU’.
String 2 = ‘WORK HARD’.
Shift string
Shift string1 by 2 places.
Shift string2 right.
Shift string1 by 2 places circular.
The output will be
ELLO – By default if nothing is specified then string is shifted by one position.
L OF YOU – Here the string is shifted by 2 places.
_WORK HARD – In this case the string is shifted to right by one place (with leading blanks)
K HARDWOR – In this case the string is shifted to the left so that 3 characters on the left appear on the right.
Replace command
You use the REPLACE statement.
Syntax
REPLACEWITHINTO[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 replaces 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 one occurrence of particular character while Translate replaces all the occurrences of the character.
When using substitution rules, use the following syntax:
Syntax
TRANSLATE USING .
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 c1 cn INTO c SEPARATED BY s.
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 c AT del INTO cl ... cn.
This statement searches the character field c for delimiter strings and the parts before and after the delimiters are placed in the target fields …..
To place all fragments in different target fields, you must specify enough target fields. Otherwise, the last target field is filled with the rest of the field 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
[+][()]
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 processed for all positions between and the end of the field.
String = string1+3(4).
Assuming that string1 = ‘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 Database. SQL has two statement types: Data Definition Language (DDL) statements and Data Manipulation Language (DML) statements.
TO include SQL statements in an ABAP/4 program, use Native SQL. To avoid incompatibilities between different database tables and also to make ABAP/4 program independent of the database system in use, SAP has created a set of separate SQL statements called Open SQL. Open SQL contains a subset of standard SQL statements as well as some enhancements, which are specific to SAP. Using Open SQL enables you to access any database tables available to the SAP system regardless of the manufacturer be it Oracle, Informix etc.
The difference between Open SQL and Native SQL is as follows:
A database interface translates SAP’s Open SQL statements into SQL commands specific to the database in use. Native SQL statements access the database directly.
Open SQL keywords
Keywords Used for
• SELECT: Reading Data from Database Tables
• INSERT: Adding Lines to Database Tables
• UPDATE: Changing Lines in Database Tables
• MODIFY: Adding or Changing Lines
• DELETE: Deleting Lines from Database Tables
When using Open SQL statements in an ABAP/4 program, you must ensure the following:
1) The database system being addressed must be supported by SAP.
2) The database tables being addressed must be defined in the ABAP/4 Dictionary.
Select statement
The following system fields play an important role in Open SQL operations:
SY-SUBRC
As with other ABAP/4 statements, the return code value in the system field SY-SUBRC indicates after each Open SQL operation whether or not the operation was successful. If an operation is successful, SY-SUBRC = 0. If an operation is unsuccessful – SY-SUBRC <> 0
SY-DBCNT
The value in the SY-DBCNT field indicates how many lines were affected by the operation or how many lines have already been processed.
To read data from a database table, use the SELECT command.
Syntax
SELECT FROM [INTO ] [WHERE ].
This statement has several basic clauses. Each clause is described in the following table.
SELECT FROM 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 :
Syntax
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: returns the sum value of the column
.COUNT: counts values or lines as follows:
-COUNT( * ) returns the total number of lines in the selection.
You must include spaces between the parentheses and the arguments. The arithmetic operators AVG and SUM can only work with numeric fields.
Sometimes you retrieve few columns form database table i.e. you have list in the SELECT Clause and INTO Clause.
If there is a list in the SELECT clause, you must use the INTO clause with the SELECT statement. You can use either a work area or an internal table or list of variables as an argument,
Syntax
TABLES: SFLIGHT.
DATA : CARRIDI LIKE SFLIGHT -CARRID,
CONNID LIKE SFLIGHT –CONNID.
SELECT CARRID CONNID FROM SFLIGHT INTO (CARRID1, CONNID1). WRITE: / CARRIDl,CONNID1.
ENDSELECT.
Many times you retrieve related data from two or more tables. In such cases you use nested selects by linking tables with common primary keys. But as far as possible avoid using nested selects as time required to access nested table is very high.
Syntax
TABLES: SFLIGHT, SBOOK.
SELECT * FROM SFLIGHT WHERE CARRID = 'LH'.
SELECT * FROM SBOOK WHERE CARRID = SFLIGHT -CARRID AND
CONNID = SFLIGHT -CONNIID.
WRITE: / SFLSIGHT-CARRID,SFLIGHT-CONNID,SBOOK-BOOKID,
ENDSELECT.
ENDSELECT.
Some performance hints for Open SQL statements
• Keep the selected dataset small
Keep the number of selected data as small as possible to avoid unnecessary network transports. Use the respective Open SQL statements always with the WHERE clause. Avoid complex WHERE clauses. The system must split up those into single statements for the database system.
Do not use the logical NOT in WHERE clauses but inverted operators instead.
The logical NOT is supported by the database indexes.
• Keep the transferred data small
• Transfer only those columns of a database table that you really need. Avoid SELECT* if you do not want to read all columns of a database. Use a list in the SELECT clause instead. Use aggregate expressions in the SELECT clause to perform calculations instead transporting great amounts of data and calculating thereafter.
• Keep the number of database accesses small
• Use operations on packages of data instead of operations on single data if you want to analyze selected data more than once. To do so, transfer the data in a single operation between tables and internal tables.
• Avoid nested SELECT loops. Instead, work with internal tables and SELECT statements using the FOR ALL ENTRIES addition.
Insert statement
INSERT statement inserts a single record into the database table.
Syntax
Tables: sflight.
Sflight-carrid = ‘LH’.
Sflight-connid = ‘234’.
Insert sflight.
Table sflight is inserted with the record. The SY_SUBRC is returned for this statement. If the entry already exists then the SY_SUBRC is set to non-zero value and you can do processing for existing record by giving some error message.
Update statement
To update database table UPDATE statement is used. This allows you to change either a single record or several records.
You can use UPDATE when you know which record you want to change. But if you do not know whether the primary key of the line you want to insert already exists or not, you can use the MODIFY statement. The MODIFY statement changes existing lines and inserts lines which do not exist.
Sflight-carrid = ‘MN’.
Sflight-connid = ‘454’.
UPDATE SFLIGHT where CARRID = ‘LH’.
Or
TABLES SFLIGHT.
UPDATE SFLIGHT SET PRICE = 1100
WHERE CARRID = ‘LH’.
Here price of sflight will get updated with new price 1100.
Delete statement
To delete records from a database table, you use the DELETE statement.
DELETE FROM SFLIGHT WHERE CARRID = ‘LH’ AND CONNID = ‘454’.
Will delete the single record where conditions are met from SFLIGHT.
You can delete the multiple records from database table by putting all the records, which you want to delete in internal table. For example
DELETE SFLIGHT FROM TABLE ITAB.
In this case whatever you have in internal table will be deleted from SFLIHT.
Note: append internal table with all the entries, which you want to delete.
EXERCISES
SIMPLE WRITE STATEMENTS
1 Write a program, which generates the model list as shown
Use these system fields in your program.
SY-DATUM, SY-UZEIT, SY-UNAME
Maintain the list headings
12/12/97 FIRST PROGRAM
______________________________________________________
This list is generated
on: 12/12/1997
at: 13:40:35
by: ABAP 1
______________________________________________________
2 Create a list as shown
---------------------------------------------------------------------------------------------------
XYZ Co. Pvt. Ltd.
Date: Today’s date Page No. 1
---------------------------------------------------------------------------------------------------
Program name: ZDEMO
SYMBOLS, ICONS AND FORMATTING
1 Write a program to show the following using system variables
(hint: use include and include
Symbols: Icons:
Telephone Checked; okay,
Fax machine Delete,
Hand pointing left, Print
Hand pointing right,
Caution,
Eg : Write sym_phone as symbol, ‘telephone’.
2 Write a program to show a string with different background colours.
eg.
write ‘HEADER’ color col_heading.
(col_heading is abap/4 name for grayish blue colour. Other colours are
col_key for bluish green, col_normal for bright gray, col_background for
gray, col_positive for green, col_negative for red, col_group for violet and
col_total for yellow)
3 Use Format intensified – format intensified off.
Format color - format color off.
Format inverse – Format inverse off
4 Show current time and today’s date.
5 Show a value ‘123456’ as 12:34:56 using ‘using edit mask’.
6 Take a number as ‘0000011’. Suppress all leading zeros.
7 Suppress a sign before a number.
GENERAL PROBLEMS
1 Create an adding machine for numbers.
The two values to be added must be entered on the selection screen as
parameters. Output the result.
2 Create the dividing machine for numbers.
The two values must be entered on the selection screen as parameters.
Output the result.
3 Create your output as shown below.
.
. .
. . .
. . . .
. . . . .
4 Write a program to accept the two numbers from the user and swap the values.
5 Declare a string ‘echo’ and design your output
e
ec
ech
echo
ech
ec
e
DO-ENDDO, IF-ELSEIF-ELSE-ENDIF, CASE-ENDCASE
1 Write a program with Do – Enddo loop.
Display squares of numbers 1 to 10
1 1
2 4
3 9
2 Write a program to accept a number (say 2) from user and create a multiplication table.
2 x 1 = 2
2 x 2 = 4
…………
2 x 10 = 20
3 Accept a number from user and find Factorial of the same. If the number is negative then display some message.
4 Write a program with Do – Enddo loop for first 20 numbers.
- Output should contain only Even number
- Odd numbers should not be displayed
5 Accept numbers and choice ‘EVEN’ or ‘ODD’ from the user and display the numbers in that range according to user’s choice.
6 Write a program with Do – Enddo loop for first 20 numbers.
- Odd numbers & Even numbers should be displayed with alternate intensities. (Use Format intensified – on – off)
7 Create a calculator, which performs the four basic types of calculations on two whole numbers. The two values and the option are to be entered on the selection screen as parameters. Output the result with 2 decimal places.
8 Write separate programs using ‘CONTINUE’ and ‘EXIT’ statements in DO-LOOP.
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 occurrences of ‘p’ to ‘b’.
(use ‘translate’ command)
9 Accept two strings and compare the two strings using ‘co’, ‘ca’, ‘cs’
‘cp’ (out put shall be ‘true’ or ‘false’ for each comparison.)
10 Accept a string ‘ABCDEF’. Output only ‘DEF’ using offset command.
11 Accept first name, last name and middle name
eg. Nandamuri Taraka Ramarao
display as N.T.Ramarao
12 Accept a string. Change all occurrences of a to b.
13 Accept a number and swap first and last digit of the same.
14 Accept a string and display the string in reverse order
15 Accept a string and check for palindrome
DATE PROBLEMS
1 Accept a date earlier to today’s date and find the difference in number of days.
2 Accept a date from user and display first day of the month and last day of the previous month.
3 Accept a date from user and add six months to the date.
4 Accept a date from user and convert month part to ‘jan’, ‘feb’ etc., and display this date.
5 Write a program to accept month. Display number of days in total month.
Make use of
- Text element for your selection screen box.
- Selection text
6 Accept birth date from user and output age in years, months and days.
CHECK BOXES AND RADIO BUTTONS
1 Write a program with
- Parameter as checkboxes
- If checkbox 1 is clicked write c.b 1 clicked else c.b 1 not clicked.
- If checkbox 2 is clicked write c.b 2 clicked else c.b 2 not clicked.
- If checkboxes 1 & 2 are clicked write c.b 1 & c.b. 2 are clicked.
- If checkboxes 1 & 2 are not clicked write c.b 1 & c.b. 2 are not clicked.
2 Write a program with
- Parameters as two groups of Radiobuttons (two Radiobuttons in each group).
- Give detailed coding as above, to show the Radiobuttons and groups
- selected
3 Write a program with
- Parameter as checkbox.
- If you click the checkbox then display first day of the next year.
- If the checkbox is not clicked then display last day of the current year.
4. Write a program with
- Parameter as group of 3 radio buttons
- If first radio button is clicked, display last day of the current month.
- If second radio button, display first day of the next month
- If third radio button, display date after six months.
SELECT STATEMENTS
1 List all the rows from the table VBAK.
2 List single row from the table BKPF.
3 List up to 5 rows from the table BSIS.
4 List all ERDATs. For better readability create a column heading in the list
5 Display total amount for carrid ‘LH’. (Tables: SFLIGHT)
6 List all the flights for which booking date is greater than ’01.06.1995’.
7 List all the flights for which payments currency is ‘DEM’.
8 List all the flights where carrid is between ‘LH’ and ‘SQ’.
9 Select a single record where carrid = ‘LH’, flight-no = ‘0400’ and
fldate = ’28.02.1998’.
10 Display carrid, connid, fldate and luggage weight multiplied by 2
11 List the maximum capacity, occupied seats and total of current bookings for each flight in the following format.
Carrier id Max. capacity Occupied seats Total of current bookings
12 From the given from-city and to-city, list all the available on this route:
From: To: (say from Frankfurt to Madras)
(Tables: SPFL1)
Carrier id Departure Time Start Airport Destination Airport
OPEN SQL
1 Accept document no. from user and display particulars of Sales document. (Default document no. ‘0010000031’)
(Table: VBAP)
Created on: xxxxx
Created by: xxxxx
Time: xxxxx
2 Accept Sales Document number from user and display corresponding material
no, description of that material and item category (Table : VBAP)
3 Accept material no. & item category by default PP100 and KMN respectively
Display corresponding details of sales document (Table: VBAP)
4 Display fields from BKPF.
Document type = ‘AB’ and
Document date = ’05.02.1998’.
Also display number of records selected.
5 Display Co. code, doc.no., acc.type, tax code.
Make use of select-options to give range of document type.
Display title of your program at the end of program
6 Accept doc. no from user.
Display doc.no., doc.status, date of doc., doc.type.
7 Display single record for document where date = ’05.02.1998’, type ‘= ‘AB and document
no. = ‘0100000006’.
8 Accept plant from user eg. PLTP.
Display document details for that plant like doc.no., doc.status, date of document etc.,
DEBUGGING
Many times an error free program doesn’t give desired output. Behavior of program is different in different situations, with different values of variable. Such program needs additional testing, by which you can test the program by stopping at 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 debugger can be started. When executing program, the ABAP/4 debugger is automatically started when the system encounters a breakpoint.
Starting the ABAP/4 debugger
There are many ways to start debugger
• By clicking the Execute button and selecting the debugging mode.
• From the ABAP/4 editor, by executing a program choosing Program Execute Debugging from the menu.
• Setting breakpoint in the program
Components of ABAP/4 debugger
The debugger shows the program information using six different views.
• Fields: Displays the field contents.
• Table: Allows modifying the contents of internal table.
• Breakpoints: Displays list of Breakpoint in the Program.
• Watchpoints: Allows dealing with Watchpoints.
• Calls: System call status like Event, Form etc.,
• Overview: Presents the program structure, events, subroutines, and modules.
• Settings: Displays the calling sequence within a particular event, up to the current breakpoint.
All these options are shown in the following screen.
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 keyboard 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.
• Watchpoints are field specific. The program is stopped when the field reaches the value specified in the watchpoint. Execute the program in debugging mode. Position the cursor over the needed field. Press the F button to get the view of field. Select the checkbox for the needed watchpoint. Click on the continue button.
• Keywords/events The program stops just before executing a specific event or 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 OK.
Navigating through the breakpoint
Following buttons are used to navigate through the program and debugger.
• Single step: Executes a single program command.
• Execute: Similar to the 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 button 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 button to get a view of the fields.
• Select the checkbox for the needed watchpoint.
• Click on the CONTINUE button.
• To display the active watchpoint 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 recognize or 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 a program, three steps are associated with it.
1. Declaration of Internal Table
2. Populating Internal Table
3. Processing Internal Table
Declaration of Internal Table
Depending on how you create, internal tables are of two types.
• Internal tables with header line.
When you create internal tables with header line, and 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 output 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 on internal tables with header line.
Internal table can be declared in the following way:
• 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-f1date
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 database 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
Carrid1 like sflight-carrid,
End of itab.
Here you are specifying different field names.
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: Addition of Table in INTO clause, you omit append itab and Endselect
• Select * from sflight
Move-corresponding sflight to itab.
Append itab.
Endselect.
Note: While using Move-corresponding, field names of DB table & Int’ table should be same.
• Select * from sflight.
Move sflight to itab.
Append itab.
Endselect.
Note: 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.
Endselect.
Processing Internal Table
Processing of internal table includes:
• Writing: write : / itab carrid. (will write only one field)
Loop at itab. (Will 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 with 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.
• Fee itab : Will de-allocate 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 DESCENDING 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 record first by f1 then by f2 and so on (Here f1, f2 are fields).
Control Break Statements
Control break statements are used to create statement blocks which process only specific table lines 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:/ ‘Last Record is reached’.
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 Subroutines
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 the 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
ENDORM.
In this case during subroutine call, the formal parameter are created as copies of actual parameter.
The formal parameters have the memory of their own. Changes made to formal parameter have no effect on the actual parameter.
Like in this case, though 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 value (p_a)
P – a = 15.
ENDORM.
By default system calls all the forms by reference.
In this case, only the address of the actual parameter is transferred to the formal parameters. The formal parameter 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 a.
FORM sub1 changing value (p_a)
P – a = 15.
ENDORM.
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 FORM VALUE OF A IN PROGRAM VALUE OF A IN FORM
(p_a = 15)
BEFORE CALLING FORM A = 20
A = 20 P_A = 100
BY VALUE
(USING)
AFTER RETURNING FROM FORM A = 20 (changing value of p_a)
A = 20.
BEFORE CALLING FORM A = 20
A = 20 P_A = 100
BY REFERENCE
(USING) AFTER RETURNING FROM FORM A = 20 (changing value of p_a)
A = 100
BE VALUE AND RETURN BEFORE CALLING FORM A = 20
A = 20 P_A = 100
(CHANGING) AFTER RETURNING FROM FORM A = 100 (changing value of p_a)
A = 100.
Passing Table to a Subroutine
You can pass internal tables as parameters 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 lies, 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 the list after TABLES in the FORM and PERFORM statements. Internal tables passed with TABLES are always called by reference.
If you pass all internal table with a header line, the table body and the table work area are passed to the subroutine. If you pass an internal table without 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 SUB1, where it is filled using the table work area F_ITAB. And itab is written in main program.
FUNCTIONS
Function modules are special external subroutines 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 your own function modules.
The main difference between a function module and a normal ABAP/4 subroutine is as follows:
Function is stored in central library and has global presence while subroutines are confined to a particular program. Subroutine cannot return values while functions can return values. Unlike functions, subroutine cannot handle exceptions. And last but not least, the difference in the way the parameters are passed to functions.
Declaring data as common parts is not possible for function modules. The calling program and the called function module have separate work in ABAP/4 Dictionary tables.
You use the ABAP/4 Workbench to call, create, and maintain function 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.
The Function Library:
The function library maintains Function Modules, the screen displays following components:
All function names should start with Z_ or Y_ followed by any name.
• Source code
• Documentation
• Administrative info
• Import-export parameters
• Table parameters and exception interface
• Global data
• Main program
(Not necessarily in the same order)
Documentation
The documentation describes the purpose of the function module, lists the parameters for passing data to and from the module, and the exceptions. The parameters of the parameter type I are import parameters, which are used to pass data to the function module. Parameters of the parameter type E are export parameters, which are used to pass data from, the function module to the calling program. Exceptions describe error scenarios, which can occur in function modules.
Import-export parameters
Import parameters correspond to the formal input parameter of subroutines. They pass data from the calling program to the function module.
Export parameters correspond to the formal output parameters of subroutines. They pass data from the function module back to the calling program (which his not possible in subroutines)
Table parameters
Table parameters are internal tables. Internal tables are treated like changing parameters and are always passed by reference.
Exceptions
Exceptions are used to handle error scenarios, which can occur in function modules. The function module checks for any type of error and raise exception and returns SY-SUBRC to the calling program. Main program checks this SY-SUBRC for any errors that have occurred and then takes action accordingly.
Source Code
The ABAP/4 Edit screen displays the ABAP/4 source code of the function module. You can work with the source code in the same way as you would work with normal ABAP/4 programs.
Import parameters, changing parameters, and table parameters can be Optional. This means that you can omit the corresponding actual parameter when you call the function in the calling program. If the parameter is optional and the actual parameter is not specified, you can specify a default value for use in the function module. Export parameters are always optional.
As with subroutines, you can specify the data types of the formal parameters in the field Reference type. In the field Ref. structure, you can specify ABAP/4 Dictionary reference structures or fields. Then, the system checks the current parameter against the structure or field at runtime.
Testing of function module
You can test a function module without calling it from an ABAP/4 program via the Function Library: Maintain Function Modules screen by choosing Single test. You can assign values to the import parameters on the Test Function Modules screen.
Calling Function Modules
To call a function module from an ABAP/4 program, use the CALL statement as follows:
Syntax:
CALL FUNCTION
[EXPORTING
f1 = s1
f2 = s2
fn = sn (parameters which you pass from program to function are
s1, s2, sn)]
[IMPORTING
f1 = r1
f2 = r2
fn = rn (parameters which program receives you pass from function in
r1, r2, rn)]
[TABLES f1 = a1 … fn = an]
EXCEPTIONS notvalid = 1
not correct = 2
OTHERS = 5].
You can specify the name of the function module as a literal or as a variable. Parameters are passed to and from the function module by exactly assigning the actual parameters to the formal parameters in the lists after the EXPORTING, IMPORTING, TABLES.
If in your function if you have raised exception not valid then this exception can be handled in main program. Functions return different sy-subrc for different exceptions.
REPORTS
About reports
Reports, in the R/3 system are online programs whose function is to retrieve data from database and display it or print it for the user. An end user often needs some information to look up, depending upon which various management decisions are taken, or to just see business results or simply to continue work. As R/3 is collection of all business applications, it has provided a very powerful feature to satisfy this crucial business need i.e., reports are involved at each and every step of business. This type of extracting, collecting and formatting data that is stored in database is done by REPORT program.
The program that is written to retrieve and display data is REPORT program and the data that is displayed on the screen when you execute the program is called as LIST (output of the report).
SAP has provided thousands of preprogrammed reports. User just selects a menu option or just one click here and there, displays the report. Often user is unaware that by clicking one button he is executing a complicated report program, which is actually accessing database and then displaying the result. An end user might not feel the necessity of writing a REPORT program but a developer has to develop a report manually using the functions and facilities provided by the R/3 system. How to develop a report using these facilities, is the purpose of this section.
When you display data, you need to display the data, user needs. For example, user wants to see the all the employee, who has joined after 12th December 1997. In this case user has to pass this information, to the system, that he needs only those employee records where joining data is greater than 12th December 1997. For user, it is passing information to the system but for the system it is input from the user. System takes input from the user before it retrieves the data from the database. This is very common requirement of any report as the need of any business is to display data, which is required by user.
Selection criteria
System accepts inputs from user through SELECTION CRITERIA.
Selection criteria are nothing but input fields which allows the user to restrict information given to program for processing further data. If you don’t specify any criteria for selection, your report program produces a long list of data, which might not be needed by the user. Basically, selection criteria are the fields where user enters some value for which he needs information. Through selection criteria user can enter discrete value or ranges. For example, user wants to see all the records of the employees, who have joined between 12th December 1997 and 12th May 1998. This range can be entered in selection criteria. As the user becomes more specific for mentioning the criteria, the list will be smaller and more specific.
Syntax:
SELECT-OPTIONS for .
Field is the variable, which you declare for accepting input from the user.
Table field is reference field.
SELECT-OPTIONS: fld1 for sflight-fldate,
carrid1 for sflight-carrid.
Maximum length of the name Select-Options variable is 8.
When system executes this statement, the selection screen is displayed and is like this.
When you enter the desired information and click on execute button, rest of the program is executed, that is retrieval of data from database, which matches this information and the list is displayed.
Behavior of SELECT-OPTIONS
When the Select-Options statement is executed the system creates the internal table with the same variable name (in this case it will be carrid1). This table is also called as selection table. The main purpose of selection table is to store selection criteria. The table has four standard fields, which are as follows:
• SIGN is a variable, which denotes the system whether the result should be included with those particular criteria. It can contain either I or E. I denotes Inclusion. The criteria are included.
E denotes Exclusion. The criteria are excluded from the result.
• LOW the data type of LOW is the same as the field type of the database table, for which you are using selection criteria. This acts as lower limit of the selection.
• HIGH the data type of HIGH is the same field type of the database table, for which you are using the selection criteria. This acts as higher limit. If you don’t enter HIGH value then the LOW value defines a single value selection.
• OPTION is two-character field, which contains operators like EQ, GT, LT, GE, and LE.
When the user enters both the values i.e., high and low then this field acts as BT (between). If you don’t enter high value then all other operators can be Applicable.
For each Select-Options statement system creates internal table.
Default values for select-options
If you want to display default values for the selection criteria before your screen is displayed, give default values for the selection table fields i.e., low or high.
SELECT-OPTIONS: CARRID1 FOR SFLIGHT-CARRID DEFAULT CARRID1-LOW = ‘LH’ AND CARRID1-HIGH = ‘SQ’.
In this case selection screen is displayed with default values ‘LH’ for lower range and ‘SQ’ for higher range. User can use same values or overwrite these values with new values, whichever he needs.
Standard report
The normal format of any report is as follows:
HEADING FOR THE LIST i.e., header area
LIST HEADERS
Detailed data
At the end of page you can have sub total of page number i.e., footer area
Usually any report has some page headings at the top of page and then data is displayed with column headings, followed by data and at the end of page may be some grand total or page number. Any such report can be displayed by using report program. Such report is called as
Classical Report.
Usually a standard report produced by system is one continuous page of 65k lines. The standard report can be declared as follows;
REPORT ZDEMO
By default the report produced by system is standard report. But when you need to have your report divided into pages of say 20 lines and you want to reserve some area for footer than you need to use following format of report statement:
REPORT ZDEMO line-count 20(3)
Line-size 75.
In this case the line count for one page is 20 lines, in which 3 lines are reserved for footer. You can display your data only in 17 lines. The width of page will be 75 characters.
As all of us know ABAP/4 is event driven language, the ABAP/4 processor controls the execution of events. For example in above report at the end of the page, you want to write the page number, reaching end of page is an event. Or whenever at the top of a page you want to write list headers, then in this event you can write the code for displaying the list headers. Report program is nothing but a set of events either controlled externally or internally. All above events are external events as the top portion of your page is reached on your screen or on your printer and is no way connected to your program. Internal events are those events, which are controlled inside the program i.e., either by if – endif statement or any other decision-making statement.
A sample report program without any events is as follows:
Report zdemo1.
Tables: sflight.
Select-options carrid1 for sflight-carrid.
* For accepting input from user.
Write: ‘This is my first report program’.
Write: / 10 ‘carrier id’, 20 ‘connection id’ 30 ‘flight date’.
* These two write statements are for writing heading and column headings.
Select * from sflight where carrid in carrid1.
Write: / 10 sflight-carrid, 20 sflight-connid, 30 sflight-fldate.
Endselect.
Write: / ‘page number:‘, sy-pagno.
In this case we are writing list headings for report. But these list headings are applicable only for the first page. If your list is spilling over multiple pages, then these list headings are not applicable to other pages. Again in this program, we write page number after all the data is displayed. This is fine as long as you have one page, but the moment your list spills over multiple pages, the page number will be displayed only after all the records are displayed. So in order to have some data like company name or list headings or page number or total of some number field on each page, you need to make use of events.
CLASSICAL REPORTS
Events in Classical report
Events associated with classical report are as follows and each one will be discussed in detail.
• INITIALIZATION
• AT SELECTION-SCREEN
• AT SELECTION-SCREEN ON
• START-OF-SELECTION
• TOP-OF-PAGE
• END-OF-PAGE
• END-OF-SELECTION
In this case first three events are associated with selection screen. Rest of the events are associated with your list.
• INITIALIZATION
We have already seen how to fill default values for the selection criteria. But in many cases you need to calculate the value and then put it in selection criteria. For example, say, you are accepting date from user and you need to fill in the default value for lower range as sy-datum – 30 days and sy-datum for higher range. In this case you are calculating lower range and then filling the criteria. This can be done in INITIALIZATION event. Piece of code to do the above task would look like the following:
Tables: Sflight.
Select-options: fldate1 for sflight-fldate.
INITIALIZATION.
Data: date1 like SY-DATUM.
Date1 = sy-datum – 30.
Fldate1-low = date1.
Fldate1-high = sy-datum.
Append fldate1.
* Here appending is required because fldate1 is int’ table
This event is triggered when you execute your program for the first time i.e., before selection screen is displayed.
• AT SELECTION-SCREEN
When user enters the values in the fields of selection screen and clicks on execute button, this event gets triggered. This event is basically for checking the values entered by the user for the fields of the selection screen i.e., data validity checking. This event is for entire selection screen. For example:
You are accepting carrid, connid, fldate from user and you don’t want to proceed if user enters no value for carrid and fldate. Using AT SELECTION-SCREEN can do this.
Select-options: carrid1 for sflight-carrid,
Connid1 for sflight-connid,
F1date1 for sflight-f1date.
AT SELECTION-SCREEN.
If carrid1-low ne ‘ ’ and fldate1-low = ‘ ’.
Error message.
Endif.
In this case, if both the fields are entered blank, then the user gets error message.
Basically, this event is for many fields on selection screen. Usually, it is for the fields which are logically related.
• AT SELECTION-SCREEN ON
When you want to check for specific value of a field. For example, carrid should be in the range of ‘LH’ and ‘SQ’. This can be done in this event. Basically, this event is for checking individual fields. You can have many AT selection-screen events in your program (i.e., for each field specified in the Select-Options).
Select-Options carrid1 for sflight-carrid.
AT SELECTION-SCREEN.
If carrid1-low ne ‘LH’ and carrid1-high ne ‘SQ’.
Error message.
Endif.
Here the system will not proceed on entering wrong values.
• START-OF-SELECTION
This is the first event for your list. Once all the events are triggered for selection screen, the data is retrieved from database. Data declaration, select statements are done in this event. Consider the following example:
START-OF-SELECTION.
Data: mtype i.
Tables: sflight.
Select * from sflight where carrid = ‘LH’.
Write: / sflight-carrid,sflight-connid.
Endselect.
• TOP-OF-PAGE
This event is triggered with first WRITE statement or whenever new page is triggered. Advantage of using this event is that, whatever you write under this event, is applicable to all the pages. If you don’t have any write statement before TOP-OF-PAGE or in START-OF-SELECTION, this event is not triggered at all. For example, if you want the name of company and column headers for all the pages, it can be written in this event.
TOP-OF-PAGE
Write: / ‘INTELLIGROUP ASIA PVT. LTD.’
Write : / 10 ‘carrid’, 20 ‘connid’, 30 ‘fldate’.
• END-OF-PAGE
This event is triggered at the end of page.
End-of-page.
Write : / ‘page number’, sy-pagno.
In this case page number will be written on every page.
Conditional triggering of EOP
Consider the following case.
REPORT ZDEMO1 line-count 15(3).
Top-of-page.
Write: ‘this line is written by top-of-page event’.
Start-of-selection.
Write: ‘this line is written by start-of-selection event’.
End-of-page.
Write : ‘this line is written by end-of-page event’.
In this case EOP will never be triggered, as end of page is never reached. The total Line-count defined for page = 15 in which 3 lines are for footer area. The output of the above code will be
This line is written by top of page event.
This line is written by start of selection event.
In output screen, only two lines are written and cursor remains still on 3rd line, the end-of-page event is not triggered. To trigger end of page event, cursor should reach at the last position, in this case on 11th line.
Such cases are quite common, and could be overcome by conditional triggering of end of page.
Sy-linct is the system variable, which gives total line count of a list.
Sy-linno is the system variable, which gives the current line number where the cursor is placed on the list.
Consider the following case:
Report zdemo1 line count 20(1).
Start-of-selection.
Data: m type i.
Write: / ‘this is first line’.
Do 5 times.
Write: / ‘the number is’, sy-index.
Enddo.
M = sy-linct, sy-linno – 1.
Skip x.
End-of-page.
Write: / ‘page end’.
The output of above example is as follows :
This is first line.
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
After skipping 10 lines
Page end
In this case, with all write statement, you don’t reach to the end of page. After all write statement, m is calculated in this case:
M = 20 – 8 – 1, So m is 12. And 11 lines are skipped after write statement and end of page is reached. (In this case you have 6 write statement so 6 lines + 1 line for page number and 1 horizontal line which is displayed for any list. So cursor is on 8th line and is subtracted from total line count i.e, 20.)
Common errors that user commits
Stating of another event denotes the end of any event. If you forget to mention the next event then everything is included in the same event. Consider the following case:
AT SELECTION-SCREEN.
If carrid1-low ne ‘ ‘.
Err. or message.
Endif.
Write: / ‘INTELLIGROUP ASIA P. LTD.’
WRITE: / 10 ‘CARRID’, 20 ‘CONNID’, 30 ‘FLDATE’.
START-OF-SELECTION.
….
….
….
In this case all the write statement are included in the `at selection screen’ as top-of-page is not specified. The end of `at selection-screen’ is denoted by the starting of start-of-selection.
Though the sequence of events in program is immaterial, it is a good programming practice to write all the events in the order specified above.
Using Variants with selection criteria
In many cases you need report to execute report at regular interval for certain fixed values of selection criteria. That means each times you execute the report you need to enter its values again and again. ABAP/4 provides the facility by which you can define the values for selection screen and store it. Using VARIANTS can do this. It can be defined as group of values used for selection criteria while executing report. For a particular report, you create a variant which means variant created for particular report cannot be used for another report. The group of values for the selection criteria is saved and assigned a variant name. So every time you call a report, you need not specify the values for selection criteria but instead call the variant thus avoiding extra typing. User can have many variants for a single report. Each of them can be used as different type of information. For example, if a manager wants to see how an employee in personnel department or admin department has performed. He need not enter the department, one has to just execute the report with variant. In case he doesn’t know about the variant, which is available, he can display list of variants attached to the report and values assigned to each variant.
Creating variant
• Execute the report program. The selection screen is displayed.
• Enter the values for selection screen and click on saves.
- System displays the variant screen
• Enter the variant name and description for it.
• Save it.
Usually the variants are useful when you need to execute the report in background, which will be discussed in background processing.
.
INTERACTIVE REPORTS
About interactive report
A classical report consists of one program that creates a single list. This means that when the list is displayed, it has to contain all the requested data, regardless of the number of details the user want to see. This procedure may result in extensive and cluttered lists from which the user has to pick the relevant data. The desired selections must be made before hand and the report must provide detailed information.
This is not possible using the classical report and for this ABAP/4 has provided reporting feature called INTERACTIVE REPORT. The list produced by classical report doesn’t allow user to interact with the system but the list produced by interactive report allows the user to interact with the system i.e., user can tell the system, that he needs further information. Depending upon what the user tells the system, the action is taken. Interactive reporting thus reduces information retrieval to the data actually required.
Interactive reporting allows the user to participate in retrieving and presenting data at each level during the session. Instead of presenting one extensive and detailed list with cluttered information, with interactive reporting you can create a condensed basic list from which the user can call detailed information by positioning the cursor and entering commands.
Detailed information is presented in secondary lists. A secondary list may either overlay the basic list completely or appear in an additional dialog window on the same screen. The secondary list can itself be interactive again. The basic list is not deleted when secondary list is created.
User can interact with the system by:
• Double clicking or pressing F2
• Selecting menu option
Like classical report, the interactive report is also event driven. Both the action mentioned above trigger events and code is written to handle these events. The events triggered by this action are as follows:
• At line-selection
• At user-command
• Top-of-Page During Line-Selection for Secondary Page Header info
Interactive report consists of one BASIC list and 20 secondary list. Basic list is produced by START-OF-SELECTION event. When the user double clicks on the basic list or chooses the menu option, the secondary list is produced. All the events associated with classical report except end-of-page are applicable only to basic list.
AT LINE-SELECTION event
Double clicking is the way most users navigate through programs. Double clicking on basic list or any secondary list triggers the event AT LINE-SELECTION. SY-LSIND denotes the index of the list currently created. For BASIC list it is always 0. Following piece of code shows how to handle the event.
Start-of-selection.
Write: / ‘this is basic list’.
At line-selection.
Write : ‘this is first secondary list’.
In this case the output will be displayed on basic list i.e.
This is basic list.
When user double clicks on this line, the event at line-selection gets triggered and secondary list is produced, i.e.
This is first secondary list.
You can go back to basic list by clicking on F3 or back icon on the standard tool bar. For this list, the value of sy-lsind will be 1.
HIDE technique
In this case thins are much simpler. Consider the case, wherein you display fields from table sflight in basic list. When user double clicks on any sflight-carrid, you are displaying the detailed information related to that particular carrid on secondary list. Hence there is a need to store the clicked carrid in some variable. So that you can access this carrid for next list. ABAP/4 has facility; a statement called HIDE, which provides the above functionality.
HIDE command temporarily stores the content of clicked field in system area.
Syntax:
HIDE .
This statement stores the contents of variable in relation to the current output line (system field SY-LINNO) internally in the so-called HIDE area. The variable must not necessarily appear on the current line.
You have to place the HIDE statement always directly after the output statement i.e., WRITE for the variable . As when you hide the variable, control is passed to next record. While writing, WRITE statement takes that record from header and writes it on to the list, but when writing onto your interactive list you will miss out 1st record.
To hide several variables, use chain HIDE statement.
As soon as the user selects a line for which you stored HIDE fields, the system fills the variables in the program with the values stored. A line can be selected.
• By an interactive event.
For each interactive event, the HIDE fields of the line on which the cursor is positioned during the event are filled with the stored values.
The HIDE area is a table, in which the system stores the names and values of all HIDE fields for each list and line number. As soon as they are needed, the system reads the values from the table. (Please try to find the name of this table.)
Sy-lsind indicates the index of the list and can be used to handle all the secondary lists. When the user double clicks on the line or presses F2, sy-lsind is increased by one and this new sy-lsind can be handled. For example:
Write: / ‘this is basic list’.
• Will create a basic list.
If sy-lsind = 1.
Write: / ‘this is first secondary list’.
Elseif sy-lsind = 2.
Write: / ‘This is second secondary list’.
Endif.
When this code is executed,
• Basic list is produced.
• When the user clicks on the basic list, sy-lsind becomes one.
• AT LINE-SELECTION event is triggered.
• Whatever is written under IF Sy-lsind = 1, gets executed.
• Secondary list is produced.
• Again if user clicks on this list, sy-lsind becomes two.
• AT LINE-SELECTION gets triggered.
• Code written under IF Sy-lsind = 2, gets executed.
A sample program for AT LINE-SELECTION.
User interface
An interactive report starts with basic list where condensed information is stored on basic list and detailed information is stored on secondary list. To implement this kind of reporting, you need to provide the user with things like menu, icons, function keys. You also need to write code, which must react, to the user’s action.
For this, you need to create the interface, which interacts with the user.
The user interface is independent of the program or list or screen. However both interface and list can be associated by means of GUI status. A GUI status groups together the interface components.
• Menu bar
• Application tool bar
• Function keys
• Title bar
The last element of the user interface is independent of the GUI status i.e., titlebar.
To assign status to your list the statement SET PR-STATUS.
Some facts about GUI status are:
• A program can have multiple GUI status and titles for different lists.
• Multiple lists can be assigned to same GUI status.
• Normally both GUI status and title go together.
Function code
An important concept, when working with user interface. Function is a four character alphanumeric code, which the system stores in the system variable called SY-UCOMM for each function key, push button, or menu option. Whenever any push button is clicked or menu option is selected, the code attached to that, is stored in SY-UCOMM and can be handled in your program.
Menu painter
Menu painter is the ABAP/4 workbench tool for creating and maintaining user interface.
Starting Menu Painter
ABAP/4 development workbench menu painter
Or
Transaction SE41 in the command field.
Or
Through program SET PF-STATUS
If you double click on the variable, the system takes you to the menu painter screen.
Creating Menu bar
Steps involved are as follows:
• Enter the name in the first field. It is just a name given to the menu and is not displayed anywhere in the output.
• Enter the name of each menu item. You can create up to six menus (total eight menu items are available, out of which system and help are mandatory).
• Enter name of the menu items and function code. You can have fifteen menu items under one menu.
If you leave function blank, the system assumes that this particular menu item will have submenu. You can create the sub menu items under this menu item. User can go up to three levels.
Creating Application Tool Bar
Assign Function Keys
In Application tool bar you can include icon assigned for function keys.
Procedure:
• Select function key.
• From the menu, more utilities - change text type. The system displays a dialog box, click on icon and presses ENTER.
• Select icon from list of icons displayed
Creating GUI title
From your program, you can set title for your list and SET TITLEBAR is used.
Syntax:
SET TITLEBAR .
Here var can be any three-character name. When developer double clicks on the var, system displays the dialog box in which you enter the title number, the description, and the actual text for title.
Similar to dictionary objects, the GUI status must be generated to be accessible by program.
AT USER-COMMAND
When the user selects the menu item or presses any function key, the event that is triggered is AT USER-COMMAND, and can be handled in the program by writing code for the same. The system variable SY-UCOMM stores the function code for the clicked menu item or for the function key and the same can be checked in the program. Sample code would look like
AT USER-COMMAND.
Case sy-ucomm.
When ‘DISP’.
Select * from sflight.
Write sflight-carrid, sflight-connid.
Endselect.
When ‘EXIT’.
LEAVE.
If GUI status, suppose you have set menu bar for two items and the function code is ‘DISP’ and ‘EXIT’ respectively. If the user clicks the menu item ‘DISPLAY’, then function code ‘DISP’ is stored in the sy-ucomm and whatever is written under the when ‘DISP’, gets executed. This is applicable for EXIT as well.
Sy-lsind for the screen increases when the user clicks the menu item.
Usually you have combination of all the three navigations in your user interface, i.e., you have to create menu bar, assign function code for the function keys and write code to handle all this in addition to handling double clicking.
Things to remember while using all the combinations:
• Sy-lsind increases even if you select menu-item.
• When the user double clicks on particular line, value of sy-ucomm is ‘PICK.
• If you set sy-lsind = 2 for your 4th secondary list, when control is transferred to the 2nd secondary list, all the other lists after 2nd are lost or memory allocated to them is lost.
• Sy-lisel also gives you the value of clicked line but in this case you cannot differentiate between field. To retrieve the exact field, you have to know the field length of each field.
• If you use statement SY-LSIND = 1.
The system reacts to a manipulation of SY-LSIND only at the end of an event, directly before displaying the secondary list. So, if within the processing block, you use statements whose INDEX options access the list with the index SY-LSIND, make sure that you manipulate the SY-LSIND field only after processing these statements. The best way is to have it always at the `as the last statement’ of the processing block.
Important system fields for reports
Sy-linct - Gives total line numbers for a page.
Sy-linno - Gives current line number on the list
Sy-lsind - Index of the lists created in interactive report
Sy-listi - Index of the list from where event was triggered, usually previous list
Sy-lilli - Line number of a list from where event was triggered
Sy-lisel - Contents of a line from where event was triggered
Sy-ucomm - Holds the function code of clicked menu item or function key
EXERCISES
INTERNAL TABLES and REPORTS
1 Create an internal table taking all the fields from BKPF and display fields Company code, Document number, Document type and date of document.
2 Create an internal table taking fields’ Company code, Document number, Account type and Tax code from table BSEG and display the same with column headings.
3 Create an internal table with following fields:
Sales Document and Material from table VBAP.
Date, Name of the user and sales document type from table VBAK and
Price group and customer group from table VBKD.
Sort the table according to Material number and display the contents.
4 Create an internal table called T_BSIS having a similar structure as table BSIS. Explore all possible methods to create the internal table with header line / without header line. (use data types, data … begin of ….end of, data …. data …. Include structure … etc.)
Also create a field string F_BSIS. Populate the internal code and display contents of BSIS. Sort the table according to company code and display contents.
5 Determine for each material type (MTART) the 5 table entries with the highest gross weight (as a ranked list).
To do this, read the table MARA and store the material type (MTART), material number (MATNR), unit of measure (MEINS) and gross weight (BRGEW) into an internal table.
Allow the user to specify the Material type as a parameter on the selection screen.
6 Create a list of the maximum number of available seats for each carrier. To do this, read the table SFLIGHT and store the airline carrier id (CARRID) and maximum number of seats (SEATSMAX) in an internal table. Determine the total number of seats for each airline carrier when filing the int’ table.
7 Read the table SFLIGHT into an internal table and then output the internal table with the fields CARRID, FLDATE and PRICE.
Delete all the internal table entries where the airline carrier (CARRID) is not equal to LH. Read the internal table with entry with the key CARRID = LH and CONNID = 0400, multiply the price by 3 and write the modified entry back to the internal table. Then Output the internal table.
8 Read table TABNA into internal table and output the fields Country, Id, Name1, and Sales. Sort the table with Country.
Delete all internal table lines with sales lower than 50,000.
Read internal table with key ‘GB’ and ‘00000003’ and multiply the sales by 3 and change table entry.
Insert any one record of your choice.
Find out how many lines are there in the internal table.
Remove all the contents of the table.
De-allocate the memory associated with table.
9 Use tables LFA1, LFB1 and LFM1.
Define an internal table with the following:
Lifnr like Lfa1-lifnr,
Bukrs like Lfb1-bukrs,
Ekorg like Lfm1-ekorg.
Add data from these table into the internal tables.
Sort the internal table Lifnr.
Read the internal table with Lifnr = ‘A5’ and change name to trainee.
Put back the record into the table.
Delete first three records of internal table.
Clear header for internal table each time you access a record.
10 Create a report, which will give the existing stock for a material. The report should have subtotal of the stock for each storage location and Grand total of the stock at the end of the plant.
Plant data should start at new page.
Input: Selection screen which will allow one to select a range of materials.
Materials:
Output Report format as follows:
Plant Storage location Material number Description Stock
(unrestricted)
Grand total * * * * * *
Tables and fields:
Material Number MARA-MATNR
Description MAKT-MAKTX
Plant MARC-WERKS
Storage location MARD-LGORT
Stock MARD-LABST
Use Standard Formatting colors.
Exception handling:
Error message “ Material not found “ – if Material not present.
11 Generate a report to list the following details from the tables LFA1 & LFB1 vendor no., vendor name, city, state, telephone no., fax no., company code and terms of payment. User shall have options to select the vendor number range for which the report is generated.
.
Report title: Vendor Master Listing 2
Vendor Name: _____________ Vendor no. : _____________
Address: __________________
Telephone no. _______________ Fax no : ______________
Company code Terms of payments
_____________ _________________
All text used in the report shall be generated using text elements only.
The output list shall have a footer showing page no., date and Intelligroup’(left corner)
12 Generate a report for displaying material description, plant & storage data.
Input: Material number (MARA-MATNR)
Data to be displayed for the following three materials only.
1. BP770M15
2. FP56790031
3. FP28652011
Output format:
11/11/1998 Report to analyze material stocks
Material No. Description
FP96412101 Meditech Patterned Weld Rod
Oatmeal 60’
Plant Storage Loc. Unrestricted stock
xxxx xxxxxxxxxxx xxxxxxxxxxxxxxx
All texts are to be generated using Text Elements only.
Use tables: MARA, MAKT, MARC and MARD.
SUBROUTINES
1. Read a number between 0 and 100 and another digit between 0 and 9. Write a subroutine that will calculate the sum of all numbers (below the limit) that end with the digit. The parameters to be passed are limit and digit both by value and sum by reference.
Ex. If limit = 67 and digit = 4 then sum should be the sum of 4,14,24,34, ..64.
2. Write a subroutine CENTRE-STRING, which will output a string on the center of a line. The subroutine will accept parameters STRING pass by value.
3. Write a program extensively using subroutines to print the equivalent number in words.
For example: if the number is 66, the output should be SIXTY SIX.
Limit the number range from 0 – 99.
Accept the input number as a parameter.
4. Accept a date from the user.
Write a date as dd-mm-yyyy where mm is month written as JAN/FEB/Mar…etc.
Make use of subroutines.
5 For each flight connection, calculate the sales for all flights of an airline carrier. Use internal table for calculating the sales. Use a subroutine for the output by passing the internal table as the parameter.
GENERAL INTRODUCTION TO TRANSACTION
Transaction, in R/3 system is an operation that lets the user make necessary changes to the database. The entire R/3 system is nothing but set of business transaction. The data transfer from old system to SAP R/3 database, or modifying data, or deleting data, which is not required, is done through transaction.
For SAP system, Transaction is nothing but sequence of steps called as dialog steps and for user it is sequence of screens that appears one after the other depending upon the option he selects. The special transaction monitor called the SAP dispatcher handles the sequence of steps that takes place in any transaction. The main task of transaction is to update database table. The database table is not updated until a transaction is completed. All changes can be rolled back if the transaction has not finished.
The transaction contains two steps which are as following:
• Interactive phase: In this step, user enters the data, which needs to be inserted or deleted or modified on to the screen. There can be single screen or multiple screens depending upon the transaction. So this step can consist of single step or multiple steps. In this phase you prepare database record.
• Update phase: This phase processes the database record and updates the database table. Actual updating of database table takes place in this phase.
All the transactions are associated with transaction code. And all these codes are stored in a table TSTC.
Logical Unit of Work (LUW)
The R/3 system is multi user system and many users access the same information at the same time, which is mainly DATA. Consider the case where one user is modifying a record, and second user is trying to delete the same record. If the second user is successful in deleting the record then the first user will face problem for modifying the record that is already deleted. The avoid such situation, R/3 system has provided Logical Unit of Work, which is defined as a locking mechanism to protect transaction integrity. Of course, there are other measures, which ensures data integrity like check table i.e. foreign key relationship. Within SAP system there are three types of transaction and may be distinguished as:
• Database transaction known as LUW. It can be defined as a period in which operation requested must be performed as a unit, i.e. all or nothing operation. At the end of LUW, either of the database changes are committed or rolled back.
• Update transaction or SAP LUW. One SAP LUW can have several databases LUW. So a set of a database is either committed or rolled back. The special ABAP/4 command COMMIT WORK, marks the end of a SAP LUW.
• ABAP/4 transaction. Is made up of a set of related task combined under one transaction code. ABAP/4 transactions are for programming environment, in which ABAP/4 transaction functions like one complete object containing screens, menus and transaction codes.
R/3 system has provided in built locking mechanism, which defines the Logical Unit of Work. Also user can set his own locking mechanism. The LUW starts when a lock entry in the system table is created, and it ends when the lock is released.
To provide the user the facility to communicate with the table in order to modify or delete or insert data, R/3 has provided tool called SCREEN PAINTER. This tool allows you to design screen, process screen through program and update the database table. SAP has provided one and only one way to update the database table, i.e. transaction. Though you can update database table by using open SQL statement through program, SAP usually doesn’t recommend this kind of updating. Many standard transactions are available to update standard table but if the need arises, the developer should be able to develop new transaction, which allows the updating of database tables. This can be achieved by using various components of screen painter.
Following are the few concepts and steps for creating entire new transaction.
DYNPRO concept
A dynpro refers to the screen + flow logic. With screen painter you can develop screen and flow logic. The relationship between screen, flow logic, and program can be shown as follows:
Dynpro, as figure indicates consist of screen and flow logic and places exactly one call to module pool program. A transaction consists of many screens and for each screen flow logic is attached. When the transaction is executed, the screen places a call to flow logic and flow logic in turn places a call to module pool program.
• A module program is usual ABAP/4 program that consist of modules and data declaration.
• ABAP/4 is an event driven language. In module pool program too, events get triggered and these events are handled in flow logic. Flow logic editor is subset of ABAP/4 editor. The system automatically displays the two important events for the flow logic.
• Screen is the important component of dynpro and can be created, designed by screen painter.
Screen Painter
A screen painter can be started by
Development workbench Screen Painter
Or
SE51 transaction code.
Using Screen Painter
The process of creating a dynpro includes the creation and definition of all the needed screen components.
The steps involved in creating the dynpro are as follows:
• Create screen and attributes by using screen attribute screen.
• Select and place the needed fields within the screen by using dict/program fields.
• Establish the field attributes to which the screen belongs by using field list.
• Define the flow logic respect to the transaction to which it belongs by using flow logic.
Creating a new Screen
Steps involved are as follows:
• Enter the name of program and number of the screen
• Click on Create
• On “screen attribute” screen enter short description
• Enter screen type. Normally, you select NORMAL option for usual R/3 screen. Other options available are SUBSCREEN & MODAL DIALOG BOX. Modal dialog box is used to establish independent and interactive dialog box while subscreen is screen within screen.
• Next attribute to be passed is NEXT SCREEN. Here you need to specify the next screen number, which must be processed after the current one.
Designing of Screen
Screen can be designed by using FULL SCREEN EDITOR. You can go to full screen editor.
From screen attribute screen
By pressing full screen editor pushbutton
Or
From initial screen of screen painter.
There are two modes available with full screen editor.
• Graphical mode. The graphical mode works similarly to typical window application.
• Alphanumeric mode (rarely used).
Elements of screen
• Text – Standard text or field labels.
• Entry - display field.
• Radiobutton – All radiobutton must be associated with one group.
• Checkbox – Normally used for YES/NO operations.
• Pushbutton – Used for activating particular function.
• Boxes – grouping together many screen elements.
• Subscreens – This is a screen area in which you can display another screen.
• Table controls – This area of screen is similar to table but should be treated as a loop.
• Status - Display output fields containing icon.
All these elements are on the control bar of full screen editor and can be placed on the screen work area by clicking and placing them wherever needed.
Selecting Screen Fields
Screen field can be either dictionary objects or program fields. Steps involved in the placing of fields on the screen are as follows:
Click the pushbutton Dict/program fields on the full screen editor
Or
Goto dict/prog fields.
• Enter table name.
• Click Get from dictionary.
• Select fields.
• Click copy pushbutton.
• Position the cursor where you want those fields to be placed.
To adjust various screen elements, you can use drag and drop facility for screen elements.
Attributes of Screen Elements
The entire element of a screen has some attributes, which determines their behavior.
• General – These attributes are directly managed by the screen painter like name of the element, or text of element or column width and various things associated with the screen.
• Dictionary – These attributes are applicable to fields, which are from dictionary. Various components of dictionary can be attached to this element like search help, foreign key.
• Program.
• Display – Behavior of the element with respect to their display feature.
Attribute dialog box can be displayed by
• Clicking on the ATTRIBUTE push button on the application tool bar.
• Double clicking on the element.
Field List
This list displays a list of all screen elements together with their screen attributes. One important element of Field list is OKCODE. Any pushbutton is associated with function code as in menu item in menu painter. When the user clicks the pushbutton this code is stored in OKCODE. This OKCODE is created by system without a name and is not visible on the screen. In ABAP/4 this field is work field and is nothing but an area wherein system stores the variable and is the last field of the field list and is invisible, hence user needs to give the name OKCODE. It is not mandatory to give the name OKCODE; developer can give any name to this field.
Screen Flow Logic
You can go to this screen either by
Initial screen of Screen painter Flow logic
Or
From Screen attribute screen Flow logic
When transaction is executed, the screen is displayed, user enters few fields, selects few functions. Later the screen is processed and processing of screen is done by flow logic. The events that are associated with screen are as follows:
• Process before Output (PBO)
• Process after input (PAI)
• Process on value request (POV)
• Process on help request (POH)
The system automatically displays two very important events or modules in flow logic i.e. PAI and PBO
PBO event
This event is triggered before the screen is displayed. The processing of screen before the display of screen is done in this event. For example, filling in default values in the screen fields.
PAI event
This event is responsible for processing of screen after the user enters the data and clicks the pushbutton. The processing of screen can include displaying another screen, or just displaying list or quitting the transaction itself and many more things. Usually it is displaying another screen. These operations can be carried out in the PAI event. OKCODE plays an important role in this operation.
POV event
Process on value request is triggered when the user clicks F4 key. You can handle this event when the user presses F4 key by writing code for the same in module pool program. Normally when the user presses F4, list of possible values is displayed. The standard list produced by system is adequate for applications you develop yourself. However, you can also have the option of setting up your own documentation and lists of possible values that are more detailed.
POH event
Normally when the user places the cursor on the field and presses F1 function key, the system displays its own Help for that particular field. You can add your own functionality to the Help button by writing code for the same in the POH event.
Module Pool Programming
This component though is not attached to the screen painter, plays important role in transaction. Normally, for reports, on line executable programs are written but for transaction, Module Pool Programs are written. The module pool program contains only modules to handle various events associated with screen and data declaration statements.
System divides the module pool program into several include program. These are global field, PBO modules, and PAI modules. It is entirely user’s decision whether to use these modules or write directly into main program.
Creation of Module Pool Program
You can create module pool program either through
Object browser
System automatically creates the module pool program and for these program which are created through object browser, system creates the include modules.
Or
ABAP/4 editor
It is similar to normal program creation. Type of program should be given ‘M’ and is not created by system.
Communication between Dynpro and Module Program
For each screen, the system executes the flow logic, which contains corresponding events. The control is passed to Module Pool Program. Module Pool Program handles the code for these events and again passes back control to the flow logic and finally to screen. Unlike on line program, in this case, the control remains with flow logic. The switching of control between flow logic and module pool program and back is common process when user executes transaction.
Creation of a Complete Transaction
Steps involved to create a complete transaction
• Create module pool program.
• From screen painter create screens.
• Write flow logic for each screen.
• Write code for all the events in module pool program.
• Check for any error in screen and flow logic.
• Generate each and every component of screen i.e. flow logic and screen.
• Single screen can be tested using Screen Painter.
• Create transaction code through object browser.
• Generate the transaction code.
• User can execute the transaction by entering the transaction code in the command field.
Handling Function Code
The function code or OKCODE is the last field of Field list. Function code can be handled as follows:
During the Designing of the screen, a function code is assigned to pushbutton.
• In field list, developer needs to specify OKCODE as last field.
• In module program it is a global field and can be evaluated in the PAI event.
• A function code is treated in the same way, regardless it comes from pushbutton, menu item or any other GUI element.
A complete example for transaction is shown below:
If you have a screen like the one below:
When the user clicks on the Display button, you want to display details of sflight, with corresponding carrid and connid (which is entered by the user).
Module pool program to handle this particular screen is as follows:
Program YVTEST7.
TABLES: SFLIGHT.
DATA: OKCODE (4).
MODULE INPUT1 INPUT,
CASE OKCODE.
WHEN ‘DISP’.
SELECT * FROM SFLIGHT
WHERE CARRID = SFLIGHT – CARRID AND
CONNID = SFLIGHT – CONNID.
ENDSELECT.
LEAVE TO SCREEN 200.
WHEN ‘EXIT’. LEAVE TO SCREEN 0.
ENDCASE.
ENDMODULE. “INPUT1 INPUT
MODULE USER_COMMAND_0200 INPUT.
CASE OKCODE.
WHEN ‘BACK’. LEAVE TO SCREEN 100.
ENDCASE.
ENDMODULE. “USER_COMMAND_0200 INPUT
When the user clicks on display, control is transferred to screen no. 200 on which you display sflight details & on the same screen, when user clicks on BACK button, he comes back to main screen.
Flow logic for screen 100 is as follows:
PROCESS AFTER INPUT.
MODULE INPUT.
Flow logic for screen 200
PROCESS AFTER INPUT.
USER_COMMAND_0200.
MODULES: Modules are handled in module pool program.
You need to write flow logic for screen 200 and design screen 200.
In case of transaction transfer of data from program to screen is automatic i.e. you need not transfer the data from program to screen explicitly. The fields, which you define in the screen receives the data from program and displays the same.
The Field Checks
As already mentioned Transaction is the only method, which SAP recommends to update the database tables. Data entered in the database table should be valid and correct. Data entered is validated at each and every point. ABAP/4 offers various methods to validate data and those are as follows:
• Automatic field checks
• Checks performed in the flow logic
• Checks performed in the ABAP/4 module pool program
Automatic Field Checks
These checks are based on the field information stored in the dictionary. These checks are performed by the system automatically when the user enters the data for the screen field. System performs these checks before PAI event is triggered. Types of field checks performed by system are as follows:
• Required input
While designing the screen, for particular screen field if you click the Req. Entry checkbox, the field becomes mandatory. When the transaction is executed if user leaves this particular field blank, the system displays error message. User cannot proceed until the user enters some data.
• Proper Data Format
Each field has its own data format whether it is table field or screen field. Whenever data is entered, system checks for the proper format of the data. For example date. Each user has its own format for date, which is defined in the user master record. If the date defined in the user master record is in the format DD/MM/YYYY, if the user enters the date, say, in YY/DD/MM, the user displays the error message. System also checks for the value of month or days. For example if month entered is greater than twelve then the error message is displayed.
• Valid Value for the Field
In data dictionary two tables are related by Primary key-Foreign key relationship. Whenever the user enters the data, the system checks for the check table values. Also in Domain, if you have fixed values, then the system checks for these values.
Automatic field checks are repeated each time the user enters the data.
About at Exit – Command
Automatic field checks can be avoided by AT EXIT-COMMAND, which works exactly the same way as Cancel works on application tools bar. In the R/3 screen, if you want to quit the processing of that particular screen without entering the mandatory fields, user can click the Cancel button. Same functionality can be incorporated in the user-defined transaction by using AT EXIT-COMMAND. This module can be called before the system executes the automatic field checks and it goes without saying that before PAI event. Code for AT EXIT-COMMAND in flow logic and in module pool program can be written as follows:
In Flow Logic
Process After Input.
Module exit AT EXIT-COMMAND.
In module pool program.
Module exit.
Case okcode.
When ‘Exit’.
Leave to screen 0.
To achieve this kind of functionality a pushbutton or menu item should be assigned a function type ‘E’. It tells the system to process this particular module before carrying out any field checks.
Flow Logic Validations
Consider the case where you want user to enter only ‘LH’ and ‘SQ’ for sflight-carrid. In this case, you are restricting value of a screen field. This cannot be achieved by automatic field check. Hence there is a need of additional validation. It can be done in flow logic by using following statement:
Field --------------- Values
Syntax
PAI.
Field sflight-carrid values (‘LH’).
For multiple values
PAI.
Field sflight-carrid values (‘LH’ ‘SQ’).
Field sflight-price values (between 1000 and 2000).
In this case when the user enters the value, PAI is triggered and field is checked for that particular value. If the value entered happens to be wrong, that field is enabled for user to enter. If you have multiple Field statements in your flow logic, it is sequential execution.
Consider the following case:
PAI.
Module assign.
Field sflight-carrid values (‘LH’ ‘SQ’).
In ABAP/4
Module assign.
Data: carrid1 like sflight-carrid.
Carrid1 = sflight-carrid.
Endmodule.
In this case, Sflight-carrid is used in the flow logic before the field statement. The system will give invalid value or some previous value as the field sflight-carrid is used in module before it is checked i.e., field statement is after the module in which sflight-carrid is being used. The field is not available to the system unless it executes the field statement. Field statement transfers the values to the program and is done only once. If you don’t have Field statement in your flow logic, transfer of values takes place in PAI event.
Consider one more case where you have multiple field statement.
PAI.
Field Sflight-carrid values (‘LH’).
Field Sflight-connid values (‘0400’ ‘0500’).
In this case if the user enters only carrid wrong, then this particular field is enabled and rest of the fields are disabled for user to input. Many times if the user enters wrong value for one field, then you might want to give option to user to enter all the fields, which is not possible by using Field statement only. This functionality can be achieved by CHAIN – ENDCHAIN.
Syntax
Chain.
Field sflight-carrid value (‘LH’).
Field sflight-connid values (between ‘200’ and ‘500’).
Endchain.
Field sflight-price values (‘100’ ‘1000’).
In this case, if the user enters wrong value only for carrid, both the fields i.e. carrid and connid are enabled as they are grouped together in the Chain statement. The field price will be disabled for input. Usually, logically related fields are grouped together with Chain-Endchain statement.
Module Pool Program Validations
Checking fields ABAP/4 program includes
• Field statement in flow logic.
• Module statement in ABAP/4 module pool Program.
Syntax
PAI.
Field sflight-carrid module .
This module can be handled in the main program i.e. module pool program.
In ABAP/4 program
Module Check.
Select single * from sflight where carrid = sflight-carrid.
If sy-subrc ne 0.
Message e001.
Endif.
In this case, field sflight-carrid is checked in the table for its existence.
Dynamically Calling the Screens
About Displaying Next Screen
Transaction is a sequence of screens, which are displayed one after the other. The next screen displayed depends upon the attributes of first screen. In attributes you need to give Next Screen number i.e. if next screen displayed should be 200 screen, then this number should be given in next Screen attributes. These are static attributes of the screen. By default, if nothing is specified in the program, the system branches out to the screen number, which is specified in the attribute screen.
But this doesn’t happen always. If you have many pushbuttons on the screen like the one in the following case:
In this case, if user selects MARA pushbutton, then fields from Mara table are displayed. When the user clicks on the MARD, then the fields from MARD table are displayed. Depending upon users selection, the screen is branched out and this has to be done during runtime. This functionality can be achieved by dynamically calling the screen in module pool program.
The screen can branch out to new screen depending upon user selection. Following command in module pool program can do this:
• SET SCREEM
• CALL SCREEN
• LEAVE TO SCREEN
All these commands override the specifications given in the attributes. This overriding is temporary. The values stored in the attribute are not changed.
Set Screen
Syntax
Set screen .
In module pool program
Case okcode.
When ‘DISP’.
Set screen 200.
When ‘LIST’.
Set screen 300.
Endcase.
In this case, the entire processing of current screen takes place and then the system branches out to next screen. If you want to branch out to the next screen without processing the current screen, LEAVE SCREEN should be used along with the SET SCREEN.
For Example:
Case okcode..
When ‘DISP’.
Set screen 200.
Leave Screen.
When ‘LIST’.
Set screen 300.
Leave Screen.
Endcase.
When SET SCREEN is used, control cannot be transferred to the main screen or previous screen, unless you write code for the same.
Call Screen
Usually used for pop up screens. Many times, there is a need for user to enter additional information or secondary information on another screen or pop up screen. Once the user enters the data, he should be able to go back to main screen or to the screen where he started. This is not possible by using SET SCREEN. CALL SCREEN achieves this functionality.
Syntax
Call Screen 200.
Will simply call a screen number 200 from a main screen. Once the screen is displayed the user can enter all the data and return to the main screen by clicking BACK button.
To call screen as pop up screen the syntax is
Call screen starting at
Ending at .
In this case window will be popped as window and user can close it by using BACK button.
Leave to screen
To SET a new screen without processing current screen, you need to use the following two statements together:
SET SCREEN 200.
LEAVE SCREEN.
Or a Single statement
LEAVE TO SCREEN 200.
Subscreens
A subscreen is a screen within screen. Consider the following case.
If user clicks on FIRST pushbutton, you want to display details of MARA table and if user clicks on the SECOND pushbutton, you want to display details of MARD table. You can do this by calling two different screens. But the information will be displayed on the next screen. Displaying data on the same screen is possible by using SUBSCREENS.
Step to create a subscreen are as follows:
• Create a subscreen area on MAIN screen and name it.
• Create a separate screen of subscreen type.
• Arrange the fields on this screen so that they fit in subscreen area exactly. Only when it is larger, the part of the screen that fits in the main area will be visible.
• Write code for calling subscreen in flow logic.
To call subscreen, from your flow logic, you need to include the statement both in PAI and PBO.
Syntax
PBO.
Call subscreen including <’screen no’>.
PAI.
Call subscreen .
Area - is the name of the area on main screen.
Prg. Name - is the name of the module pool program.
Screen number - is subscreen screen number.
Some of the don’ts with subscreen are:
GUI status cannot be set to the subscreen
• OKCODE is not applicable to the subscreen.
• Subscreen cannot call another screen.
• It cannot contain AT EXIT-COMMAND.
You can call multiple subscreen in the same area (at any given point of time, only one subscreen can be called in the subscreen area) and is done dynamically during runtime by using variable screen number.
Table Controls
A table can be created in transaction. These tables when designed on the screen are called as SCREEN TABLES. These screen tables are of two types viz.
• Table controls
• Step loops
Though these are tables when code is written to handle them, the tables are treated as loops.
Features of Table Controls
• Data is displayed in the form of table when many records match the criteria.
• Table control gives user the feeling of an actual table.
• You can scroll through the table vertically and horizontally.
• You can select rows and columns
• Resize the width of a column
• You can have separator lines in between rows and columns
• Automatic resizing of the table when the user resizes the window.
In general table control includes all the features of an actual table and user gets the feeling that he is actually working with table. You can update information in table control and it can be updated in the database table by writing code for it.
Steps associated for creating complete screen table are as follows:
• Declaration of table control in module pool program.
• Designing of table control on the screen.
• Passing data to table in flow logic.
Declaring of Table Control in the Module Pool Program
Syntax
Controls TCI type Tableview using screen
When you use table control in a screen you must declare the structure in module pool program. Important fields of tableview are as follows:
• Lines – number of displayable rows in a table.
• Top_line – the row of table where the screen displays start.
• Current_line – The row currently being processed inside a loop.
When you process the table control in flow logic depending upon where you want to start display of rows, you need to use these variables.
Designing Table Control on Screen
• To design table control on the screen, you need to click on Table in control bar and place it on the screen. You can adjust the length and width of table control.
• Name the table control. (Here you need to use same name which you have used for declaration of table control in module pool program)
• From dictionary object, select table fields and place them in the table control.
Passing data to Table Control
As already mentioned, table controls are tables but are treated like loops. Usually transfer of data from program to screen is automatic. But in case of table control, transfer of data is not automatic. You need to explicitly transfer the data to table control. ABAP/4 provides loop statement, which is associated with flow logic to transfer the data. Because table control is treated like a loop, data from where it is transferred should be a loop. You cannot transfer the data by only select statement; you need to put the data into internal table. ABAP/4 provides the LOOP statement, which is associated with the flow logic and allows you to loop through the table control and internal tables. In between LOOP-ENDLOOP, you can use most of the flow logic keywords like field values. Module etc.
You need to code a LOOP statement in both PBO and PAI event of the screen. With LOOP statement, you can transfer the data from program to table control and vice versa. That is, if user updates the value in the table control, you can update database table with its value. And this can be done in PAI event. So even if you are not updating database table through the table control, you need to put the LOOP statement in the PAI event also.
Syntax
PBO.
LOOP AT with control cursor
PAI.
Loop at itab.
Proper usage of Table Control is as follows:
In flow logic.
PBO.
LOOP AT ITAB WITH CONTROL TC1 CURSOR TC1-TOP_LINE.
MODULE ASSIGN.
ENDLOOP.
PAI.
LOOP AT ITAB.
ENDLOOP.
Considering, we have following fields in table control and the screen looks like this:
In module pool program
CONTROL TC1 Type tableview using screen 200.
Module assign.
Sflight – carrid = itab – carrid.
Sflight - connid= itab - connid.
Sflight - fldate= itab – fldate.
Endmodule.
The transfer of the data from program to table control takes place in steps and these steps are as follows:
• With LOOP AT statement the first row is picked up and placed in the header of the internal table.
• Whatever statements you have in between LOOP-ENDLOOP are executed. In this case, you have Module statement. In Module statement, value of internal table is assigned to table control field.
• The row in internal table is transferred to the first line of the table control as stated in the LOOP AT statement.
• The system encounters the ENDLOOP statement and Control is passed to the next line of the internal table.
• In the same way, all the records of the internal table are passed to the table control.
STEP LOOPS
Step Loops are type of screen table as already mentioned. Step loops are repeated blocks of field in a screen. Each block contains one or more fields and these blocks are repeated. Step loops aren’t like actual table. You can scroll vertically but not horizontally. Three steps are associated with creation of step loops:
• Creation of step loops on screen, which includes declaring fields on the screen and then defining the step, loops for these fields.
• Passing data to the step loop is exactly similar to the passing of data to table controls.
• In step loop, you don’t need to define the step loop as such in the module pool program but the cursor needs to be defined in the program.
Types of Step Loops
• Static – Static Step Loop (SSL) have fixed size that cannot be changed during the runtime. If user resizes the window, the size of the static step loop is not changed.
• Dynamic – Dynamic Step Loop (DSL) is variable in size. When the user resizes the window, the system increases or decreases the number of the step loop blocks.
You can have only one dynamic step loop and can have as many static loops in your transaction.
Programming with the Static and dynamic step loop is exactly same. For the system or for the user it doesn’t make any difference whether it is static or dynamic step loop. Only attribute, which you fix during designing of the step loop, is type attribute for step loop F for fixed i.e static and V for variable i.e. dynamic.
Writing code for Step Loop in the flow logic.
PBO.
Loop at itab cursor cl.
Module set.
Endloop.
PAI.
Loop at itab.
Endloop.
* Empty loop is must for both table control and step loop
LOOP AT statement for step loops and Table controls is similar. Loop At statement transfers the data to screen table. You need to have the Module to assign the values for the screen table.
In module pool program you need to define the cursor.
Date: CL TYPE i.
* Cursor parameter tells which line of step loop display should start.
“Module Set” in module pool program assigns the values to step loop fields, which is similar to table controls.
Branching to List Processing
Switching To List Mode
You can display a list within a transaction.
You can produce a list from module pool program by using the command
Leave to List-Processing.
This statement switches the system from dialog mode to list mode. And from this point onwards until you return to dialog mode, you can use all the normal report statement like write, select or any other event.
Returning back from LIST mode
You can return back to dialog mode by clicking the BACK button.
You can have your GUI status and write code for the same. You can include the command LEAVE LIST-PROCESSING. When the system reaches this command, it leaves the list mode and returns to the dialog mode.
Help & Value Request
In any transaction, When the user presses F1 or ? on a field, System provides the help facility for that particular field. In dialog program, when F1 is pressed, help provided by R3 system is sourced from data element documentation. If this documentation is not present for that particular field or if user needs to display additional information for that particular field, then user defined help can be provided through PROCESS ON HELP REQUEST.
In ABVP/4 help can be provided to the user by:
Data element documentation: The F1 help can be enhanced, by adding an additional text for the data element in ABAP/4 dictionary.
It can be done with the help of following steps:
Place cursor on the screen field,
GOTO DOCUMENTATION DATA ELEMENT DOCUMENT
You can now extend the existing help.
USING THE PROCESS ON HELP-REQUEST.
If you don’t have this event in a program, then the documentation of the field in the ABAP/4 dictionary is taken into consideration. If this event exits in the program then it is executed.
Process on HELP-REQUEST event
This event is triggered when user presses F1 on a screen field. You need to handle this event in flow-logic by specifying the fields and attaching the module to it.
Syntax
PROCESS ON HELP –REQUEST.
FIELD SFLIGHT-CARRID MODULE HELP-FOR-CARRID.
In module pool program
MODULE HELP.
Write : `This is field is from sflight table’
Write : / ‘It is of four Character’.
ENDMODULE.
When the user presses F1 on this particular field, then this message will be displayed on the screen.
Value Request
Whenever the user presses F4 on the screen field list of possible values, particular fields are displayed. If the standard value-help is inadequate or if you want to display additional fields or with different combination of fields, developer can program this in PROCESS ON VALUE-REQUEST event in the flow-logic and subsequent module in the module pool program. When the user presses F4, list of possible values are displayed either from matchcode objects or check table or help view or domain. Each one of them is explained briefly.
Matchcode objects: Are aggregated dictionary objects and detailed procedure to create these objects is explained in the later part of the material.
Check Table: If a check table is assigned to the table field and if the user presses F4 for that particular field, then all the key fields are displayed.
Domain Values: The values defined in the domain are displayed. These values are set in domain when the domain is created in the dictionary.
Help views: In cases where the check table is not sufficient, you can create a help view with this check table, which gives additional information like explanatory text for the fields of the check table.
PROCESS ON VALUE_REQUEST.
Each time the user presses F4 on the screen field, following algorithm is called internally.
When the user presses F4 on flight number, the following screen is displayed.
The screen displayed is pop-up screen and code for the flow logic and module is written below:
Flow-logic code
PROCESS ON VALUE-REQUEST.
FIELD SFLIGHT-CONNID MODULE HELP-FOR-CONNID.
Code for module pool program.
MODULE HELP-FOR-CONNIDINPUT.
DATA: BEGIN OF ITAB OCCURS 0,
CONNID(50),
END OF ITAB.
REFRESH ITAB.
ITAB-CONNIDI= POSSIBLE VALUES FOR CONNECTION ID’.
APPEND ITAB.
SELECT CONNID FROM SFLIGHT INTO TABLE ITAB.
CALL FUNCTION ‘POPUP_WITH_TABLE_DISPLAY’
EXPORTING
ENDPOS_COL = 45
ENDPOS_ROW = 25
STARTPOS_COL = 10
STARTPOS_ROW = 1
TITLETEXT = ‘TEXT’
IMPORTING
CHOISE = Some Integer Variable
TABLES
VALUETAB = ITAB
EXCEPTIONS
BREAK_OFF =1
OTHERS =2.
ENDMODULE. “HELP-FOR-CONNID INPUT
Changing The Screen During Runtime
The attributes are assigned to the screen field when the screen is designed in full screen editor. Such kind of assignment is static, which means that these attributes are fixed. But many times the need to change the attributes of the screen arises. And this has to be done during runtime.
Need To Change Screen
There can be a requirement in the transaction that, certain fields on the screen
Appear only in certain conditions.
Are in Change/display mode according to user inputs
Become mandatory subject to specific inputs.
Changes its format depending upon certain conditions.
Modifying the screen
At the runtime, attributes for each screen field is stored in system defined internal table, with header line, called as SCREEN TABLE. It contains name of field and its attributes. This tab le can be modified during the runtime i.e. through module pool program. Screen table has following fields:
Field Name Length Description
NAME 30 Name of screen field
GROUP1 3 Field belongs to field group1
GROUP2 3 Group 2
GROUP3 3 Group 3
GROUP4 3 Group 4
ACTIVE 1 Hide/Show
REQUIRED 1 Field input is mandatory
INPUT 1 Enable/Disable
OUTPUT 1 Field for display only
INTENSIFIED 1 Field is highlighted.
INVISIBLE 1 Field is suppressed.
LENGTH 1 Field output length is reduced
DISPLAY 3D 1 Field is displayed with 3-D Frame
VALUE_HELP 1 Field is displayed with Value help
E.g., SCREEN-ACTIVE = 0 has the same effect as the following statements.
SCREEN- INPUT = 0.
SCREEN-OUTPUT = 0.
SCREEN-INVISIBLE = 1.
The fields SCREEN-NAME and SCREEN-GROUP 1 through SCREEN-GROUP4 tell you which field and / or field group has the attributes.
You can assign up to 4 groups to a field.
You need to program screen modifications in module, which is processed during the event PROCESS BEFORE OUTPUT.
`SCREEN’ is an internal table and, in order to change the field values, LOOP statement has to be used so that the header-line can be populated with the new values, changing the earlier values, the SCREEN table consisted for the specific screen. Finally the changed record in the header-line is NOT APPENDED, but is MODIFIED to the SCREEN table. That is, we first use `LOOP AT SCREEN’ and then assign the values. And finally PRIOR TO ENDLOPP give `MODIFY SCREEN’.
PROCESS BEFORE OUTPUT.
MODULE MODIFY_SCREEN OUTPUT.
MODULE MODIFY_SCREEN.
LOOP AT SCREEN.
IF SCREEN-NAME = ‘SFLIGHT-CARRID’.
SCREEN-INPUT = 1.
MODIFY SCREEN.
ENDIF.
ENDLOOP.
ENDMODULE.
Working with Matchcode Objects
A Matchcode is an aggregated object and it gives list of possible values for the user. A matchcode is a collection of search terms on which you retrieve a data from the database table.
All matchcode are associated with either selection criteria or parameters. When an input field has a little triangle in the right-hand corner, it indicates that it has an associated matchcode. When you click on drop-down arrow or press F4 button, it gives a list of all possible values. For example Matnr field i.e. material number from MARA table, user might not know all the material number, but they might know other details like material description, type or any other details. You can create matchcode, which has all these search terms i.e. you can create matchcode with description as search term or matchcode with type as search term.
R/3 system includes many predefined matchcode but developers can create new matchcode as is created in following case. Usually, system displays list of possible values for all the primary keys with particular search term. Usually you create matchcode in following cases:
When you use non-primary key of input.
You need different search term for the primary key.
Creating Matchcode object
Entire Matchcode object is created in two steps:
Defining of Matchcode object.
Defining one or more search ids for the object.
Defining Matchcode object
It includes all the tables and fields, which make up the Matchcode, which are used for Matchcode Ids.
Steps for defining Matchcode object are as follows:
From dictionary, enter name (four character).
Select Matchcode radiobutton and click on CREATE.
Define attributes for the object i.e. description.
Select primary table.
Select the fields for the table by clicking on the fields.
Activate the object.
If at all you are selecting secondary table then it is done after selecting primary table.
And steps are as follows:
Tables Choose secondary table. A dialog box appears, which displays list of possible secondary tales. Select the table by Choose copy.
To activate the object, Matchcode object - activate
Creating Matchcode ids.
Once the object is created, you need to define search term for the object and steps are as follows:
Click on the Matchcode ID from maintenance screen.
Enter attributes for the Matchcode Id.
Short text.
Update type - Default is 1 for logical updating. It means that at the moment when you access the Matchcode object, the table is created like view. Unlike logical updating, physical updates are: A,S,P.
System Matchcode: If you click this particular field, it indicates a system matchcode, which is used by SAP software and cannot be changed by the end user.
Autho.checks: If it is checked, the system performs authorization checks for this matchcode Id.
Selecting secondary tables
Position the cursor on the base table of the ID.
Edit Choose secondary tables
A dialog box appears listing the tables linked to the table by foreign keys
Select table.
Save.
Selecting fields for Matchcode Id
Select fields.
Choose fields.
Once all the fields are selected, click on copy fields.
Fields are transferred to the matchcode Id.
Activation of Id
A corresponding database view is created in the database during activation for the Ids of update type I. During activation, a check is made to see whether the corresponding index to support view selection exists in the database. If it doesn’t, a warning is displayed.
Testing the Matchcode Id.
To test the matchcode Id:
Maintain matchcode object.
Utilities display matchcode data.
Using Matchcode
When the user do not know which matchcodes are available for a field, user can find the matchcode by:
Positioning the cursor on a field and clicking on drop arrow or pressing the F4 key.
A dialog box appears with a list of available matchcode
User can select another matchcode by clicking on the NEW selection button.
Double click on a matchcode to use it. If you want to use this as default matchcode, click on standard button. If user does this once, the selected matchcode is proposed automatically the next time.
You can enter the search term and press ENTER. If search term is not specified, the system displays all the records for the specific matchcode.
Lock Objects
In a system where many users can access the same data, it becomes necessary to control the access to the data. In R/3 system this access control is built-in on database tables. Developers can also lock objects over table records.
To lock an object you need to call standard functions, which are automatically generated while defining the lock object in ABAP/4 dictionary. This locking system is independent of the locking mechanism used by the R/3 system. This mechanism also defines LUW i.e. Logical Unit of Work. Whenever an object is locked, either by in built locking mechanism or by function modules, it creates corresponding entry in global system table i.e. table is locked. The system automatically releases the lock at the end of transaction. The LUW starts when a lock entry is created in the system table and ends when the lock is released.
Creating Lock Objects
Lock object is an aggregated dictionary object and can be defined by using the following steps:
o From initial data dictionary screen, enter the name for the object, Click Lock object radiobutton and then click on Create. The system displays a dialog box for Maintain Lock Objects screen
o Enter short text as usual and the name for primary table.
o Save
o Select Tables option
From this screen you can:
Select secondary tables, if any, linked by foreign key relationship.
Fields for the lock objects. This option allows you to select fields for objects (R/3 system allows locking up to record level). Lock object argument are not selected by user but are imposed by the system and includes all the primary keys for the table.
Types of locks
You can lock the table or record by using following types of locking:
Exclusive (E) the locked data can only be displayed or modified by single user i.e the owner of the object. Access to other users is denied.
Shared (S) several users can access the same record simultaneously, but only in display mode and except the first one, who has asked for the data in update mode.
Exclusive not cumulating (X) it is similar to exclusive lock. It allows only a single user access. E can be called several times from the same transaction. In contrast, a lock type X can be called only once during the transaction. Any other call for this lock is rejected.
Activation of Lock Object
When you activate the lock object, the functions are automatically generated. And these are ENQUEUE-EZN and DEQUEUE-EZN. EZN is name of the lock object.
While ENQUEUE is used in program to set the code over the selected data depending upon the lock object arguments. DEQUEUE is used to release the lock.
EXERCISES
1. Create a matchcode for MARA-MATNR with one matchcode ID. The fields in the ID should be MARA_MATNR., MARD-WERKS. MARD-LGORT. MAKT-MAKTX.
2. Create a GUI status of type list with the following features and attach it to a report. (Create a simple report with Write statement).
Use the statement SUBMIT REPORT AND RETURN TO CALL A REPORT.
Menu
REPORTS SYSTEM HELP
Materials
Vendors
Exit
Application tool bar: 3 push button - Material, vendors, exit.
When material push button or menu option is chosen to display a list a materials with the following fields:
MARA-MATNR, MARD-WERKS,MARD-LGORT,MAKT-SPRAS.
When vendor pushbutton or menu option is chosen, display a list of vendors with the following fields.
LFA1-LIFNR, LFA1-NAME1, LFA1-ORTO1.
Exit to quit the program.
3. Create a transaction with three screens
Screen 1:
Radiobutton : 2 R1,R2.
Pushbutton :2-Next, Exit,
When NEXT button is pressed, display screen 2 or screen 3 on the radio button selected.
i.e., if R1 is selected display screen 2 or if R2 is selected display screen3.
Screen 2:
Entry fields : SPFLI-CARRID, SPFLI-CONNID,SPFLI-CITYFROM, SPFLI-CITYTO.
Pushbutton : First screen, Exit.
Screen 3.
Entry fields : SFLIGHT-CARRID. SFLIGHT-CONNID.SFLIGHT-FLDATE.SFLIGHT-SEATSMAX,SFLIGHT-SEATSOCC.
Pushbuttons: First screen, Exit.
`Firstscreen’ pushbutton is to display screen 1 and exit is to quit the transaction.
***********USE SELECT-SINGLE*************
4. Create a transaction with on screen.
Screen one
Entry fields: MARD-MANTNR,MARD-WERKS,MARD-LGORT
Pushbuttons: Firstrecord Next Record, Previous record, Last Record, Exit.
Select the data from MARD into an internal table and whenever a button is pressed display the corresponding record (i.e. First, Next, Previous, or Last) using the internal table index.
Exit to quit the transaction.
5. Copy above transaction and enhance it with these features. Place another pushbutton ‘List’. When this button is pressed, Display a list with the following fields. MARD-MATNR,MARD-WERKS,MARD-LGORT.
**********Use LEAVE –TO-LIST-PROCESSING***********
6. Create a transaction with two normal screens and two subscreens.
Screen1 : Normal screen.
Entry fields : MARA-MATNR
Radiobuttons: Plant, Description
Push-button :Display, Exit.
Screen2: Normal screen.
Display fields: MARA-MATNR.
Pushbuttons:Back,Exit.
Screen3: Subscreen.
Display fields: MARD-WERKS,MARD-LGORT.
Screen4: Subscreen
Display fields:MAKT-SPRAS,MAKT-MAKTX.
When the display pushbutton is clicked, display Screen2 with proper subscreen attached to it based on the selection of radio button..
i.e. Screen 3 - if plant is selected and Screen 4 - if description is selected.
BATCH DATA COMMUNICATIONS/BATCH INPUT/INBOUND-OUTBOUND
ABOUT DATA TRANSFER
Implementing a new software system takes major effort. New implementation requires moving data from the present system i.e., legacy system into the R3 system. The product, components, customers and vendors have to be available in the new system. Initial data transfer is the process of populating your R3 database with data from your legacy system.
To prepare for the data transfer there are certain tasks you need to perform.
• First, understand your SAP system to know which data needs to be transferred, e.g., you would not transfer any sales order if you do not use the Sales and distribution module.
• Second, you need to know the contents of existing data in your legacy system.
Data transfer program, an effective and efficient way of transferring large amount of data into your new system, saves time and resources. But more importantly it ensures that accurate data is transferred into R/3.
Two steps involved in data transfer are CONVERSION and SAP DATA TRANSFER.
• CONVERSION, data is converted from your legacy system into the required flat file format.
• SAP DATA TRANSFER, data is automatically entered into the SAP system. A SAP data transfer program reads the prepared data from the flat file and moves it into R/3.
Steps for any data transfer
Preparation for legacy database
This is the first step of transfer though not associated with SAP, plays very important role in data transfer.
Before data is extracted, delete obsolete data in the legacy system and fix inconsistencies. It is easier this way, than doing it during conversion.
The two steps involved in this are:
Data purging: Before transferring data from legacy system, delete all the old and obsolete data, e.g.: To save conversion time and disk space, you may delete all one-time customers, vendors and all unused materials.
Data cleansing: This process corrects data inconsistencies and ensures the integrity of the existing data during the transfer process. Mistakes must be fixed before the transfer.
Converting legacy data to the flat file
For this second step, SAP provides no specific tools.
• In the ABAP/4 development workbench, write an ABAP/4 program to convert a file from your legacy system into the required flat file structure.
• Use other programming language to write conversion program. For C, COBOL, you can easily download the table definition for specific flat file structure.
• Use third party tools, such as format editors and code generators, which support mapping and conversion between different file formats.
• For other RDBMS like oracle, Sybase, MS access, you have EXPORT utility. By which, you can directly export data to flat file.
Files will be discussed in detail in later part of the topic.
Getting the data into R/3
This step actually transfers data to SAP database. After converting the data into the flat file you are ready to begin the third step of the data transfer.
Data transfer is an interactive process. You may often feel like you are taking two steps forward and one step back.
For example, short steps involved in whole process are as follows:
• Convert the data from the legacy system into the flat file format.
• Run the data transfer program.
• Check data for error.
• Is the transfer working as it was designed?
• If not, adjust the data/conversion program and start with step 1. Go back to step one, if you don’t get the desired result.
You have three different options to enter your data into R/3.
• Automatically, with SAP standard data transfer programs.
• Automatically, by creating your own branch input programs
• Manually, by entering the data via the corresponding online transaction.
Automatic transfer with a standard data transfer program
This can be done if:
• A standard program exists for the data transfer of a business object in R/3.
• The data is available in electronic form.
• There is a significant number of records you want to transfer.
• The cost of converting the legacy data into the required flat file format is acceptable.
Manually transferring business objects
You should manually transfer data, if:
• You have no legacy system.
• There is only small number of records to enter.
• Translating legacy data into the R/3 structure is more an effort than manually entering the data.
Using customer specific batch input to transfer business objects
Create batch input program to transfer data if:
• No standard program exists to transfer the business object in R/3.
• The data is available in electronic form.
• There is a significant number of records you want to transfer.
• Translating your legacy data into the structure required by your custom program is easier than manually entering data.
Batch input is a standard procedure for transferring large amount of data into the R/3 system. It simulates manual data entry. Data consistency is ensured because batch input uses all the checks conducted on the normal screen. Using batch input is like entering the data online. Another advantage to batch input is that you do not have to check the data in advance.
Batch input is a two-step procedure. It involves a program that creates the batch input session. This session is the data file that includes everything to begin the transaction and the data to be entered on the appropriate screens. The data is not yet in the database tables of R/3 application. The second step is to process the session, which then actually transfers the data to database table. You can transfer data directly to database table by using CALL TRANSACTION method also. Another method - Direct Input, is done for high volume of data for the standard application. All these methods are discussed in detail in later part of the topic.
Basically there are two steps involved in any transfer of data from legacy system to SAP system.
- Creation of file and transferring file into SAP system
- Transferring data to database file
Whenever, you create flat file following points should be considered:
- Provide the data in an ASCII/Text file format.
- Know how each line of the file is structured.
- Know how the required flat file for the business object must be structured.
- Once your flat file is ready, the data should be transferred into SAP system.
FILE HANDLING IN SAP
Introduction
• Files on application server are sequential files.
• Files on presentation server / workstation are local files.
• A sequential file is also called a dataset.
Handling of Sequential file
Three steps are involved in sequential file handling
• OPEN
• PROCESS
• CLOSE
Here processing of file can be READING a file or WRITING on to a file.
OPEN FILE
Before data can be processed, a file needs to be opened.
After processing file is closed.
Syntax:
OPEN DATASET FOR {OUTPUT/INPUT/APPENDING}
IN {TEXT/BINARY} MODE
This statement returns SY_SUBRC as 0 for successful opening of file or 8, if unsuccessful.
OUTPUT: Opens the file for writing. If the dataset already exists, this will place the cursor at the start of the dataset, the old contents get deleted at the end of the program or when the CLOSE DATASET is encountered.
INPUT: Opens a file for READ and places the cursor at the beginning of the file.
FOR APPENDING: Opens the file for writing and places the cursor at the end of file. If the file does not exist, it is generated.
BINARY MODE: The READ or TRANSFER will be character wise. Each time ‘n’’ characters are READ or transferred. The next READ or TRANSFER will start from the next character position and not on the next line.
IN TEXT MODE: The READ or TRANSFER will start at the beginning of a new line each time. If for READ, the destination is shorter than the source, it gets truncated. If destination is longer, then it is padded with spaces.
Defaults: If nothing is mentioned, then defaults are FOR INPUT and in BINARY MODE.
PROCESS FILE:
Processing a file involves READing the file or Writing on to file TRANSFER.
TRANSFER Statement
Syntax:
TRANSFER TO .
can also be a field string / work area / DDIC structure.
Each transfer statement writes a statement to the dataset. In binary mode, it writes the length of the field to the dataset. In text mode, it writes one line to the dataset.
If the file is not already open, TRANSFER tries to OPEN file FOR OUTPUT (IN BINARY MODE) or using the last OPEN DATASET statement for this file.
IF FILE HANDLING, TRANSFER IS THE ONLY STATEMENT WHICH DOES NOT RETURN SY-SUBRC
READ Statement
Syntax:
READ DATASET INTO .
can also be a field string / work area / DDIC structure.
Each READ will get one record from the dataset. In binary mode it reads the length of the field and in text mode it reads each line.
CLOSE FILE:
The program will close all sequential files, which are open at the end of the program. However, it is a good programming practice to explicitly close all the datasets that were opened.
Syntax:
CLOSE DATASET .
SY-SUBRC will be set to 0 or 8 depending on whether the CLOSE is successful or not.
DELETE FILE:
A dataset can be deleted.
Syntax:
DELETE DATASET .
SY-SUBRC will be set to 0 or 8 depending on whether the DELETE is successful or not.
Pseudo logic for processing the sequential files:
For reading:
Open dataset for input in a particular mode.
Start DO loop.
Read dataset into a field.
If READ is not successful.
Exit the loop.
Endif.
Do relevant processing for that record.
End the do loop.
Close the dataset.
For writing:
Open dataset for output / Appending in a particular mode.
Populate the field that is to be transferred.
TRANSFER the filed to a dataset.
Close the dataset.
Handling of local files
Introduction
Files on presentation server / workstation are LOCAL FILES.
Local files are processed using UPLOAD and DOWNLOAD functions. The local files are brought into ABAP/4 memory using these functions. Unlike dataset, all the records of the file are UPLOADED into an internal table in one shot. Similarly, all records are DOWNLOADED in one shot from an internal table to a local file.
DOWNLOAD function:
Important EXPORTING parameters for this function are:
Filename = name of the local file to which the internal table is to be downloaded.
Filetype = file type, default values are ASC, DAT, BIN
Mode = Write mode, overwrite (‘ ‘) or append (‘A’)
Important IMPORTING parameters are:
Filename = actual file name entered
Tables to be passed to the function:
Data_tab = the internal table that is to be downloaded.
Similar function called WS_DOWNLOAD is used to download the information from internal table to local file. The only difference between DOWNLOAD and WS_DOWNLOAD is that, DOWNLOAD does not require the ‘FILENAME’ and ‘FILETYPE’ to be exported to the function; instead it will ask for the same at runtime. However, for WS_DOWNLOAD, these two parameters need to be passed.
UPLOAD function
Upload function is used to upload the local file to internal table into SAP system.
Parameters passed are similar to DOWNLOAD function.
For uploading, you have similar function called WS_UPLOAD.
Files with multiple record types
Many times the input files will have records with different structures. In all such cases each record will have a field, (usually the first) which identifies the record (e.g., ‘H’ for header, ‘D’ for detail or ‘1’ & ‘2’ etc).
Text tile with multiple record types would be as mentioned below:
Hxxxxyyyyyyyynnnnnnnnn
Daaaaaaaaaabbbbbbbbbcccccccc
Daaaaaaaaaabbbbbbbbbbcccccccc
Hxxxxyyyyyyynnnnnnnnnnn
Daaaaaaaaaabbbbbbbbbbcccccccc
Daaaaaaaaaabbbbbbbbbbcccccccc
Processing Text file with multiple record types:
To process such files, it is necessary to first read the record into a character field that is a minimum of the lengths of the different structure in the file. If ‘H’ type record is 30 char long (including the record identifier) and ‘D’ type is 40 long (including the record identifier), then this character field should be at least 40 char long.
Pseudo logic for processing the sequential files with multiple record types (text mode):
Open dataset.
Do.,
Read dataset into character field.
If sy-subrc ne 0.
Exit.
Endif.
If record id of the char field (or the first of field) is ‘H’
Do processing for ‘H’ type of records.
Else.
Do processing for d type of records.
Endif.
Enddo.
Pseudo logic for processing the local files with multiple record types:
WS_UPLOAD into itab.
Loop at itab.
If itab-recid is ‘H’.
Do processing for ‘H’ type record.
Else.
Do processing for ‘D’ type record.
Endif.
Endloop.
BATCH DATA COMMUNICATION
About Data Transfer In R/3 System
When a company decides to implement the SAP R/3 to manage business-critical data, it usually does not start from a no-data situation. Normally, a SAP R/3 project comes into replace or complement existing application.
In the process of replacing current applications and transferring application data, two situations might occur:
• The first is when application data to be replaced is transferred at once, and only once.
• The second situation is to transfer data periodically from external systems to SAP and vice versa.
• There is a period of time when information has to be transferred from existing application, to SAP R/3, and often this process will be repetitive.
The SAP system offers two primary methods for transferring data into SAP systems. From non-SAP systems or legacy system. These two methods are collectively called “batch input” or “batch data communication”.
1. SESSION METHOD
2. CALL TRANSACTION
3. DIRECT INPUT
Advantages offered by BATCH INPUT method:
1. Can process large data volumes in batch.
2. Can be planned and submitted in the background.
3. No manual interaction is required when data is transferred.
4. Data integrity is maintained as whatever data is transferred to the table is through transaction. Hence batch input data is submitted to all the checks and validations.
To implement one of the supported data transfers, you must often write the program that exports the data from your non-SAP system. This program, known as a “data transfer” program must map the data from the external system into the data structure required by the SAP batch input program.
The batch input program must build all of the input to execute the SAP transaction.
Two main steps are required:
• To build an internal table containing every screen and every field to be filled in during the execution of an SAP transaction.
• To pass the table to SAP for processing.
Prerequisite for Data Transfer Program
Writing a Data Transfer Program involves following prerequisites:
Analyzing data from local file
Analyzing transaction
Analyzing transaction involves following steps:
• The transaction code, if you do not already know it.
• Which fields require input i.e., mandatory.
• Which fields can you allow to default to standard values.
• The names, types, and lengths of the fields that are used by a transaction.
• Screen number and Name of module pool program behind a particular transaction.
To analyze a transaction::
• Start the transaction by menu or by entering the transaction code in the command box.
(You can determine the transaction name by choosing System – Status.)
• Step through the transaction, entering the data will be required for processing your batch input data.
• On each screen, note the program name and screen (dynpro) number.
(dynpro = dyn + pro. Dyn = screen, pro = number)
• Display these by choosing System – Status. The relevant fields are Program (dynpro) and Dynpro number. If pop-up windows occur during execution, you can get the program name and screen number by pressing F1 on any field or button on the screen.
The technical info pop-up shows not only the field information but also the program and screen.
• For each field, check box, and radio button on each screen, press F1 (help) and then choose Technical Info.
Note the following information:
- The field name for batch input, which you’ll find in its own box.
- The length and data type of the field. You can display this information by double clicking on the Data Element field.
• Find out the identification code for each function (button or menu) that you must execute to process the batch-input data (or to go to new screen).
Place the cursor on the button or menu entry while holding down the left mouse button. Then press F1.
In the pop-up window that follows, choose Technical info and note the code that is shown in the Function field.
You can also run any function that is assigned to a function key by way of the function key number. To display the list of available function keys, click on the right mouse button. Note the key number that is assigned to the functions you want to run.
Once you have program name, screen number, field name (screen field name), you can start writing.
DATA TRANSFER program.
Declaring internal table
First Integral Table similar to structure like local file.
Declaring internal table like BDCDATA
The data from internal table is not transferred directly to database table, it has to go through transaction. You need to pass data to particular screen and to particular screen-field. Data is passed to transaction in particular format, hence there is a need for batch input structure.
The batch input structure stores the data that is to be entered into SAP system and the actions that are necessary to process the data. The batch input structure is used by all of the batch input methods. You can use the same structure for all types of batch input, regardless of whether you are creating a session in the batch input queue or using CALL TRANSACTION.
This structure is BDCDATA, which can contain the batch input data for only a single run of a transaction. The typical processing loop in a program is as follows:
• Create a BDCDATA structure
• Write the structure out to a session or process it with CALL TRANSACTION USING; and then
• Create a BDCDATA structure for the next transaction that is to be processed.
Within a BDCDATA structure, organize the data of screens in a transaction. Each screen that is processed in the course of a transaction must be identified with a BDCDATA record. This record uses the Program, Dynpro, and Dynbegin fields of the structure.
The screen identifier record is followed by a separate BDCDATA record for each value, to be entered into a field. These records use the FNAM and FVAL fields of the BDCDATA structure. Values to be entered in a field can be any of the following:
• Data that is entered into screen fields.
• Function codes that are entered into the command field. Such function codes execute functions in a transaction, such as Save or Enter.
The BDCDATA structure contains the following fields:
• PROGRAM: Name of module pool program associated with the screen. Set this field only for the first record for the screen.
• DYNPRO: Screen Number. Set this field only in the first record for the screen.
• DYNBEGIN: Indicates the first record for the screen. Set this field to X, only for the first record for the screen. (Reset to ‘ ‘ (blank) for all other records.)
• FNAM: Field Name. The FNAM field is not case-sensitive.
• FVAL: Value for the field named in FNAM. The FVAL field is case-sensitive. Values assigned to this field are always padded on the right, if they are less than 132 characters. Values must be in character format.
Transferring data from local file to internal table
Data is uploaded to internal table by UPLOAD of WS_UPLOAD function.
Population of BDCDATA
For each record of internal table, you need to populate Internal table, which is similar to BDCDATA structure.
All these five initial steps are necessary for any type of BDC interface.
DATA TRANSFER program can call SESSION METHOD or CALL TRANSACTION. The initial steps for both the methods are same.
First step for both the methods is to upload the data to internal table. From Internal Table, the data is transferred to database table by two ways i.e., Session method and Call transaction.
SESSION METHOD
About Session method
In this method you transfer data from internal table to database table through sessions.
In this method, an ABAP/4 program reads the external data that is to be entered in the SAP System and stores the data in session. A session stores the actions that are required to enter your data using normal SAP transaction i.e., Data is transferred to session which in turn transfers data to database table.
Session is intermediate step between internal table and database table. Data along with its action is stored in session i.e., data for screen fields, to which screen it is passed, the program name behind it, and how the next screen is processed.
When the program has finished generating the session, you can run the session to execute the SAP transactions in it. You can either explicitly start and monitor a session or have the session run in the background processing system.
Unless session is processed, the data is not transferred to database table.
BDC_OPEN_GROUP
You create the session through program by BDC_OPEN_GROUP function.
Parameters to this function are:
• User Name: User name
• Group: Name of the session
• Lock Date: The date on which you want to process the session.
• Keep: This parameter is passed as ‘X’ when you want to retain session after
processing it or ‘ ‘ to delete it after processing.
BDC_INSERT
This function creates the session & data is transferred to Session.
Parameters to this function are:
• Tcode: Transaction Name
• Dynprotab: BDC Data
BDC_CLOSE_GROUP
This function closes the BDC Group. No Parameters.
Some additional information for session processing
When the session is generated using the KEEP option within the BDC_OPEN_GROUP, the system always keeps the sessions in the queue, whether it has been processed successfully or not.
However, if the session is processed, you have to delete it manually. When session processing is completed successfully while KEEP option was not set, it will be removed automatically from the session queue. Log is not removed for that session.
If the batch-input session is terminated with errors, then it appears in the list of INCORRECT session and it can be processed again. To correct incorrect session, you can analyze the session. The Analysis function allows to determine which screen and value has produced the error. If you find small errors in data, you can correct them interactively, otherwise you need to modify batch input program, which has generated the session or many times even the data file.
CALL TRANSACTION
About CALL TRANSACTION
A technique similar to SESSION method, while batch input is a two-step procedure, Call Transaction does both steps online, one after the other. In this method, you call a transaction from your program by
Call transaction using
Mode
Update
Messages into .
Parameter – 1 is transaction code.
Parameter – 2 is name of BDCTAB table.
Parameter – 3 here you are specifying mode in which you execute transaction
A is all screen mode. All the screen of transaction are displayed.
N is no screen mode. No screen is displayed when you execute the transaction.
E is error screen. Only those screens are displayed wherein you have error record.
Parameter – 4 here you are specifying update type by which database table is updated.
S is for Synchronous update in which if you change data of one table then all the related Tables gets updated. And sy-subrc is returned i.e., sy-subrc is returned for once and all.
A is for Asynchronous update. When you change data of one table, the sy-subrc is returned. And then updating of other affected tables takes place. So if system fails to update other tables, still sy-subrc returned is 0 (i.e., when first table gets updated).
Parameter – 5 when you update database table, operation is either successful or unsuccessful or operation is successful with some warning. These messages are stored in internal table, which you specify along with MESSAGE statement. This internal table should be declared like BDCMSGCOLL, a structure available in ABAP/4. It contains the following fields:
1. Tcode: Transaction code
2. Dyname: Batch point module name
3. Dynumb: Batch input Dyn number
4. Msgtyp: Batch input message type (A/E/W/I/S)
5. Msgspra: Batch input Lang, id of message
6. Msgid: Message id
7. MsgvN: Message variables (N = 1 - 4)
For each entry, which is updated in database, table message is available in BDCMSGCOLL. As BDCMSGCOLL is structure, you need to declare a internal table which can contain multiple records (unlike structure).
Steps for CALL TRANSACTION method
1. Internal table for the data (structure similar to your local file)
2. BDCTAB like BDCDATA
3. UPLOAD or WS_UPLOAD function to upload the data from local file to itab. (Considering file is local file)
4. Loop at itab.
Populate BDCTAB table.
Call transaction using
Mode
Update .
Refresh BDCTAB.
Endloop.
(To populate BDCTAB, You need to transfer each and every field)
The major differences between Session method and Call transaction are as follows:
SESSION METHOD CALL TRANSACTION
1. Data is not updated in database table unless Session is processed. Immediate updation in database table.
2. No sy-subrc is returned. Sy-subrc is returned.
3. Error log is created for error records. Errors need to be handled explicitly
4. Updation in database table is always synchronous Updation in database table can be synchronous Or Asynchronous.
Error Handling in CALL TRANSACTION
When Session Method updates the records in database table, error records are stored in the log file. In Call transaction there is no such log file available and error record is lost unless handled. Usually you need to give report of all the error records i.e., records which are not inserted or updated in the database table. This can be done by the following method:
Steps for the error handling in CALL TRANSACTION
1. Internal table for the data (structure similar to your local file)
2. BDCTAB like BDCDATA
3. Internal table BDCMSG like BDCMSGCOLL
4. Internal table similar to Ist internal table
(Third and fourth steps are for error handling)
5. UPLOAD or WS_UPLOAD function to upload the data from the local file to itab. (Considering file is local file)
6. Loop at itab.
Populate BDCTAB table.
Call transaction using
Mode
Update
Messages .
Perform check.
Refresh BDCTAB.
Endloop.
7 Form check.
IF sy-subrc <> 0. (Call transaction returns the sy-subrc if updating is not successful).
Call function Format_message.
(This function is called to store the message given by system and to display it along with record)
Append itab2.
Display the record and message.
DIRECT INPUT
About Direct Input
In contrast to batch input, this technique does not create sessions, but stores the data directly. It does not simulate the online transaction. To enter the data into the corresponding database tables directly, the system calls a number of function modules that execute any necessary checks. In case of errors, the direct input technique provides a restart mechanism. However, to be able to activate the restart mechanism, direct input programs must be executed in the background only. Direct input checks the data thoroughly and then updates the database directly.
You can start a Direct Input program in two ways;
Start the program directly
This is the quickest way to see if the program works with your flat file. This option is possible with all direct input programs. If the program ends abnormally, you will not have any logs telling you what has or has not been posted. To minimize the chance of this happening, always use the check file option for the first run with your flat file. This allows you to detect format errors before transfer.
Starting the program via the DI administration transaction
This transaction restarts the processing, if the data transfer program aborts. Since DI document are immediately posted into the SAP D/B, the restart option prevents the duplicate document posting that occurs during a program restart (i.e., without adjusting your flat file).
Direct input is usually done for standard data like material master, FI accounting document, SD sales order and Classification for which SAP has provided standard programs.
First time you work with the Direct Input administration program, you will need to do some preparation before you can transfer data:
- Create variant
- Define job
- Start job
- Restart job
Common batch input errors
- The batch input BDCDATA structure tries to assign values to fields which do not exist in the current transaction screen.
- The screen in the BDCDATA structure does not match the right sequence, or an intermediate screen is missing.
- On exceptional occasions, the logic flow of batch input session does not exactly match that of manual online processing. Testing the sessions online can discover by this.
- The BDCDATA structure contains fields, which are longer than the actual definition.
- Authorization problems.
RECORDING A BATCH INPUT
A B recording allows you to record a R/3 transaction and generate a program that contains all screens and field information in the required BDC-DATA format.
You can either use SHDB transaction for recording or
SYSTEM SERVICES BATCH INPUT EDIT
And from here click recording.
Enter name for the recording.
(Dates are optional)
Click recording.
Enter transaction code.
Enter.
Click Save button.
You finally come to a screen where, you have all the information for each screen including BDC_OKCODE.
• Click Get Transaction.
• Return to BI.
• Click overview.
• Position the cursor on the just recorded entry and click generate program.
• Enter program name.
• Click enter
The program is generated for the particular transaction.
BACKGROUND PROCESSING
Need for Background processing
When a large volume of data is involved, usually all batch inputs are done in background.
The R/3 system includes functions that allow users to work non-interactively or offline. The background processing systems handle these functions.
Non-interactively means that instead of executing the ABAP/4 programs and waiting for an answer, user can submit those programs for execution at a more convenient planned time.
There are several reasons to submit programs for background execution.
• The maximum time allowed for online execution should not exceed 300 seconds. User gets TIMEOUT error and an aborted transaction, if time for execution exceeds 300 seconds. To avoid these types of error, you can submit jobs for background processing.
• You can use the system while your program is executing.
This does not mean that interactive or online work is not useful. Both type of processing have their own purposes. Online work is the most common one entering business data, displaying information, printing small reports, managing the system and so on. Background jobs are mainly used for the following tasks; to process large amount of data, to execute periodic jobs without human intervention, to run program at a more convenient, planned time other than during normal working hours i.e., Nights or weekends.
The transaction for background processing is SM36.
Or
Tools Administration Jobs Define jobs
Or
System services Jobs
Components of the background jobs
A job in Background processing is a series of steps that can be scheduled and step is a program for background processing.
• Job name. Define the name of assigned to the job. It identifies the job. You can specify up to 32 characters for the name.
• Job class. Indicates the type of background processing priority assigned to the job.
The job class determines the priority of a job. The background system admits three types of job classes: A B & C, which correspond to job priority.
• Job steps. Parameters to be passed for this screen are as follows:
Program name.
Variant if it is report program
Start criteria for the job: Option available for this are as follows:
Immediate - allows you to start a job immediately.
Date/Time - allows you to start a job at a specific name.
After job - you can start a job after a particular job.
After event - allows you to start a job after a particular event.
At operation mode - allows you to start a job when the system switches to a particular operation mode.
Defining Background jobs
It is two step process: Firstly, you define the job and then release it.
When users define a job and save it, they are actually scheduling the report i.e., specifying the job components, the steps, the start time.
When users schedule program for background processing, they are instructing the system to execute an ABAP/4 report or an external program in the background. Scheduled jobs are not executed until they are released. When jobs are released, they are sent for execution to the background processing system at the specified start time. Both scheduling and releasing of jobs require authorizations.
HANDLING OF POP UP SCREEN IN BDC
Many times in transaction pop up screen appears and for this screen you don’t pass any record but some indication to system telling it to proceed further. For example: The following screen
To handle such screen, system has provided a variable called BDC_CURSOR. You pass this variable to BDCDATA and process the screen.
Usually such screen appears in many transactions, in this case you are just passing information, that YES you want to save the information, that means YES should be clicked. So you are transferring this information to BDCDATA i.e., field name of YES which is usually SPOT_OPTION. Instead of BDC_OKCODE, you are passing BDC_CURSOR.
BDC_CURSOR is also used to place cursor on particular field.
AN EXAMPLE WITH SESSION METHOD
Following program demonstrates how data is passed from flat file to SAP transaction and further to database table by using SESSION method.
The transaction is TFBA (to change customer).
A simple transaction where you are entering customer number on first screen and on next screen data is displayed for the particular customer number. Field, which we are changing here, are name and city. When you click on save, the changed record gets saved.
Prerequisite to write this BDC interface as indicated earlier is:
1. To find screen number
2. To find screen field names, type of the field and length of the field.
3. To find BDC_OKCODE for each screen
4. Create flat file.
Flat file can be created in your hard disk as follows:
1 Vinod Krishna Hyderabad
2 Kavitha Secunderabad
3 Kishore Hyderabad
(Where 1st character field is Customer number, 2nd field is Customer name and 3rd field is City.)
To transfer this data to database table SCUSTOM following interface can be used.
REPORT DEMO1.
* Following internal table is to upload flat file.
DATA: BEGIN OF ITAB OCCURS 0,
ID(10),
NAME(25),
CITY(25),
END OF ITAB.
*Following internal table BDCDATA is to pass date from internal table to session.
DATA: BDCTAB LIKE BDCDATA OCCURS 0 WITH HEADER LINE.
* Variables
DATA: DATE1 LIKE SY-DATUM. DATE1 = SY-DATUM - 1. “ This is for Hold Date
* To upload flat file to internal table.
CALL FUNCTION UPLOAD
EXPORTING
FILE NAME = ‘C:\FF.TXT’
FILE TYPE = ‘ASC”
TABLES
DATA_TAB = ITAB
EXCEPTIONS
CONVERSION_ERROR = 1
INVALID_TABLE_WIDTH = 2
INVALID_TYPE = 3
NO_BATCH = 4
UNKNOWN_ERROR = 5
OTHERS = 6.
If sy-subrc = 0.
* Calling Function to Create a Session
CALL FUNCTION ‘BDC_OPEN_GROUP’
EXPORTING
CLIENT = SY-MANDT
GROUP = ‘POTHURI’
HOLDDATE = DATE1
KEEP = ‘X’
USER = SY-UNAME
EXCEPTIONS
CLIENT_INVALID = 1
DESTINATION_INVALID = 2
GROUP_INVALID = 3
GROUP_IS_LOCKED = 4
HOLDDATE_INVALID = 5
INTERNAL_ERROR = 6
QUEUE_ERROR = 7
RUNNING = 8
SYSTEM_LOCK_ERROR = 9
USER_INVALID = 10
OTHERS = 11.
If sy-subrc = 0.
*-------------------------- MAIN Logic------------------------------
LOOP AT ITAB
PERFORM GENERATE_DATA. “ Populating BDCDATA Table
CALL FUNCTION ‘BDC_INSERT’
EXPORTING
TCODE = ‘TFBA’
TABLES
DYNPROTAB = BDCTAB
EXCEPTIONS
INTERNAL_ERROR = 1
NOT_OPEN = 2
QUEUE_ERROR = 3
TCODE_INVALID = 4
PRINTING_INVALID = 5
POSTING_INVALID = 6
OTHERS = 7.
REFRESH BDCTAB
ENDLOOP.
* Calling function to close the session
CALL FUNCTION ‘BDC_CLOSE_GROUP’
EXCEPTIONS
NOT_OPEN = 1
QUEUE_ERROR = 2
OTHERS = 3.
Endif.
Endif.
*&--------------------------------------------------------------------*
*& Form GENERATE_DATA
*&--------------------------------------------------------------------*
* Create BDC Data
*&--------------------------------------------------------------------*
FORM GENERATE_DATA
* Passing information for 1st screen on BDCDATA
BDCTAB-PROGRAM = ‘SAPMTFBA’.
BDCTAX-DYNPRO = 100.
BDCTAP-DYNBEGIN = ‘X’.
APPEND BCDTAB.CLEAR BDCTAB.
* Passing field information to BDCDATA
BDCTAB-FNAM = ‘SCUSTOM-ID’
BDCTAB-FVAL = ITAB-ID.
APPEND BDCTAB.CLEAR BDCTAB.
* Passing BDC_OKCODE to BDCDATA
BDCTAB-FNAM = ‘BDC_OKCODE’.
BDCTAB-FVAL = ‘/5’.
APPEND BDCTAB.CLEAR BDCTAB.
* Passing screen information for next screen to BDCDATA
BDCTAB-PROGRAM = ‘SAPMTFBA’.
BDCTAB-DYNPRO = 200.
BDCTAB-DYNBEGIN = ‘X’.
APPEND BDCTAB.CLEAR BDCTAB.
* Passing screen information to BDCDATA
BDCTAB-FNAM = ‘SCUSTOM-NAME’.
BDCTAB-FVAL = ITAB-NAME.
APPEND BDCTAB.CLEAR BDCTAB.
* Passing screen information to BDCDATA
BDCTAB-FNAM = ‘SCUSTOM-CITY’.
BDCTAB-FVAL = ITAB-CITY.
APPEND BDCTAB.CLEAR BDCTAB.
* Passing BDC_OKCODE to BDCDATA
BDCTAB-FNAM = ‘BDC_OKCODE’.
BDCTAB-FVAL = ‘SAVE’.
APPEND BDCTAB.CLEAR BDCTAB.
ENDFORM. “GENERATE_DATA
AN EXAMPLE WITH CALL TRANSACTION
Same steps to be repeated for CALL TRANSACTION
The only difference between the two types of interface is in Session method, you create session and store information about screen and data into session. When session is processed the data is transferred to database. While in CALL TRANSACTION, data is transferred directly to database table.
REPORT DEMO1.
* Follow above Code till MAIN Logic. Even the Subroutine should be copied
LOOP AT ITAB
PERFORM GENERATE_DATA, “Populating BDCDATA Table
Call transaction ‘TFBA’ using BCDDATA Mode ‘A’ Update ‘S’.
REFRESH BDCTAB
ENDLOOP.
SAP Scripts/Layout Sets/Forms
If the user wants to print documents such as invoices, purchase order, all such documents are printed with the use of forms. SAP allows the user to define these forms by using layout sets. SAP script is the tool used to create the layout set.
In order to print the document, the SAP system runs a program that collects the data for the document and feeds it into the layout set. This is called as Print Program.
SAP Provides a standard layout set for every printable document and usually there is no need to create layout sets as such. User just modifies the existing layout sets as per requirement of client. Following are some standard layout sets provided by SAP:
• RVORDER 01 Sales order confirmation
• RVDELNOTE Picking List
• RVPICKSIN Picking List
• RVINVOICE 01 Invoice
• MEDRUCK Purchase Order
• F110_PRENUM_CHCK Pre-numbered check
Usually you don’t create layout sets, instead, you copy the existing layout sets with some modification to the existing layout sets. SAP doesn’t allow you to modify the layout sets. You need to copy the existing layout set to your own layout set and then do all the modification.
Procedure to copy the existing layout sets.
Tools Word processing Layout sets.
Utilities Copy from client
• Enter the name of the layout set in layout name.
• Enter target layout set name
• Click execute
The SAP standard layout set uses D German as the original language. In order to modify the copied layout set, the original language of the set must be changed to the language in which you are working.
To convert language:
Utilities – Convert original language
Click OK.
Layout Set
Layout set is used to design the document. Layout set on its own does not contain any data. The selection of data for the document is done through the print program i.e. the print program selects the data from database table and feeds it to the layout set. The document is printed after the print program gets executed.
A layouts set consist of following components:
• Header
• Paragraph
• Character String
• Windows
• Pages
• Page Window
Header: The header consists administrative information for the layout sets and default settings for the various other components of the layout sets like page, paragraph. You give all the administrative information for the header when you create the layout set, while all default settings are specified when all the components are created.
Paragraphs: A Paragraph contains all the information needed to format a paragraph of text and font. Tabs are important for paragraphs. Specifying the list of tabs is the way to create columns for outputting line items of a document.
Character string: is used to override paragraph settings for specific words in a paragraph. For example you might want to use Bold for a single word but not the entire paragraph. The only important thing that is defined with the character string is the font.
Windows: A window mainly contains the SAP scripts text and the variable to be printed. There is one special window, MAIN, which contains the output of the line item of a document and is created by the system. The window can be of type VAR or CONST except for the MAIN. But in the present version, SAP system does not distinguish between these two types. The content of variable window is regenerated on every page. The content of a constant window is generated once at the beginning and later printed on every page.
Printing a company logo
There are two ways to print a company logo:
1. The logo can be included in the layout set.
2. It can be a macro on PCL – 5 printers.
Including a logo in the layout sets
• Create logo with a graphics program and save it as tiff file.
• From editor run the program RSTXLDMC.
Parameters to be passed are
• File name
• File type
• BMON – For a black and white image.
• BCOL – For a color image.
• Text name – The standard text in layout set
This text can be included in a layout set by including . Using PCL – 5 printers, can also print the logo. In R3, the printer types are IIPLJIIID, IIPLJ4, LX4039 and SM120XXS.
Control Commands
About control commands:
All script control commands are entered in the SAP Script editor.
• All commands are indicated by /: in the tag column
• Only one control command is allowed per line
• Lines with control commands are not affected by the editor formatting
• If control command is unknown or incorrect, command line is treated as comment line
ADDRESS: This command formats and address according to the postal standards of the country.
Syntax:
/: Address
/: Title ‘Company’
/: Name ‘Intelligroup’
/: Street ‘115’
/: P.O. BOX ` `
/: Postcode
/: City
/: Region
/: Country
/: End Address
BOTTOM-ENDBOTTOM: For the Main window you can determine lines, which are always output automatically at the bottom of that window. This is called footer text.
Syntax:
/: BOTTOM
/: ENDBOTTOM
BOX, POSITION, & SIZE: These commands are used for drawing boxes and are used only during creating output.
Syntax:
/: BOX [Xpos] [Ypos] [Width] [Height] [Frame] [Intensive]
X & Y – Upper left corner of the box.
Width – Width of the box
Ht – Height of the box
Frame – Thickness of the box (Default is full black)
Units used for Width, Height and Thickness are TW, PT, IN, CM, CH, LN.
Ex., /: BOX WIDTH ‘20’ CM HEIGHT 1 IN
FRAME 10 TW INTENSIFY 15.
POSITION
Syntax:
/: POSITION [X Origin] [Y Origin] [Window] [Page]
X & Y - Sets the origin for x 7 y parameters for the box command.
Window - Sets the default values for the left and upper edges.
Pages - Sets the values for the left and upper edges of the current page.
Basically used to set default setting for the box command.
/: Position x Origin ‘1.5’ cm y origin ‘1’ cm
SIZE
Syntax:
/: SIZE [WIDTH] [HEIGHT] [WINDOW] [PAGE]
Sets width and height parameters for the box command.
CASE: It is similar to ABAP/4 editor command ‘CASE’ only symbol can be queried.
Syntax:
/: CASE SYMBOL
/: WHEN 1
/: WHEN 2
/: WHEN OTHERS
/: ENDCASE
DEFINE: Values can be assigned to text symbol by DEFINE keyword. The assigned value may have a maximum 60 characters. It can also contain further symbols.
Syntax:
/: DEFINE & SYMBOL & = ‘XXXX’
IF: With IF command you can define the lines that are output only under certain conditions.
Syntax:
/: IF &var& = ‘char val’
/: ENDIF
INCLUDE: Contents of another text can be included in text by INCLUDE command. The contents are copied only at the time of the output formatting. You can also specify language and the paragraph irrespective of the language in which the calling text is created. The language which is used in include test is used for output.
Syntax:
/: INCLUDE MYTEXT
NEW–PAGE: SAP Script automatically carries out a page break if window MAIN of one page is filled with NEW-PAGE command. You can face page break at any point. The current page is completed and the text in the following line is written on new page. If no name is defined, then, the next page attributes from page setup is taken.
Syntax:
/: NEW – PAGE [PAGE-NAME]
NEW–WINDOW: You can have 99 MAIN windows on one page. If MAIN window is filled, then the next MAIN window is accessed automatically. With NEW-WINDOW command, you can call next main window even if the current MAIN window is not yet completely filled.
PROTECT: You can determine that a paragraph must not be separated by a page break. The lines in this command are printed together on one page. If the space is enough on current page, then all the lines are printed on current page. If, however the space is not sufficient the PROTECT command works as a ‘NEW-PAGE’.
Syntax:
/: PROTECT
/: ENDPROTECT
SET COUNTRY: Some field types are formatted country – specifically. E.G. date. Normally the display types are defined in the user master record with the control command set country, an alternative to that in the user master record can be chosen.
Syntax:
/: SET COUNTRY
SET DATE MASK: Standard display of date can be changed
Syntax:
e.g. SET DATE MASK = ‘MM DDDD (Day in full) yyyy’
You can switch back to default display of date by
/: SET DATE MASK = ‘ ‘
SET TIME MASK: Standard display of time can be changed
Syntax:
/: SET TIME MASK = ‘HH:MM’.
TOP-ENDTOP: For main window, you can determine lines, which are always O/P automatically at the top of the window.
MISCELLANEUOS TOPICS
RUNTIME ANALYSIS
The runtime analysis is an additional development workbench tool that is quite useful for analyzing performance of an ABAP / 4 Program or transaction. With this tool, the system can display information about:
• Executed instruction
• Accessed execution time.
• Tables and Types of access.
• Chronological execution flow
The runtime analysis tool creates lists that reveal expensive statements, summarize table accesses. Runtime analysis is specifically designed for tuning individual programs and transactions.
The Runtime Analysis tool measures ABAP/4 statements that are potentially expensive in terms of CPU time. The most significant of these are:
Statement used for database access like select.
Statement used for modularization such as module, perform, call function.
Internal table statements like append, collect.
Starting Runtime Analysis
• From ABAP/4 development workbench select Test – Runtime Analysis.
• From ABAP/4 editor, select utilities – more utilities – Runtime Analysis.
• From ABAP/ source code screen, select Execute – Runtime Analysis.
• From R3 screen, select System – Utilities – Runtime Analysis.
• Entering Transaction code SE30 in the command field.
Following screen is the initial screen for SE30 transaction.
On the initial screen, select the needed object you want to analyze i.e. program or transaction. Enter the name of the object. Click on execute. The system will execute the specified object and will generate a trace file or performance data file, which can then be analyzed when the transaction or program is finished.
Analyzing a performance data file
These files are created at operating system level and many times occupy large memory space, so be sure to remove the files, which are no longer needed.
To analyze the files:
• Click on Analysis
• Following screen is displayed
• From GOTO option you can get overview of runtime analysis.
The options are as follows:
• Hit List – Displays a list with the most system expensive instructions.
• Tables – Displays the most important tables, the number of accesses and the time needed for the accesses.
• Group hit list – Displays a list with the performed instructions classified by instruction type.
• Call hierarchy – Presents a chronological listing with the flow of calls during the execution of a program.
During Runtime Analysis, the system measures the statements and stores these measurements in a performance data file. If you measure the same program or transaction several times, the data can vary. Many factors make it difficult to reproduce identical result. E.g., Network traffic.
When you evaluate this file, the system displays the overview - Runtime Analysis Evaluation screen including a bar chart for total execution time. From this screen, you can analyze several types of information like:
• Hit list: displays the list with the most `system-expensive’ instructions.
• Tables: displays the most important tables, the number of accesses and the time needed for the accesses.
• Group hit list: displays a list of performed instruction classified by its type.
• Call hierarchy: presents a chronological listing with the flow of calls during the execution of program.
SQL TRACE
The SQL trace is a tool, which allows displaying and analyzing the contents for the database calls, which are made by the reports and transactions written in ABAP/4. It monitors programs and transactions on the database level. With the help of this facility for every open SQL instructions, you can display, about which SQL Embedded (DECLARE, OPEN, FETCH) Statement have been executed, besides analyzing the system performance.
Steps to Creation
• From R3 screen, select system –-> Utilities –-> SQL trace. Or Enter transaction ST05.
• Click the trace on button.
• Enter the user name whose programs are going to be traced.
• Execute the program or transaction you want to trace.
• Return to SQL trace initial screen and press the button SQL trace off. This switching off is necessary because if it is not done then SQL trace will trace each and every program executed by a particular user. And it is quite expensive in terms of memory and time of the system.
Analyzing The Trace File
To analyze the created trace, press the button list trace. Using this file you can see exactly how the system handles database requests. The first screen of the SQL trace data file displays each measured database requests, the application made. The trace file records when the request occurred and its duration.
To display dictionary definition information about the table field, position the cursor on the table field and click on the DDIC info button. When this button is clicked, it displays system information like object name, table class, whether buffering is allowed or not i.e. information related to dictionary.
Explain SQL: This button provides the functionality, which includes the utility for providing detailed information about the SQL Operation Strategy followed by the underlying database system. You need to click on Explain SQL button. The system displays the execution plan for SQL statements. Here you can display the actual SQL statement like Select, which fields are being accessed, Table being accessed, all where conditions.
ABAP/4 Display Gives you the actual ABAP/4 code.
More information gives the detailed information for time, select statement, client, number of records selected etc. Replace variable will display the SQL statement with another variables.
VIEWS
A view is an aggregated dictionary object. Aggregate object or complex object are objects, which are created by using object. E.g., Table is created using data element and domain. A view is created using tables.
A view is an imaginary table or virtual table. Using one or more tables can create a view. Physically, view does not contain any data. The view is filled dynamically during runtime.
View is mainly used to restrict or limit, access to information or data by employees, area, plant and so on. By using view, you can display information specific to a particular user or to their work or the information for which they have the right to access.
Types of Views
R/3 System offers following types of views:
• Database View: You can create this view on transparent table. It supports all the three operations like Selection, Projection & Join
• Projection View: This type allows you to suppress some fields from the transparent table. This view is defined only with relational operator projection.
• Help View: These views are exclusively used by the SAP help system. All relational operators are supported. These views are generated when the user presses F4 function key on the field on selection screen. You can see these views only with SAP help and not with open SQL statements.
• Maintenance View: This type of view enables the maintenance of a group of related tables using SM30 Transaction, which is for extended table maintenance.
Creating View
• From initial screen of data dictionary, enter the name of object i.e. view.
• Select view radio button and click on the push button.
• Dialog box is displayed for types of views.
• Select the view type.
• On the next screen, you have to pass following parameters.
• Short text
• In the table box you need to enter the table names, which are to be related.
• In join table box you need to join the two tables.
• Click on the TABFIELD. System displays the dialog box for all the table fields and user can select the fields from this screen. These fields are displayed in the view fields box.
• Save and Activate: When the view is activated, view is automatically created in the underlying database system. As long as the table exists in the database, the view also exists (Unless you delete it).
Workbench Organizer & Transport System
SAP recommends three types of systems for implementation purpose
• Development System
• Test System
• Production System
Though number of systems used by an organization depends upon many factors such as size of implementation, budget etc. However even in the smallest installation, a second system is a must.
Development system
Development system is the system where the actual development takes place. Normally the development is carried out for objects and these objects are original for these systems.
Test system
Also known as quality assurance system and are used to test the objects. You can test objects on development system also, but on Test System the object is tested against real data. When the tests are validated the development objects are transported to the production system.
Production System
The production system is where the end user enters real business data and where the actual business runs. No development takes place in this system. You need to transfer the object from test system to production system.
The overall flow of objects can be understood in the following diagram:
Developer creates the objects in the development system, these objects are transported to the Test system to test them against the real data and when validated, these objects are transported to the Production System.
To transport these objects from one system to another, ABAP/4 development work bench provides the tool called Work bench organizer which is also used to manage activities that are important in the overall development environment.
Example, for these activities are.
• The management and control of new development requests.
• Modification of objects
• Version management
In a distributed environment, workbench Organizer transports the development object between different SAP systems. In the following example, the objects are transported from the development system to production system.
E.g., between development and Production System
Develop System: New Development No development
Workbench Organizer
The most puzzling topic of R3 system is intended to help functions for system development.
Concepts of workbench
• Development objects: Workbench records and controls change to existing development objects as well as new objects. A development object is an object created in R/3 system. (Program, Screens, Function modules.)
• Dictionary objects: Tables, Domains, Match code objects, Data Elements.
The workbench is fully integrated into the ABAP/4 development workbench.
• Development Classes: A Development class classifies the objects belonging to the same development project. When a user creates a object in R/3 system, the object needs to be stored in a particular development class. The development class are objects themselves. In R/3 system you can store objects.
• In local object i.e. object is stored in $tmp class and cannot be transported from one system to another.
• User can assign his own development class and can be transported.
Transport System
• Developers are in charge of creating or correcting data objects and will create change request, which can be for individual object or common request for a project. When the change request is released the system performs transport
• R/3 administrator is the person who sets up the transport system. This group works both at the R/3 application level and at the operating system level, using transport control (tp) program.
Change Request
A Change request is a list in the system, which mainly contains the object to be transported. It also contains the transport type, the request category and the target system.
When the change request is created either manually or automatically, the system assigns a number to it automatically. This number is known as change request number.
The format of this number is normally
K
E.g., DD1K<900002>
Where DD1 is System Identification Number (SID)
K is keyword
The number is automatically generated by system and starts with 900001.
The change request records all modifications made to development object.
When the changes are made and the change task (will be discussed) has been released, the change request can be released.
SEO9 transaction
Or
Tools -> ABAP/4 W.B -> overview -> W.B. organizer
Will display and check all the change requests.
Tasks
A task in the workbench organizer is an activity in which user either creates an object or modifies the same. In workbench organizer, task can be either development or repair task.
A task is related to single user while change request contains tasks belonging to different users. You cannot transport task as such, but as a part of request. Each task is associated with task number, which is similar to change request number.
Usually, when a development work starts, a system administrator or project manager creates a change request to define tasks for all users involved in the project. Later, user starts modifying objects or create new object. Once user finishes his task, they must release them. A change request can be released for transporting, only when all tasks under the same change request are released.
Objects included in task become locked against other development work on the same object.
Version Management
ABAP/4 workbench and the organizer provide a version management for all the objects in the system. With version management user can compare current version object and object with the previous version.
To display the version for a object,
Locate your object through the change request number of workbench organizer. Click on the object and from menu.
Or
Utilities display version.
It displays what has been modified and who did it.
Version management is important for developers also as it allows user to compare previous programs with the current one.
Transport
A transport means the process of moving something from one place to another. In R/3 system this ‘something’ means change request. To transport the objects you need to create the change request. It can be done with the help of workbench organizer. Transport System and workbench organizer are closely linked to each other.
An object original is a development object that has been created in the system in which you are working.
DD1 PP1
Suppose you transport object Zsus001 to another system, Zsus001 is object original for system DD1. If anyone tries to modify the program, he will be making repair to it, provided he has access key for the same. R/3 system offers this security measure to ensure that development object remain consistent for all system, thus preventing parallel work on the same objects. Correction of objects and development of objects can be only in original system.
The difference between Repair and Correction is as follows:
• If you modify an object in a system in which it is created, you are making Correction to it.
• If you modify an object in a system in which it was not created, then you are making Repair task.
Releasing Tasks and Request
When new development or correction is complete, developer must release their task and request.
To release a task:
• Find a task from the Workbench initial screen.
• Position the cursor over the task.
• Click on the release button
A request is released by either system Administrator or Project Managers, once all the tasks are released