abap

143
http://www.abapprogramming.net/2008/08/sap-abap-complete-course-day- wise.html SAP ABAP Syllabus Syllabus for SAP---ABAP Module Ver 6.0 EE Session 1 · ERP Fundamentals · Introduction to SAP R/3 · Features & Advantages of SAP R/3 · Technical Features of SAP. · SAP R/3 Architecture Session 2, 3, 4 & 5. · ABAP Data Dictionary. · Technical Requirements to Create the Table · Data Dictionary Data types · Domain · Data Element · Steps to create the table · Structure · Foreign key Relationship · Search helps · Views · Lock objects. Session 6 · Introduction to ABAP Programming Lang · ABAP Statements & Key words · Data Types & Data Objects · Elementary Data Types · User defined Data types · Introduction To ABAP Program Session 7 · About Write Statement · Using Like Operator · Control Statements 1) Branching 2) Looping Session 8 · String Operations · Variables · Parameters · Check box · Radio Button · Simple ABAP Programs · System Variables Session 9, 10, & 11 internal tables · Introduction TO Internal tables

Upload: ashishksrivastava

Post on 01-Nov-2014

109 views

Category:

Documents


6 download

DESCRIPTION

Completed Note

TRANSCRIPT

Page 1: ABAP

http://www.abapprogramming.net/2008/08/sap-abap-complete-course-day-wise.html

SAP ABAP Syllabus  Syllabus for SAP---ABAP Module Ver 6.0 EE

Session 1·         ERP Fundamentals·         Introduction to SAP R/3·         Features & Advantages of SAP R/3·         Technical Features of SAP.·         SAP R/3 Architecture

Session 2, 3, 4 & 5.·         ABAP Data Dictionary.·         Technical Requirements to Create the Table·         Data Dictionary Data types·         Domain·         Data Element·         Steps to create the table·         Structure·         Foreign key Relationship·         Search helps·         Views·         Lock objects.

Session 6·         Introduction to ABAP Programming Lang·         ABAP Statements & Key words·         Data Types & Data Objects·         Elementary Data Types·         User defined Data types·         Introduction To ABAP Program

Session 7·         About Write Statement·         Using Like Operator·         Control Statements1)      Branching2)      Looping

Session 8·         String Operations·         Variables·         Parameters·         Check box·         Radio Button·         Simple ABAP Programs·         System Variables

Session 9, 10, & 11 internal tables·         Introduction TO Internal tables·         Purpose of  Internal tables·         Declaring Internal tables·         Populating & Processing Internal tables·         Control break Statements in Internal Tables

Session 12. ABAP Debugger·         Purpose of ABAP Debugger·         Features of ABAP Debugger·         Starting with ABAP Debugger·         Break points.

Page 2: ABAP

Session 13·         About Client in SAP·         Creating Development Class·         Transport system·         Version Management

Session 14, 15, 16 Modularization·         Modularization Techniques·         Introduction & Advantages of Modularization1)      Include Programs2)      Function Modules3)      Subroutines

Session 17 Open SQL Statements·         Open SQL Statements1)      Select2)      Insert3)      Update4)      Delete·         Aggregate Expressions1)      MAX2)      MIN3)      AVG4)      SUM5)      COUNT

Session 18, 19, & 20 REPORTS·         Introduction to Reports·         Types of Report1)      Classical Report2)      Interactive Report3)      ALV Reports

Session 21 Working with Files·         On Presentation Server·         On Application Server

Session 22 LSMW·         Basic Concepts and Steps in LSMW·         Get hands on to LSMW·         Purpose & Advantages of LSMW

Session 23, 24 & 25 BDC·         Batch Data Communication Techniques·         Session Method·         Call Transaction method

Session 26, 27, 28 & 29 Module Pool Programming·         Introduction to Module pool programming·         Concepts of SAP GUI Screen Development·         Working with Screen Painter·         Working with Menu Painter·         Sub-screen·         Working with Tab Strip Control

Session 30, 31 & 32 SAP Script·         Introduction to SAP Script·         Components of Scripts·         Window and its types·         Control Commands

Page 3: ABAP

·         Defining Form Layout and Print Programs

Syllabus for Cross Applications

Session 33, 34 & 35 Smart Forms·         Introduction to Smart forms & Advantages·         Designing of Smart forms·         Types of Windows·         Tables·         Writing Processing Logic·        

Session 36, 37, 38 Exits·         Introduction to Customer/User Exits·         Types of Exits1)      Function Module Exit2)      Screen Exit3)      Menu Exit·         Implementation of Exits

Session 39, 40 BADI & BAPI·         Introduction to BADI & BAPI·         Types  of BADI’s·         Types of BAPI’s·         Implementation of BADI

Session 41, 42, 43, 44 & 45·         Introduction to IDOC’s·         Types of Idoc’s·         IDOC structure·         Creating Segments·         Creating BASIC IDOC Types·         Attaching Segments to IDOc’s·         Linking IDOC type & Message Type·         IDOC Inbound & Out bound Process·         Testing IDOC’s

Session 46, 47 RFC (Remote Function Call)·         Introduction to RFC·         Purpose & usage of RFC·         Developing RFC.

Session 48, 49, 50.·         Business flow in S&D·         Flow in BI/BW·         SQL Trace & Run Time Analysis (ST22)·         Some Real Time Examples with Documentations.

Session DetailsSession # Session Topics Session Details

1 Introduction to SOA Service Oriented Architecture overviewComposition of SOAHow SOA is related to Netweaver

Page 4: ABAP

Unit Test No.1, Questionnaire No.1

2 Introduction to Netweaver Netweaver overviewNetweaver stack

Unit Test No.1, Questionnaire No.1

3 Introduction to Netweaver Netweaver ArchitectureProducts in NetweaverIntegration with J2EEIntegration with ABAP

Unit Test No.1, Questionnaire No.2

4 Introduction to ESA Enterprise Services Architecture OverviewHow ESA in related to Netweaver

Unit Test No.2, Questionnaire No.3

5 SAP R/3 Over view What is ERP?Why we need ERP?Advantages of ERPWhat is SAP?History & Features of SAPSAP R/3 Architecture (Types of work processes)SAP R/3 Application ModulesSAP Landscape

Unit Test No.3, Questionnaire No.4

6 Introduction to ABAP What is ABAP/4?Logon to SAP R/3Transaction CodesMultitasking CommandsABAP/4 Editor ( SE38 )Steps for Creating a ProgramElements in R/3 Screen

Unit Test No.4, Questionnaire No.5

7 ABAP/4 Data Dictionary ABAP/4 Dictionary IntroductionData Dictionary FunctionsData Dictionary ObjectsDomainsData ElementsData Base TablesStructures

Unit Test No.4, Questionnaire No.7

8 ABAP Data Dictionary ViewsType GroupsSearch helpsLock objectsPrimary Key And Foreign Key relationsTable Maintenance Generator

Unit Test No.4, Questionnaire No.8

9 Packages, variants and message classes

Difference between local objects & packagesTransferring local objects to PackagesVariants IntroductionCreating variants in ABAP Editor & Data DictionaryMessage Class IntroductionMessage typesCalling message class in ReportDialog programs

Unit Test No.5, Questionnaire No.9

10 Selection Screens & Open SQL Statements

Selection screensParameter StatementSelect-options StatementSelection-screen Statement

Page 5: ABAP

Unit Test No.5, Questionnaire No.10

11 Selection Screens & Open SQL Statements

Screen table and its fieldsDynamic screen modificationsSelectInsertModifyUpdateDelete operations

Unit Test No.5, Questionnaire No.11

12 Internal tables Internal Tables IntroductionDeclaring Internal TablePopulating Internal TableProcessing Internal TableInitializing Internal TablesInner Joins And For All EntriesControl Break Statements

Unit Test No.5, Questionnaire No.12

13 DebuggingTechniques

Debugging Techniques IntroductionBreak - points (Static & dynamic)Watch pointsDynamically changing internal tables contents in Debugging Editorprogram in Debugging Editor

Unit Test No.6, Questionnaire No.13

14 Modularization Techniques Modularization Techniques IntroductionIncludesSubroutinesPassing Parameters to Subroutines Passing Tables to SubroutinesFunction GroupsFunction Modules

Unit Test No.7, Questionnaire No.14

15 Reports Reports IntroductionTypes of ReportsClassical ReportsEvents in classical reports

Unit Test No.7, Questionnaire No.15

16 Reports Interactive ReportsEvents in interactive reportsTechniques For Interactive ReportsHotspotHideGet Cursor

Unit Test No.7, Questionnaire No.16

17 Dialog / Module Pool Programming/ Transactions

MPP IntroductionFlow Logic EventsProcess Before Output (PBO)Process After Input (PAI)Process On Value Request POV)Process On Help Request (POH)Include Programs in MPPDynamic Screens

Unit Test No.7, Questionnaire No.17

18 Dialog / Module Pool Programming/ Transactions

Call ScreenSet ScreenProcessing of List from Transaction and Vice VersaElements in Screen Layout

Page 6: ABAP

Table ControlsStep LoopsTab strip ControlsSub-screens

Unit Test No.7, Questionnaire No.18

19 Batch Data Communication BDC IntroductionMethods in BDCFlat file creationUploading dataBDC MethodsSession MethodCall Transaction Method

20 Batch Data Communication RecordingHandling Table Controls in BDC

21 Batch Data Communication Legacy System Migration WorkbenchFile HandlingApplication ServerPresentation Server

Unit Test No.8, Questionnaire No.19

22 SAP Scripts SAP Scripts IntroductionComponents of SAP ScriptsLayout SetStandard TextOut Put Program

23 SAP Scripts Modifying Standard SAP Script LayoutsSAP Script Utilities – Upload / Download

Unit Test No.8, Questionnaire No.20

24 Smart Forms Smart Forms IntroductionGraphics ManagementStyle MaintenanceParagraph FormatsCharacter FormatsWriting print program and designing layouts

Unit Test No.9, Questionnaire No.21

25 Object Oriented ABAP & ALV Reports

OOABAP ConceptsALV Reports IntroductionTypes of ALV’sALV’s based on Function modules and OOPsSimple ALV’s

Unit Test No.10, Questionnaire No.22

26 ALV Reports Hierarchical ALV reports based on Function modules and OOP’sBlocked ALV’s

Unit Test No.10, Questionnaire No.22

27 ABAP query’s Quick Viewer SAP ABAP Queryuser groupinfo setquery reportsList creation

Unit Test No.11, Questionnaire No.23

28 Performance Tuning & Cross Applications

Types of Program AnalysisStatic , Dynamic ChecksShort Dump AnalysisPerformance ToolsRuntime Analysis and SQL TraceIntroduction to Cross ApplicationsIntroduction to Distributed Environment

Page 7: ABAP

Unit Test No.12, Questionnaire No.24

29 RFC & ALE Introduction to RFCDefine logical systemsCreating RFC Destination between 2 SystemsCreating program using Remote Enabled FunctionALE BasicsOverview of Outbound & Inbound ProcessConfiguration StepsAssign client to logical systemModel viewCreating Ports

30 IDOC’s (Intermediate Document) What is an IdocsTypes of IdocsBasic IdocsExtension IdocsCreating IdocsMessage TypesAssigning Idoc type to Message type

Unit Test No.14, Questionnaire No.26 & 27

31 Enhancements Enhancement ConceptsTypes of ExitsImplementing various type of user exits for enhancementField ExitScreen ExitFunction ExitMenu Exit

32 BAPI’s (Business Application Programming)

BAPI OverviewCreation of BAPI

Unit Test No.15, Questionnaire No.28

33 EDI (Electronic data Interchange) Difference between ALE & EDIOverview of Outbound & Inbound ProcessConfiguration StepsPort CreationPartner Profile Creation

Unit Test No.16, Questionnaire No.29

34 BADI’s (Business Addin’s) & Work flow

BADI’s OverviewDefining a BADIImplementing a ClassWhat is workflow?Overview of workflowSingle task workflowMultiple task workflow

Unit Test No.15, Questionnaire No.25

35 ASAP Methodology & Case Study ASAP Overview and SAP Full Life Cycle Implementation PhasesReview of the Total courseCase Study Based on Real time Project

ABAP DATA DICTIONARY

Overview

Page 8: ABAP

Data definitions also called as meta data are managed and created in ABAP Dictionary. It allows to maintain a

huge volume of data without data redundancy. The ABAP Dictionary describes the logical structure of all the

dictionary objects used in Application development. It also provides you with the flexibility of accessing the

data on the screen and allows you to maintain manage and create without any programmers intervention.

The data dictionaries can be categorized into the following.

Database table

Views

Data types

Domain

Search Help

Lock Objects

Database tables:

Tables can be defined independently in the database in the ABAP Dictionary. The fields of the table are

defined together with their data types and lengths.

A table definition has following components:

Table fields

Foreign keys

Technical settings

Indexes

Views

A View is a logical representation of tables. This is just a way of organizing the data by combining more than

one table by comparing the common fields which is called a join.

The data dictionaries can be categorized into the following.

Database table

Views

Data types

Domain

Search Help

Lock Objects

Database tables:

Tables can be defined independently in the database in the ABAP Dictionary. The fields of the table are

defined together with their data types and lengths.

A table definition has following components:

Table fields

Foreign keys

Technical settings

Indexes

Page 9: ABAP

Views

A View is a logical representation of tables. This is just a way of organizing the data by combining more than

one table by comparing the common fields which is called a join.

Data types:

It’s an attribute to tell as to what kind of data is it going to hold like numbers, characters, integers etc. A data

type can be an elementary data type or a reference data type.

Domain:

A domain contains the technical attributes of the data type. Like the length, the actual data type ( like char,

integer), The output characteristics and the value range which tells us as to what kind of data can be

accepted as a valid input.

Search Help:

A search help is simply what you see in SAP when you key in the F4 button. It provides you with the

list/range of values.

A search help can be categorised into three types:

Elementary Search help

Collective Search Help

Append Search Help

Lock Object:

A lock object is virtual link of an sap table which is used to synchronize the data when more than one user

attempts to write to the Database table. These lock objects are called and handled inside the program based

on requirement.

By Rahul Dada (18 th July 2012)

ERP Fundamental

Page 10: ABAP

ERP: (Enterprise Recourse planning): Planning of recourses in an enterprise is called ERP. This is concept and its nowhere exist.

Q: - What is ERP?

ERP is a package with the techniques and concepts for the integrated management of business as a

whole, for effective use of management resources, to improve the efficiency of an enterprise. Initially,

ERP was targeted for manufacturing industry mainly for planning and managing core business like

production and financial market. As the growth and merits of ERP package ERP software is designed

for basic process of a company from manufacturing to small shops with a target of integrating

information across the company.

E-Enterprise: This is group of people with a common goal which has certain recourses of its disposal to activate the goal.

R- Recourse- It includes money, manpower material and all others things which required to run the enterprise.

P- Planning: This is done to ensure that nothing goes wrong in an enterpriseQ: - What are the types of ERP ? 

1.Horizantal ERP (Horizantal ERP will fit for any sort of organization there is no industrial specific

ex:SAP,ORACLE Apps)

2.Vertical ERP (Vertical ERP is Industrial specefic this will not fot for all types of industries

ex:DTR(Plastic industy),Axis(Steel industry))

Q: - What is SAP ?

SAP is software that built up in the year 1972 by Five German Engg., as they were working in IBM, SAP

(System, Application, And Product In Data Processing) is Worlds largest ERP (Enterprises Resource

Planning) software.

Initially it was known as GERMAN SAPAG.

This is real time s/w.

SAP

Page 11: ABAP

Functional Technical HR ABAP BASIS MM

FI SD

PP….. so on

Introduction to SAP R/3

SAP is basically server based process which has 3 tear architecture. This is also called by R/3 Architecture where R stand for real time and three represents third generation.

R/3 Architecture: As this is server based hence it has three server namely1) Presentation Server.2) Application server.3) Database Server.

Architecture:

RFC

RFC

Buffer

WPWPWPWPWPWPWPWP

Dispatcher FIFO

Database Server

Application Server

Presentation Server

Page 12: ABAP

Presentation Server: The upper most layer of the image is presentation server which is used to give the input and produced the output. User directly interact with the presentation server hence it’s also called user interface server.

Application Server: Presentation server user send request to the Application server which is basically used the processing the request. Application server is having three components namely.

a) Dispatcherb) Work Processc) Buffer.

When Application server receives the request, it directly goes to dispatcher. Dispatcher used to categorize work request in several work process on the FIFO (First in first out) Basis. Then work request goes to buffer and buffer directs the work process to the Database server. Once database return the request it goes to buffer and buffer forward to work process and work process directly send to Presentation server and reflect the output.Note: when database is returning the record or result of request then it’s not going in dispatcher again.

Database Server: This server is mainly used to maintain the data.

This whole processing is happening in 300 seconds (5Min). Each server connected with RFC protocol. The entire processing is known as LUW (logical unit of work).

Application Server is in Detail: As earlier we discussed the components of the Application server.Three components are :

a) Dispatcher b) Work Processc) Buffer

A) Dispatcher: The main work of dispatcher to receive work from presentation server and maintaining the queue on FIFO basis.

B) Work Process: At least 7 Work process can runs in Application server at a time. 5 work Process are run as below:1) D: Dialogue- This used in screen handling and having at least 2 Work process.2) B: Background- All background processing handle by this Work process. This Also contain 2

work process.3) S: Spool: All printing related request handled by this work request. this is containing at least

1 process4) U: Update: If any update request comes then its handled by this work process. This is

containing at least 1 process.5) E: Enqueue : This is used to lock the object so at a time one user can access and change the

data. This is containing only 1 process.C) Buffer: buffer is basically temporary memory which used to store records of the data and

respond the user if receive any duplicate request before going Database.There are two mechanism used to buffer the data Data flow process:1) Synchronous: This is basically forward the data and wait until unless didn’t get the

acknowledgment from the receiving end. Once acknowledgment is received its deliver another data and wait.

2) Asynchronous. This is regularly sending the data without getting acknowledgment.

Page 13: ABAP

ABAP/4: This is stand for advance business application programming.Features: this is very fast in comparison of other s/w’s.User Friendly.Object OrientedDownward and upward compatibility.

(20th July 2012)How to work on SAP-ABAP/4 work environment:

Client: At the time of implementation of the SAP, there are three type of client on which any ABAPER works.1) Development Server2) Quality Server3) Production Sever.

Testing Phase

Change Request No (Transport Request Number)SE09/SE10: used to move TR for Dev to QASThere are three steps:

ABAPER’S Roles & Responsibility:

Information gathering TR moved to QAS to PROS By BASIS

FSD(Functional Specification Documents)TR moved to QAS by BASIS

TSD(technical Specification Documents)

Release TR in dev.Import TR in QAS (which is done by BASIS) (STMS IMPORT)Import TR in QAS 9STMS- IMPORT)

Few Important Transaction code;

Development Server

Production ServerQuality Server

Development Server

Quality Server

Production Server

ABAP

Functional

End User

Page 14: ABAP

SE11- Data Dictionary.SE13 : ABAP Dictionary : Technical SettingsSE14 : Database UtilitySE15 : Repository Information SystemSE16 : Data BrowserSE17 : General table DisplaySE21- Package.SM30 : Table MaintenanceSE38- ABAP Editor.SE80-Object Navigator.SE84- Object NavigatorSE91- Massage classSE55 : Table View Maintenance

24th July 2012

Data Dictionary:(T-code: SE11)

A data dictionary is a central source of information for the data in a information management system.

Its main function is to support the creation and management of data definitions (or “metadata”).

What is Data dictionary used for ?

Management of data definitions

Provision of information for evaluations

Support for software development

Support for documentation

Ensuring that data definitions are flexible and up-to-date

Objects in the ABAP Dictionary resided on three levels that support their re-usability. These levels are:

Page 15: ABAP

1. Tables and structures

2. Data elements

3. Domains

Lets look into them in detail -

Domains Describes the technical characteristics of a table field

Specifies a value range which describes allowed data values for the fields

Fields referring to the same domain (via the data elements assigned to them) are changed when a

change is made to the domain

Ensures consistency

Ex. Purchasing document number (EBELN)

Data Elements Describes the role played by a field in a technical context

Fields of same semantic meaning can refer to the same data element

Contains the field information

Ex. Purchasing document number (EBELN)

Page 16: ABAP

Tables Represent the Database Tables where data actually resides.

Tables can be defined independently of the database in the ABAP Dictionary.

The fields of the table are defined with their (database-independent) SAP ABAP data types and

lengths.

Structures Are record declarations that do NOT correspond to a Database Table.

Just like user-defined data type.

Defined like a table and can then be addressed from ABAP programs.

Structures contain data only during the runtime of a program.

Page 17: ABAP

Aggregated Objects of ABAP DictionaryAggregated means consisting of several components. In the ABAP Dictionary, aggregated objects are

objects which come from several different transparent tables.

1. Views

2. Search Help

3. Lock Objects

Lets look into them in detail

Views Views in SAP _ ABAP are used to summarize data which is distributed among several tables

The data of a view is not actually physically stored. The data of a view is instead derived from one

or more other tables

It is tailored to the needs of a specific application

Page 18: ABAP

Search Help A Search help is a tool to help you search for data records in the system

An efficient and user-friendly search assists users where the key of a record is unknown

Lock Objects Simultaneous accessing of the same data record by two users in the SAP system is synchronized by

a lock mechanism.

Locks are set and released by calling certain function modules. These function modules are

generated automatically from the definition of so-called lock objects in the ABAP/4 Dictionary

Function modules :

Enqueue_<obj name> – to lock the table

dequeue_<obj name> – to release the lock

Note: 1) T-code for data dictionary is SE11.

Page 19: ABAP

3) IF want to open new session then we use /o and then write t-code. For example if want to open data dictionary with new session the we can write /ose11.

4) If we want to open new session in the same screen then we can write /n+ t-code.

What is Table and what is its type. Table is a general terminology it can be transparent table cluster table or other, So table is nothing but place where we will store data.There are four type of tables exist in data dictionary.

i)Transparent tables - Exists with the same structure both in dictionary as well as in database exactly with the same data and fields. Both Open sql and Native sql can be used..

ii) Pool tables: A table in the database in which all records from the pooled tables assigned to the table pool are stored corresponds to a table pool.The definition of a pool consists essentially of two key fields (Tabname and Varkey) and a long argument field (Vardata). A pool has the following structure:

Field Data type Meaning

Tabname CHAR(10) Name of pooled table

Varkey CHAR (n) Contains the entries from all key fields of the pooled table record as a string, max. length for n is 110

Dataln INT2(5) Length of the string in Vardata

Vardata RAW (n) Contains the entries from all data fields of the pooled table record as a string, max. length n depends on the database system used

If a pooled table record is saved, it is stored in the table pool assigned. The name of the pooled table is written to the field Tabname. The contents of all key fields of the pooled table are written as a string to fieldVarkey and the contents of all data fields as a string to field Vardata. The length of the string stored in Vardata is entered in field Dataln by the database interface.

Page 20: ABAP

Due to the structure of a table pool, there are certain restrictions on the pooled tables assigned to it. The name of a pooled table may not exceed 10 characters. Since Varkey is a character field, all key fields of a pooled table must have character data types (for example, CHAR, NUMC, CLNT). The total length of all key fields or all data fields of a pooled table must not exceed the length of the Varkey or Vardata field of the assigned pool.

iii) Cluster tables:

Several logical data records from different cluster tables can be stored together in one physical record in a table cluster.

A cluster key consists of a series of freely definable key fields and a field (Pageno) for distinguishing continuation records. A cluster also contains a long field (Vardata) that contains the contents of the data fields of the cluster tables for this key. If the data does not fit into the long field, continuation records are created. Control information on the structure of the data string is still written at the beginning of the Vardata field. A table cluster has the following structure:

Field Data type Meaning

CLKEY1 * First key field

CLKEY2 * Second key field

... ... ...

CLKEYn * nth key field

Pageno INT2(5) Number of the continuation record

Page 21: ABAP

Timestamp CHAR(14) Time stamps

Pagelg INT2(5) Length of the string in Vardata

Vardata RAW (n) Contains the entries from the data fields of the assigned cluster tables as a string, max. length n depends on the database system used

The records of all cluster tables with the same key are stored under one key in the assigned table cluster. The values of the key fields are stored in the corresponding key fields of the table cluster. The values of all data fields of the assigned cluster tables are written as a string to the Vardata field of the table cluster. Besides the actual data values, the data string contains information on the structure of the data and which table it comes from. If the string exceeds the maximum length of the Vardata field, a continuation record is written with the same key values. The continuation records for a key are distinguished by their value in field Pageno. The actual length of the string in the Vardata field is stored in the Pagelg field by the database interface.

You need the structural information stored in the ABAP Dictionary to read the data from a pooled table or cluster table correctly. These tables can therefore only be processed using Open SQL with the cluster interface, and not with Native SQL directly in the database.

iv) Internal Table: An Internal table is a temporary table gets created in the memory of application server during program execution and gets destroyed once the program ends. It is used to hold data temporarily or manipulate the data. It contains one or more rows with same structure.An internal table can be defined using the keyword TABLE OF in the DATA statement. Internal table can be defined by the following ways.

TYPES: BEGIN OF ty_student,

Page 22: ABAP

id(5) TYPE n, name(10) TYPE c, END OF ty_student.

DATA: gwa_student TYPE ty_student.

"Referring to local data typeDATA: it1 TYPE TABLE OF ty_student."Referring to local data objectDATA: it2 LIKE TABLE OF gwa_student."Referring to data type in ABAP dictionaryDATA: it3 TYPE TABLE OF mara.

Use the APPEND statement to add data to internal table. First define the work area i.e. define a field string with a structure similar to row of the internal table. Then place the data in the work area and use the APPEND statement to add the data from work area to internal table.

*--------------------------------------------------------------**Data Types*--------------------------------------------------------------*TYPES: BEGIN OF ty_student, id(5) TYPE n, name(10) TYPE c, END OF ty_student.

DATA: gwa_student TYPE ty_student.

*--------------------------------------------------------------**Data Declaration*--------------------------------------------------------------*"Referring to local data typeDATA: it TYPE TABLE OF ty_student.

gwa_student-id = 1.gwa_student-name = 'JOHN'.APPEND gwa_student TO it.

gwa_student-id = 2.gwa_student-name = 'JIM'.APPEND gwa_student TO it.

gwa_student-id = 3.gwa_student-name = 'JACK'.APPEND gwa_student TO it.After the last APPEND statement in the above program, internal table ‘IT’ has the following 3 entries. But the internal table values are not persistent i.e. the internal table and its values are discarded once the program ends.

ID NAME

1 JOHN

Page 23: ABAP

2 JIM

3 JACK

Usually internal tables are used to hold data from database tables temporarily for displaying on the screen or further processing. To fill the internal table with database values, use SELECT statement to read the records from the database one by one, place it in the work area and then APPEND the values in the work area to internal table.DATA: gwa_employee TYPE zemployee, gt_employee TYPE TABLE OF zemployee.

SELECT * FROM zemployee INTO gwa_employee. APPEND gwa_employee TO gt_employee.ENDSELECT.After ENDSELECT the internal table GT_EMPLOYEE contains all the records that are present in table ZEMPLOYEE.Using INTO TABLE addition to SELECT statement we can also read multiple records directly into the internal table directly. No work area used in this case. This select statement will not work in loop, so no ENDSELECT is required.SELECT * FROM zemployee INTO TABLE gt_employee.

Table Creation: There are three approaches to create a table.1) Top Down.2) Bottom Up.3) Predefined of type.

Top Down: In top down approach we first create table then data element and then domain as below

a) Tableb) Data elementc) Domain.

Bottom Up: In bottom up approach we first create domain, then data element and then Table as below

a) Tableb) Data elementc) Domain.

25 th July 2012 How to create Domain, Data element.

Page 24: ABAP

Note: Whenever we create table or write program, then we have to defined the table name of program name with ‘Z’ or ‘Y’.

1) Create Domain: In Domain we have to consider only three things.a) Descriptionb) Character type.c) Length

After entering these three fields we have to save the records and activate the domain.

2) Data Element: It also has three things.d) Descriptione) Domain namef) Field Lable

After entering these three fields we have to save the records and activate the Data element.

3) Predefined: Predefined is already integrated in library. We have to just click on “Built in type”.

Note: There are two ways to update the table.1. We can go to utilities and call maintenance generator. Or2. We can directly open maintenance view by entering T-code SM30.3. SE14: is used to Adjust the table.

Steps To create Transparent table:

Steps: first of all we enter the T-Code SE11 and press enter. Following window will appear.

Enter the database table name with initial of ‘Z’ and press create button.

Create

Enter the Database Table name with initials of “Z”

Page 25: ABAP

Database Table: Tables can be defined independently in the database in the ABAP Dictionary. The fields of the table are defined together with their data types and lengths.

Give the short description which can be anything about the table and then press on Delivery Class.

Click on delivery Class

Short Descriptions: any thing about Table

Page 26: ABAP

Double click on A as a Application table.Question: What is Delivery Class?Ans: A delivery class helps manage the transport of table data when installing or upgrading in a client copy and when transporting between customer systems. It is also used in extended table maintenance.

Whether SAP provides the table with or without contents.

· Determines the table type.

· Determines how the table behaves when it is first installed, at upgrade, when it is transported, and when a client copy is performed.

There are the following development classes: A,S,C,L

* A: Application table (master and transaction data).* C: Customer table, data is only maintained by the customer.* L: Table for storing temporary data.* G: Customer table, SAP may insert new data records but may not overwrite or delete existing ones. The customer namespace must be defined in table TRESC. To define the customer namespace use report RDDKOR54. You can start it directly from the table maintenance by choosing Customer namespace definition on the Attributes tab.* E: System table with its own namespace for customer entries. The customer namespace must be defined in table TRESC. To define the customer namespace use report RDDKOR54. You can start it directly from the table maintenance by choosing Customer namespace definition on the Attributes tab.* S: System table, data changes have the status of program changes.

Select A as application Table for transparent

table

Page 27: ABAP

* W: System table (e.g. table of the development environment) whose data is transported with its own transport objects (e.g. R3TR PROG, R3TR TABL, etc.)

As above we have to enter Data browser/Table view maintenance as Display /Maintenance allwed and then need to click on Fields.

Click on fields

It will always Display/Maintenance

Allowed

Page 28: ABAP

Field: It holds Domain Name.Primary Key: Unique no which can not duplicateInitial Value: Data Element: Data element is a semantic domain ,it described role played by domain in technical context A Field in R/3 system is a data element. It always starts with ‘Z’ or ‘Y’.

Data Type: It’s an attribute to tell as to what kind of data is it going to hold like numbers, characters, integers etc. A data type can be an elementary data type or a reference data type.Length: It describe the length of the field.Decimal Places: if decimal place required it will reflect here.Short Descriptions: This is short description about the data element or domain.

Now enter the field name as MANDT.MANDT: MANDT is the client dependent table name which is predefined table.

Domain Description

Deci. Places

LengthData Type

Data ElementPrimary Key

Fields:Enter Domain

name

Short Description which can be anything about the Table

Page 29: ABAP

Enter another field name like below

Client Dependent Table

Defined the field zstud_roll as data element.

Page 30: ABAP

Now double click on data element. It will asked to create data element. Click yes or press enter like below.

Now enter the short description of the data element and domain name which can be same as data element name but we can write different name as below..

Yes

Page 31: ABAP

Best practice to keep domain name as it is data element. Now save (CTR+S) and double click on domain name. it will asked for the package name as below

Save Button or press enter

Package Name

Short Description like Student Roll no

Domain Name which can be same as data element

Page 32: ABAP

Enter the package name and press save button. It will again asked for the transport no.

Transport No: This is no which is used to move work to production server to quality server or vice versa. It will reflect last created TR No By default but we can change the TR no with pressing key create new request which we will learn ahead.

After pressing save button it will asked for the create data domain which is not available In the data dictionary. Press yes or press enter key.

Save

TR No

Page 33: ABAP

Once press yes it will reflect like below .

Yes

Output Length

No Of character

Data Type like NUMC

Short Description of the data domain

Page 34: ABAP

In Data domain we need to fill four fields.Short Description: It can be anything about the domain.Data Type: It is going to hold the data hence defined the type of data like number, character or string.No Character: this is basically reflect the no of character at the time of output.Output Length: Again this is same as no of character.

Now we have to save the data domain as below. During saving the data domain it will again asked for the package name and TR no. we have to press enter or just need to save the both. Now Activate the Data domain by pressing CTR+F3 key or by clicking activate button as below.

This will again prompt below window.

Activate or CTR+ F3

Page 35: ABAP

Now table will in active mode like below.

Press this to continue or press enter button

.

Table which is need to activate

Active

Page 36: ABAP

Now Press F3 button to go back and click on field label.

Field Label: This is describe the Length and header of the table.

Field Label

Back button or Press F3

Length

Field Label

Page 37: ABAP

Copy the short Description and paste in the field label name and press enter button. Field length will automatically reflect . now save and activate by CTR + F3 button and press F3 to go back.Now one field is added like below.

Now repeat the same process and add more field like name address and contact no. Once all field added, now save the table and then go to technical setting.

Field Added

Page 38: ABAP

What is technical setting?

The technical setting specifies how the table should handle by the SAP system. The main technical

settings of a table are

1. Data Class

2. Size category

3. Buffering Permissions

4. Buffering Type

5. Logging

Technical Setting

Page 39: ABAP

Click on data class icon to access the dataclass.

Data Class

Select the data class as per the requirement.

Page 40: ABAP

Data class: Data class specifies the physical area in RDBMS called tablepsace. The table will be created in that area. The following are the main data class options used.

APPL0: Master data which is rarely changesAPPL1: Transaction data which is frequently changedAPPL2: Organization data which is holding the customizing data and very rarely changes.Apart from these USR and USR1 are other special data classes for user developments.

Now click on Size category.

Size category: Size category specifies the expected space required for the table. And the options available in size category are

0-- 0 to 14000. 1 : 14,000 to 57,000 2 : 57,000 to 220,000 3 : 220,000 to 910,000. 4 : 910,000 to 3600, 00 5 :3600,000 to 7300,000 6 : 7300,00 to 290,000,000.

Each of this option will assign a certain fixed memory for that table.

Size Category.

Page 41: ABAP

We will double click on 0 and then click on buffering not allowed radio button like below.

We will select 0

Buffering not allowed

Page 42: ABAP

Buffering Permissions: There are 3 types of buffering permissions are there1. Buffering not permitted2. Buffering permitted but not activated3. Buffering activated ( in this option we need to specify the buffering type)

Buffering Type: Following are the three buffering types used for tables1. Full buffering: All the records of accessed table will be buffered.2. Generic buffering: All other records which having the same generic fields of the accessed

records will be buffered.3. Single record buffering: Only the accessed record will buffer in this case.

We can determine the buffering type based on the table size and the operations need to handle in our applications.

Logging: This option specifies about the storage of log about the changes in table. The changes will be logged in a table DBTABPRT. There are 3 types of logging options for a table.

1. rec/client = ALL (Enable log for all clients)2. rec/client = 000[,...] ( Enable log for only specified clients)3. rec/client = OFF ( Turn off the logging)

Now save the technical setting by pressing CTR + F3 button and press F3 to get back on database table.Now Activate the table by pressing CTR+F3 button.

Now table activated and need to enter data in the table. For that go to utilities-table content and Create entry.

Enter Continue

Select the table which we want to

activate

Page 43: ABAP

Save the first record by ctr + S and reset the fieldby clicking ctr _F2 button.Once done with the entry now need to see the data which enterd

Click on Create entry

Page 44: ABAP

For that first goto utilities table content and display or press CTR+SHIFT+F10.

Now it will reflect like

Display the record

We can sent the criteria and then press the execute button or press the F8 button to see

the table with data.

Page 45: ABAP

We can sent the criteria and then press the execute button or press the F8 button to see the table with data.

Now done with the database table.

Data view: if two tables are there and we want to merge both table then view will come existence.

View:

1) Database view2) Maintenance view.3) Projection view.4) Search view.

Database view:

Two table need to add: data base view is process used to display the data from different different table and join the data in 1.For example there is a table called zemp1. Which has two field namely id and name like belowZemp1.

ID Name

101 Anish

One entry.

Page 46: ABAP

102 Ashish

Another table called zemp2 which is having two field id and contact no. make sure for database view there should be primary key same in both table.Zemp2

ID Contact no

101 9021233364

102 9373882634

Now we want to display the data in one table which hold the all those three field namely id, name and contact no. Like…

ID Name Contact No 101 Anish `9021233364 102 Ashish 9373882634

Process to create database view First of all create foreign key for that please follow the below step.Make foreign key Relationship:

1) Copy the primary key of the first table in to the second table.

Click on primary button. Following window will open.

Click on foreign Key

Page 47: ABAP

2) In check table field--- Here write table name for which primary key same for all table.3) Click generate proposal. - After clicking generate proposal First Table primary key will reflect in

work area.4) Click copy.5) Save and activate..

Make Database View:

1) Se11

Copy

Primary Key will Reflect Here

3) Generate Proposal

2)Primary table Name

1)Description- Any think

Page 48: ABAP

2) View: give data view name with z and press create button.

3) Select data base view option and click on copy.

Create

View Name

Database View

Copy

Page 49: ABAP

4) Description(any thing)5) In tables name (first table name)6) Click on relationship

7) Select check box and then click on copy.

3-Relationship

2-First Table Name

1-Description

Copy

Select the check for that table with which database view is required

Page 50: ABAP

8) Click on view field

9) Click on table field

View Field

Table Fields

Page 51: ABAP

10) Double click on first table.

11) Select all field of first table and copy.

Double Click on first table

Copy

Select all fields including primary key

Page 52: ABAP

12) Again click on table field.13) Now double click on second field

14) Copy save and activate 15) With warning massage and click no.

Double Click

Copy

Select field accept primary key

Page 53: ABAP

16) Execute the table.

Maintenance view: Maintenance view used to maintain the global table.

Step: First enter T-code se11.

Press enter. Now below screen will open

T-Code SE11

Page 54: ABAP

Click on view and write the view name followed by Z. and click on create button.

Following screen will appear.

Click on View

Create or F6

Page 55: ABAP

Select maintenance view and click on copy now below screen will appear

Now enter the following details as per the given graphical representation.

2)Enter Table name for example MARA

3) Click on View fields

1-Enter the description (anything)

Maintenance View

Copy

Page 56: ABAP

1) Short Description- This is the field where we can right anything as description.2) Tables: Enter the table name for which we are going to create maintenance view.3) View Field: now click on view field which will reflect like below…

Now click on table fields as above.

Table Fields

Page 57: ABAP

After clicking above screen will appear and here we can select the field which we want to change, with the help of check box. Then press copy button as above.

Select the field which you want to change

Press on copy after selecting the field.

Activate

Page 58: ABAP

Now all selected field will come in the maintenance table. Now we have to save the table and activate the table with the help of CTR+F2 Button or as clicking above activate button.During activation of the table it will ask the package name. write package name which already designed as below…..

Click on save button as above. It will prompt for transport request no like below..

Package Name for ex-ZABAP

Save

Page 59: ABAP

We can directly continue with the selected transport no but we can create new transport request no as aboveClick on create request now below screen will appear.

Transport Request no

Click on create request

Page 60: ABAP

Give the Short Description and save the transport request no as above. After pressing enter it will return the actual TR window and the press enter for continue.After pressing enter for continue again activation window will prompt now again press enter to activate the table. Like below..

Short Discription

Save

Page 61: ABAP

Note: During activation of the table we will get the warning massage like below.

Select the table which you want to activate. By default table will highlighted with who you are working

Click here or press enter.

Press NO

Page 62: ABAP

We have to ignore this massage and now our table will activated.

Now we have go to the utilities – Table Maintenance generator as below..

Below screen will appear..

Utilities -> Table Maintenance Generator

Page 63: ABAP

We have to Select authorization group by click on given icon as below….

Select &NC& (w/o auth group) option.

Authorization Group

Select &CN&

Page 64: ABAP

Now select the function group as below… (Function group will start with Z).

After selecting function group press enter and package name will automatically reflect.Now Press maintenance type as one step radio button, and click find screen Numbers button as below.

Function Group which will start with Z

Package Name

Page 65: ABAP

After clicking find screen numbers button below screen will appears..

2-Click on Find scr. Numbers

1-Maintenance Type- One Step

Save

Select- Display free no ranges

Page 66: ABAP

Now below screen will reflect. Double click on screen 4

Now screen no will reflect in maintenance screen no field.Now click on create button or press F6 . As below

Vaccant Screen no

Page 67: ABAP

After clicking create button it will again prompt for package no. press Enter to continue and again it will ask for transport number the again press enter to continue.

Congratulation now Maintenance view has been created.

Now open the new session and write T-Code SM30 for maintain the table…

Screen No

Create

Page 68: ABAP

As above table maintenance view name automatically reflect, we have to select Maintain button to do amendment in the table.In this screen…

1) Table view name2) No Restriction will already clicked.3) Maintain

Now maintenance view will reflect like below

Maintain

Page 69: ABAP

Do amendment whatever we want and save the table.

Creating Package:

For creating package enter the T-code SE21.Below screen will come

Page 70: ABAP

Enter the package name with initial of ‘Z’ like ZABAP3.Then press F6 or create button.

Package name with “Z”

Create

Software Component-

Short Description

Package Name

Save

Page 71: ABAP

As above we have to fill up below details.

1) Package Name: It should be start with “Z”.2) Short Description: Any description about the package.3) Software Component: It will always Home.4) Save: Finally save and press enter.

Once it will save then it will prompt for transport request no. press enter.

Now package is ready for use. Press F3 to go back

Kind of Projects in SAP: There various types of projects available but as a ABAPER, we have to interact with following,

1) Implementation: This is fresh SAP installed in any organization.2) Rollout: This is something execution of existing SAP.3) Upgrade: This used to upgrade the version.4) AMS: This is called Application, maintenance & support.

Page 72: ABAP

26 th July 2012

Reports: Reports are nothing but its programming to fetch he data from the database and reflect in proper manner. Mainly three types are report used in SAP.There are three types of reports.

1. Classical Reports2. Interactive Reports3. Drill down Reports

CLASSICAL REPORT:- A report which can generate only one list, that is Basic List, is called classical report. First List of a report is called BASIC LIST.

INTERACTIVE REPORT:- A report which can generate one basic list and upto 20 interactive lists is called an interactive report. First list is called Basic List and Interactive lists are called Secondary Lists.

DRILL DOWN REPORTS:- In these reports the output will be in tree format.

EVENTS IN CLASSICAL REPORTS

1. INITIALIZATION2. AT SELECTION-SCREEN

(a) AT SELECTION-SCREEN ON <FIELD>(b) AT SELECTION-SCREEN OUTPUT(c) AT SELECTION-SCREEN ON VALUE-REQUEST FOR <FIELD>

3. START-OF-SELECTION4. TOP-OF-PAGE5. END-OF-PAGE6. END-OF-SELECTION

Now we will discuss what are the uses of these events.

INITIALIZATION:- This is the first event to be triggered. This event is triggered before the selection-screen is displayed. This event is used to give default vales to selection-screen fields.

AT SELECTION-SCREEN:- This event is triggered after giving input in selection-screen fields. This event is used to handle the user actions on the screen. This is also used to validate all the selection-screen fields.

AT SELECTION-SCREEN ON <FIELD>:- This event is used to validate a particular field present on the selection-screen.

AT SELECTION-SCREEN OUTPUT:- This event is used to change the selection-screen properties dynamically.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR <FIELD>:- This event is used to give F4 help to a particular field resent on the selection-screen.

Page 73: ABAP

START-OF-SELECTION:- The main logic of the program is written in this event. Usually write statement is recognized from this event.

TOP-OF-PAGE:- This event is used to write something on top of every page. The first write statement or output statement (SKIP) of a page triggers this event.

END-OF-PAGE: - This event is used to write something at end of every page. Last line of the page triggers this event. We have to allocate the line for end of page.

END-OF-SELECTION:- Usually program output is written in this event. This event is used to handle abnormal termination of the program. The stop statement written in start-of-selection event takes the control to end-of-selection event.

No event is mandatory. But default event is start-of-selectionBecause ABAP is an event driven language there is no need to maintain the order of the events.

System will take care of the order of the events.The write statement written in initialization event can not be seen if the program is having

selection-screen, because initialization event is triggered before the selection-screen is displayed. If the program is not having the selection-screen we can see the write statement written in Initialization event.

Starting of new event symbolizes ending of previous event.The STOP statement in start-of-selection takes the control to end-of-selection statement.Skip statement also triggers top-of-page event.Declarations should be written before initialization event.

See the following sample program which uses initialization event and write statement.

REPORT ZSAMPLE .parameters p_matnr type mara-matnr.initialization.write : 'HELLO'.

I have written write statement in Initialization event and the program is having selection-screen. The write statement can not be seen. Actually HELLO will be written but that is immediately overwritten by selection-screen. That is the reason why we can not see the write in output. REPORT ZSAMPLE .Initialization.write : 'HELLO'.

If I execute the above program HELLO will be seen because this program is not having selection-screen.

Now see the following program which is having all the above events.

REPORT ZEVENTS no standard page heading line-count 10(1) line-size 500.tables mara.data d_matnr type mara-matnr.data: begin of itab occurs 0,

Page 74: ABAP

matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.data count type i.select-options s_matnr for mara-matnr no-extension no intervals.at selection-screen on s_matnr.

select single matnrfrom marainto d_matnrwhere matnr in s_matnr.if sy-subrc ne 0.message e000(zmsg) with s_matnr-low s_matnr-high.endif.start-of-selection.

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.stop.end-of-selection. loop at itab. write: / itab-matnr, itab-mbrsh, itab-mtart. endloop.count = sy-linct - sy-linno - 1.skip count.top-of-page.write / 'data from mara table'.

end-of-page.write: /45 'page number: ', sy-pagno.

In the above program I have used a statement message e000(zmsg)

which is used to raise the message. The meaning of this statement is that raise an error message from zmsg message class. The message number to be raised is 000.

MESSAGE CLASS:- Its is a collection of messages. Each message class can hold 1000 messages. (000 to 999). T-code for creation of message class is SE91.

There are 5 types of messages in SAP. 1. Error Message (E).2. Warning Message (W).3. Information Message (I).4. Success Message (S).5. Abend Message (A).

A Message created in a message class can be used as any of the above 5 types. What ever the letter I have given in the brackets after each type of message should be used to specify the system about which type message you are going to raise.

Page 75: ABAP

Error Message temporarily halts the program. That means once the errors are corrected the control moves forward. But Abend message completely terminates the program.

Information and Success messages give the message and move forward. They won’t stop the control.

Warning message also temporarily terminates the program. When ever you go for validations better you use Error message.

Now we look into statements that are new in the above program.

NO STANDARD PAGE HEADING:- This is used to suppress the default heading given by system in output. That means first two lines in the output(i.e. Text given in title of the program and the a horizontal line) will be suppressed.

LINE-COUNT 10(1):- Here 10 specifies no of lines per a page. If this is not mentioned system takes 65,000 lines as single page. So when ever you want to specify no of lines per a page you have to mention here. 1 that is written in brackets indicates no of lines allocated for end-of-page. That means the complete meaning is 10 lines per each page and in those 10 lines 1 line is allocated for end-of-page.

LINE-SIZE 500:- Line-size specifies about how many characters should be printed in a line. If it is not mentioned system will print only 255 characters in a page. Maximum line-size allowed is 1023 characters. This is used in a program when you want to display many fields in the output. Because in that case normal output of 255 characters per a line may not be sufficient.

SY-LINCT:- This is a system variable which gives no of lines allocated per a page. In the above program sy-linct value will be 10.

SY-LINNO:- This is also a system variable which gives no of lines printed in a page.

In the program I have used count = sy-linct - sy-linno - 1. skip count.

This logic is used to trigger end-of-page event for last page also. If this logic is not used page number for the last page will not come because end-of-page event is triggered by last line of the page. If there no enough lines that means 9 lines to be printed in the last page end-of-page will not be triggered. The logic used above will help in triggering the end-of-page event even for the last page also. You can try the program without this logic also. Then you will understand better. You also execute the program in debug mode to understand better.

SY-LILLI:- It is a system variable which gives clicked line number in the list.SY-LISEL:- It is a system variable which contains whole contents of clicked line.

Try these system variables in debug mode.

INTERACTIVE REPORTS:- A report which can generate one basic and up to 20 interactive lists is called an interactive report.

First list is called basic list and next lists are called interactive lists.

EVENTS IN INTERACTIVE REPORTS

1. INITIALIZATION

Page 76: ABAP

2. AT SELECTION-SCREENa. AT SELECTION-SCREEN ON <FIELD>b. AT SELECTION-SCREEN OUTPUTc. AT SELECTION-SCREEN ON VALUE-REQUEST FOR <FIELD>

3. START-OF-SELECTION4. TOP-OF-PAGE5. END-OF-PAGE6. AT LINE-SELECTION7. TOP-OF-PAGE DURING LINE-SELECTION

AT LINE-SELECTION:- This event is used to generate an interactive list when ever particular in the out is double clicked.TOP-OF-PAGE DURING LINE-SELECTION:- This event is used to write some thing on top of every page of individual secondary lists. Top-of-page event is used to write something on only basic list.

In these interactive lists we take the help of HIDE table. Hide is an intermediate memory area which is used to hold the values that are used for generation of next secondary list. Hide statement should be used after write statement. Then only you will get correct results. Other wise you will get wrong values. Hide table values you can’t see even in debug mode.

SY-LSIND:- This is also a system variable which gives present processing list number. It’s value will be 0 for basic list and 1 to 20 for secondary lists. We will make use of this sy-lsind in our next program to tell the system about which logic should be executed while going to a particular list..

REPORT ZEVENTS no standard page heading.tables mara.

data: begin of itab occurs 0, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.DATA: BEGIN OF ITAB1 OCCURS 0, MATNR TYPE MARC-MATNR, WERKS TYPE MARC-WERKS, END OF ITAB1.

DATA: BEGIN OF ITAB2 OCCURS 0, MATNR TYPE MAKT-MATNR, MAKTX TYPE MAKT-MAKTX, END OF ITAB2.select-options s_matnr for mara-matnr." no-extension no intervals.

start-of-selection.

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.

Page 77: ABAP

loop at itab. write: / itab-matnr, itab-mbrsh, itab-mtart. HIDE ITAB-MATNR. endloop.

AT LINE-SELECTION. CASE SY-LSIND. WHEN 1. SELECT MATNR WERKS FROM MARC INTO TABLE ITAB1 WHERE MATNR EQ ITAB-MATNR.

LOOP AT ITAB1. WRITE: / ITAB1-MATNR, ITAB1-WERKS. HIDE ITAB1-MATNR. ENDLOOP.

WHEN 2.

select MATNR MAKTX FROM MAKT INTO TABLE ITAB2 WHERE MATNR EQ ITAB1-MATNR.

LOOP AT ITAB2. WRITE: / ITAB2-MATNR, ITAB2-MAKTX. ENDLOOP. ENDCASE.

TOP-OF-PAGE. WRITE / 'DATA FROM MARA TABLE'. TOP-OF-PAGE DURING LINE-SELECTION. CASE SY-LSIND. WHEN 1. WRITE ' DATA FROM MARC TABLE'. WHEN 2. WRITE 'DATA FROM MAKT TABLE'. ENDCASE.

How to change the package?Goto-object directory entry-select the package..

28 th Aug 2012 Reports with Programming.

Addition of two no’s.

Syntax for variable declaration:

Page 78: ABAP

Data: <variable name> type <data type>. Example: Data: a type i. Here data: Allocate the memory for ‘a’ in database. ‘a’ is variable which holds the integer type value. ‘.’ Symbol used to terminate the program.

If we are declaring more than 1 variable then ‘,’ comma symbol used instead of ‘.’ Symbol. Whenever we used ‘.’ Symbol it means program has been terminated.

Printing the value:Syntax: write < variable name>.Exam: write a.

Here write Is keyword which used to produced the output. If we want to print more than 1 value then we have to write ,Write a, b, c.Which will produced the result like 1 2 3. But if we want to produced result in line format, then we have to place ‘/ ‘ symbol before variable which holds the value. Like.Write: / a, /b, c.it will produced result like:123Suppose if we want to pass few arguments on output screen then we have to pass the argument in between ‘ ‘ quotes before variable like….

Write: ‘a=’, a./ ‘b=’, b./ ‘c=’, c.

It will produced the output like

A= 1B= 2C= 3.

Data Type: there are various type of data type in the SAP library but most which we are using are…I : Integer.C: Character.N: D: Date with format DDMMYYYY

Page 79: ABAP

T : TimeP: This is also called packed no which store 16bit.CHAR : this also hold character value with 1 digit.

Simple Program for addition, subtraction, multiplication and division.

Data: a type I, B type I, C type i.

*Addition of two no’s C = a + b.Write c.

*Multiplication of two no.C = a * b.Write c.

*subtraction of two no.C = a - b.Write c.*division of two no

C= a / b.Write c.

Program-1: Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.Solution:

REPORT ZPROGRAM_1.

* calculation of gross salary.with syntax Data declaration*data: BASIC type i,* HRA type i,* DA type i,* GROSS_SAL type i.** BASIC = 10000.** HRA = 40 * BASIC / 100.* DA = 20 * BASIC / 100.** GROSS_SAL = BASIC + HRA + DA.** write: ' Basic is =', BASIC.* write: / ' HRA will be =', HRA.* write: / ' DA will be =', DA.

Page 80: ABAP

* write: /'Gross Salary will be =', GROSS_SAL.

* calculation of gross salary.with syntax 'Parameters' declaration

parameter: BASIC type i.

Data: HRA type i, DA type i, GROSS_SAL type i.

HRA = 40 * BASIC / 100. DA = 20 * BASIC / 100.

GROSS_SAL = BASIC + HRA + DA.

write: ' Basic is =', BASIC. write: / ' HRA will be =', HRA. write: / ' DA will be =', DA. write: /'Gross Salary will be =', GROSS_SAL.

Program-2: The distance between two cities (in km.) is input through the keyboard.

Write a program to convert and print this distance in meters, feet, inches and centimeters. 

Solution: REPORT ZPROGRAM_2.* * calculation of gross salary.with syntax Data declaration

* Data: DISTANCE type i,* METER type i,* FEET type i,* INCH type i,* CENTI_METER type i.** DISTANCE = 10.** METER = DISTANCE * 1000. " 1KM = 1000 meter* CENTI_METER = DISTANCE * 1000 * 100. " 1KM=1000 Mtr, 1Meter=100*CM* INCH = DISTANCE * 1000 * 40. " 1mtr= 39.4 Inch.* FEET = DISTANCE * 1000 * 40 * 12. " 1 feet=12 inch.** write: ' DISTANCE in KM =', DISTANCE.* write: / ' KM converted in to Meter =', METER.* write: / ' KM converted in to Centimeter =', CENTI_METER.* write: / ' KM converted in to Inch =', INCH.* write: / ' KM converted in to Feet =', FEET.

* calculation of gross salary.with syntax 'Parameters' declaration

parameter: DISTANCE type i.

Data: METER type i, FEET type i, INCH type i, CENTI_METER type i.

Page 81: ABAP

METER = DISTANCE * 1000. " 1KM = 1000 meter CENTI_METER = DISTANCE * 1000 * 100. " 1KM=1000 Mtr, 1Meter=100CM INCH = DISTANCE * 1000 * 40. " 1mtr= 39.4 Inch. FEET = DISTANCE * 1000 * 40 * 12. " 1 feet=12 inch

write: ' DISTANCE in KM =', DISTANCE. write: / ' KM converted in to Meter =', METER. write: / ' KM converted in to Centimeter =', CENTI_METER. write: / ' KM converted in to Inch =', INCH. write: / ' KM converted in to Feet =', FEET.

Program-3: If the marks obtained by a student in five different subjects are input

through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100. 

Solution:

REPORT ZPROGRAM_3.

* Calculation of %age

parameters: HINDI type i, ENGLISH type i, MATH type i, PHYSICS type i, CHEMESTR type i.

Data: Tot_Mar type i, Percentage type char5.

Tot_Mar = HINDI + ENGLISH + MATH + PHYSICS + CHEMESTR. Percentage = Tot_Mar * 100 / 500.

write: 'Maximum Marks Obtained in Hindi out of 100 =', HINDI. write: / 'Maximum Marks Obtained in English out of 100 =', ENGLISH. write: / 'Maximum Marks Obtained in Math out of 100 =', MATH. write: / 'Maximum Marks Obtained in Physics out of 100 =', PHYSICS. write: / 'Maximum Marks Obtained in Chemestry out of 100 =', CHEMESTR. write: / 'Total Marks Obtained in 5 Subject =', Tot_Mar. write: / 'Aggregate %age Obtained =', Percentage.

Program-4: Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

Solution:

REPORT ZPROGRAM_4.

* Conversion of tempreture.

parameters: Temp_far type i.

Data: centi_gr type i, Fahren_h type i.

Page 82: ABAP

* to convert farehrit into celsius.

centi_gr = Temp_far - 32.centi_gr = centi_gr * 5.centi_gr = centi_gr / 9.

write: 'After conversion fahreheit into celsius ->', centi_gr.

* to convert celcious in fahrenheit

Fahren_h = Temp_far * 9.Fahren_h = Fahren_h / 5.Fahren_h = Fahren_h + 32.

write: / 'After conversion celcious into fahrenheit ->', Fahren_h.

Program-5: The length & breadth of a rectangle and radius of a circle are input

through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Solution:

EPORT ZPROGRAM_5.

parameters: length type i, breadth type i, radius type i.

Data: area_circle type i, area_rect type i, circu_fe type c, perimeter type i, pai type p decimals 2 value '3.14'.

area_rect = length * breadth. " l * b perimeter = 2 * length + 2 * breadth. " 2(l+b) area_circle = pai * radius * radius. "pai(r*r) circu_fe = 2 * pai * radius. " 2 pai r

write: 'Area of rectangle =', area_rect. write: / 'Perimeter of the rectangle =', perimeter. write: / 'Area of circle =', area_circle. write: / 'circumference of circle =', circu_fe.

SELECT-OPTIONS:- It allows you to input multiple values or range of values into the program. But when ever select-options is used the program syntax changes like this.

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.DATA: D_MATNR TYPE MARA-MATNR, D_MBRSH TYPE MARA-MBRSH, D_MTART TYPE MARA-MTART, D_MEINS TYPE MARA-MEINS.

Page 83: ABAP

SELECT MATNR MBRSH MTART MEINS FROM MARA INTO (D_MATNR,D_MBRSH,D_MTART,D_MEINS) WHERE MATNR IN S_MATNR.

WRITE: / D_MATNR, D_MBRSH, D_MTART, D_MEINS. ENDSELECT.

If in select-options no input is given in the selection-screen system fetches all the data from database from the table for which select query is written. Some times I may get a requirement where this should not happen. That means I want to make the input compulsory. For this use the keyword obligatory. Obligatory keyword makes the input compulsory. The syntax is.

Select-options s_matnr for mara-matnr obligatory.

Some times I may get a requirement to get single record from data base for the given input. That means I want to get first single matching record for the input what ever I give. For that use select single.

Select single is used to get fetch first single matching record for the given input. when ever select single is used you should not use end select.

The sample program is as follows…..

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.DATA: D_MATNR TYPE MARA-MATNR, D_MBRSH TYPE MARA-MBRSH, D_MTART TYPE MARA-MTART, D_MEINS TYPE MARA-MEINS.

SELECT SINGLE MATNR MBRSH MTART MEINS FROM MARA INTO (D_MATNR,D_MBRSH,D_MTART,D_MEINS) WHERE MATNR IN S_MATNR.

WRITE: / D_MATNR, D_MBRSH, D_MTART, D_MEINS.

Some times a requirement may come where I need to fetch n no of records from data base. For that we use select up to n rows. It should contain endselect. The program is as follows

Page 84: ABAP

If I write select up to 1 rows it will fetch single record from data base. This is what is done when we write select single also. Then what is the difference between select single and select up to 1 rows. The differences are

1. Select single doesn’t require endselect but select up to 1 rows requires endselect.2. Use select single when all the primary key fields of a table are used in the select query where

condition. Otherwise use select up to 1 rows. Performance wise SAP is recommending you to use this way. Even though you use interchangingly nothing will happen but performance comes down.

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.DATA: D_MATNR TYPE MARA-MATNR, D_MBRSH TYPE MARA-MBRSH, D_MTART TYPE MARA-MTART, D_MEINS TYPE MARA-MEINS.

SELECT MATNR MBRSH MTART MEINS FROM MARA INTO (D_MATNR,D_MBRSH,D_MTART,D_MEINS) UP TO 10 ROWS WHERE MATNR IN S_MATNR.

WRITE: / D_MATNR, D_MBRSH, D_MTART, D_MEINS.ENDSELECT.

This program will fetch first 10 matching records from database for the given input. If there are no 10 records to be fetched for the given input system fetches what ever the records that are there for the given input.

In the above program we are getting the data record by record only. That means if we want 1 lakh records from data base we are hitting data base 1 lakh times. The performance of the program is low and the network traffic as also high. So my requirement is I want to get all the matching records from data base in single shot and I want to place it in the memory. The memory that we have created in the above programs by those declarations can only hold single record at a time. To over come these problems SAP has come up with a concept of internal tables.

Sign = I.Option = EQ.BT.Low = Value 1High = value 2.

INTERNAL TABLES

Page 85: ABAP

Internal table is an intermediate table. It can hold multiple records at a time. It is a temporary table. The memory for the internal table will be allocated at runtime and de allocated after the execution of the program automatically by the system. The changes that made to the records of internal table are temporary. The changes are not reflected in data base until some DML commands are written. Hence original data is retained in data base. There are three types of internal tables.

1. Standard Internal Tables2. Sorted Internal Tables3. Hashed Internal Tables.

There two ways to declare the Internal tables.1. Internal Tables with Header line.2. Internal tables without Header line.

INTERNAL TABLE WITH HEADER LINE

Header of the internal table can contain only single record and body can contain multiple records. If we are writing the logic to move record by record by record from DB table to header of internal table, after record comes into header it has to be moved to body of internal table by saying append <table name>. If it is needed to write the records present in the body of internal table into list, record by record has to be moved to header and written out. For this we have to write loop at <internal table>. When ever it is needed to make the changes in the records present in the body of internal table, every record has to be moved to header and modified. We can not do any operations on the records directly present in the body of the internal table. These things we have to keep in mind.

Syntax for declaring internal table with header line is…..

Data: begin of <internal table name> occurs 0, <Fieldname> type <tablename-filedname>, <Fieldname1> type <tablename-filedname>, -------------, -------------, End of <internal table name>.

Sample program is as follows………………

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.data: begin of itab occurs 0, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.

select matnr mbrsh mtart from mara into itab where matnr in s_matnr.

Page 86: ABAP

append itab.endselect.

loop at itab.write: / itab-matnr, itab-mbrsh, itab-mtart. endloop.

This program is also performance wise very poor. Because here also we are getting the records one by one only. That means here network traffic will be more and the burden on the server will be high. My requirement is I want to get the data from data base in single shot and directly I want to place the records in the body of the internal table. For this we have to modify the select query like this.

Sample program is like this…….

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.data: begin of itab occurs 0, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.*append itab.*endselect.

loop at itab.write: / itab-matnr, itab-mbrsh, itab-mtart. endloop.

In the above select query I have used select into table. Into table statement fetches all the matching required records from database in single shot and directly places into the body of internal table. Hence in the above program I have commented append and endselect. Always when ever you use internal tables try to use into table which improves the performance of the program.

Begin of itab occurs 0 statement creates an internal table with name itab with header line.

SY-TABIX:- It is a system variable which gives present processing record number.

SY-DBCNT:- It is also a system variable which gives no of records fetched from data base table.

SY-SUBRC:- It is an important system variable. It is used to find out where previous ABAP statement is executed successfully or not. If it is successfully executed SY-SUBRC value will be 0. If it is not executed successfully it’s value can be 4 or 8 or 12 or 16. If you want to check whether previous

Page 87: ABAP

statement executed successfully or not always check whether SY-SUBRC equal to 0 or not equal to 0. If equal to 0 statement executed successfully, otherwise not executed successfully.

You can see a sample program with all these variables.

REPORT ZINTERNAL .tables mara.select-options s_matnr for mara-matnr.data: begin of itab occurs 0, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.if sy-subrc eq 0.write: / 'no of records fetched from db', sy-dbcnt.loop at itab.write: / sy-tabix, itab-matnr, itab-mbrsh, itab-mtart. endloop.else.write: / 'no data to display'.endif.

INTERNAL TABLES WITHOUT HEADER LINE

When ever begin of <internal table name> occurs 0 is used to create an internal table system by default allocates 8KB of memory. If no of records fetched from database table are more, that memory system initially allocated may not be sufficient. Hence system will allocate extra memory. The extra memory allocated will be in multiples of 8KB only. Hence in this case there is a possibility that memory may be wasted. Since memory is allocated in pockets of 8KB the performance of the program comes down. To avoid all these problems SAP has come up with a concept of internal tables without header line. In this case internal table directly contains body without header. When ever internal table is created without header line we have to create a work area. Here work area acts like a header which can contain single record. The condition is the structure of work area and internal table should be same or at least it should be compatible.

When ever it is needed to create an internal table without header line we use TYPES keyword in the program. This keyword is used to create a structure. Using this structure create an internal table as well as work area. We see a sample program which creates an internal without header line.

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.types: begin of ty_itab, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart,

Page 88: ABAP

end of ty_itab.

data itab type standard table of ty_itab.data wa type ty_itab.

select matnr mbrsh mtart from mara into wa where matnr in s_matnr. append wa to itab. endselect.

loop at itab into wa. write: / wa-matnr, wa-mbrsh, wa-mtart. endloop.

In this above program first I have created a structure ty_itab using types statement ( Structure internally contains fields). Using this structure I have created an internal table (ITAB) and as well as work area (WA). When ever type standard table of syntax is used it creates an internal table. If we use only type in the syntax it creates work area. But in the above program first record by record is coming into work area and then it is appended into the body of the internal. This program is not good performance wise. Because we have to get the records in single shot from database and have to place directly into the body of internal table. For that purpose we can write the program like this which improves the performance.

REPORT YSELECT9 .TABLES MARA.SELECT-OPTIONS S_MATNR FOR MARA-MATNR.types: begin of ty_itab, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of ty_itab.

data itab type standard table of ty_itab.data wa type ty_itab.

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.* append wa to itab.* endselect.

loop at itab into wa. write: / wa-matnr, wa-mbrsh, wa-mtart. endloop.

CLEAR:- This keyword clears/deletes the contents from the header of internal table or from the variable memory.

Page 89: ABAP

Syntax:- CLEAR <TABLE NAME>/<VARIABLE NAME>.

REFRESH:- This keyword deletes the contents from the body of the internal table.

Syntax:- REFRESH < TABLE NAME>. Instead of this we can also use the syntax CLEAR <TABLE NAME[]> .This statement also deletes the contents from the body of the internal table.

In SAP [] indicates the body of internal table.Eg:- itab[] indicates the body of the internal table itab.

FREE:- This keyword is used to deallocate the memory allocated for internal table as well as any variable .

Syntax:- FREE <TABLE NAME>/<VARIABLE NAME>.

CONTROL STATEMENTS

Control statements are nothing but loops. The property of the loop is to rotate by it self until loop is terminated. There are 4 types of control statements in SAP. They are

1. DO.………..………..ENDDO.

2. DO N TIMES.………..………..ENDDO.

3. WHILE <CONDITION>.………..………..ENDWHILE.

4. CASE <VARIABLE>.WHEN <VALUE1>. ……….. ………..WHEN <VALUE2>. ………..…………WHEN OTHERS. ………..…………

Page 90: ABAP

ENDCASE.

Exit statement is used to terminate the loop. SY-INDEX is a system variable which gives present loop iteration number. These both things we use in coming program to see how they act in the loop.

DO LOOP SAMPLE PROGRAM

*&---------------------------------------------------------------------**& Report ZSAMPLE **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT ZSAMPLE .

DO. WRITE / SY-INDEX. IF SY-INDEX EQ 10. EXIT. ENDIF.ENDDO.

In this program the control comes out of the program when sy-index value becomes 11. That means at 11th iteration the control comes out of the loop.

For aligning the program lines use PRETTY PRINTER button present on the application tool bar of the ABAP editor.

Good I have written the above program and I will get the following output and I am happy.

Page 91: ABAP

But my requirement is to see how the variable’s values are changing while execution of the program. This technique is called Debugging. To see how control is moving while execution of a program we have to stop the control at some point or at some line in the program. That point is called Break Point.

DEBUGGING:- It is a technique to see how control is moving while execution of a program.

BREAK POINT:- It is a line in the program where control is needed to be stopped while execution.

To keep the break point in the program at particular line, keep the cursor on that particular line and press STOP button. That line immediately turns to yellow color and at the status bar you will get a message saying that Breakpoint set. When you execute the program the control goes to that particular line and program execution is stopped there. To execute the program further you have to use the following keys.

F5 --- > FOR LINE BY LINE EXECUTION.F6 --- > TO COME OUT OF LOOP.F7 --- > TO COME OUT OF FUNCTION MODULE.

F8 --- > TO GOTO NEXT BREAK POINT IF EXISTS OR TO EXECUTE THE PROGRAM COMPLETELY.

Page 92: ABAP

Maximum number of break points allowed are 30. Sap has given option to keep these many break points to easily debug a program which is having many lines. When you execute the program in debugging mode the screen will be in this format.

Page 93: ABAP

What ever the fields value you want to find out while execution you double click on the filed name. Immediately field name comes under Field names and value comes under Field contents. Otherwise you can also type the Filed name under Field names and press enter.

If you want to delete the break point that is set, keep cursor on the line where break point is set and once again press STOP button. The break point will be deleted. One more thing you have to remember is break points can be set in a program if program is active. That means we can not keep break point in a program if program is inactive. The break points that are set using Stop button are automatically deleted when you logout. You cannot see those break points once you login.

If you want to keep permanent break points use keyword BREAK-POINT. This keyword is used to keep permanent break points. Where you want to stop the control before that line use this break-point key word.

Sometimes a requirement may come to set the break point for a particular user. In that case BREAK <USER NAME> key board. Let us assume that you have logged in with sapuser and if you want to set break point to that particular use only then syntax will be …….

BREAK SAPUSER.

If you execute the program in that sapuser only the program goes to debug mode. If you execute the program in others the program will be executed in normal mode.

Page 94: ABAP

From now onwards what ever the program you write you try to execute the program in debug mode. So that you will understand the program well.

One more thing you have to remember is that whenever do loop is used it is mandatory to use Exit statement. Other wise the program will be in infinite loop and you never get the output.

MATHEMATICAL OPERATORS RELEVENT SAP OPERATORS

= EQ< LT> GT<= LE>= GE>< NE

We can also use mathematical operators or relevant sap operators inABAP programming. But SAP is recommending you to use relevant SAP operators only. If you see SAP standard programs they have also used all relevant SAP operators.

DO N TIMES SAMPLE PROGRAM

*&---------------------------------------------------------------------**& Report ZSAMPLE **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT ZSAMPLE .

DO 10 TIMES. WRITE / SY-INDEX.ENDDO.

The output of this program will also be the same as above i.e. 1 to 10. In Do n times loop there is need to use Exit statement because the loop will be rotated for those many times and then the control comes out of the loop.

WHILE LOOP SAMPLE PROGRAM

*&---------------------------------------------------------------------**& Report ZSAMPLE **& **&---------------------------------------------------------------------**& *

Page 95: ABAP

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

REPORT ZSAMPLE .

WHILE SY-INDEX LE 10. WRITE / SY-INDEX.ENDWHILE.

The output of this program is also same as above two programs i.e. 1 to 10.

Now we discuss about the differences between DO loop and WHILE loop a famous question in C language.

1. In Do loop we enter into the loop and check the condition, but in While loop first we check the condition then only we enter in to the loop.

2. Minimum number of number of times Do loop executed is one time, but while loop minimum number of times executed is Zero. If condition is wrong the control will not enter into the loop.

CASE STATEMENT SAMPLE PROGRAM

*&---------------------------------------------------------------------**& Report ZSAMPLE **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT ZSAMPLE .PARAMETERS Z.CASE Z. WHEN 'A'. WRITE / 'YOU ENTERED A'. WHEN 'B'. WRITE 'YOU ENTERED B'. WHEN OTHERS. WRITE 'YOU ENTERED OTHER ALPHABIT'.ENDCASE.

If A is given as input to this program we get YOU ENTERED A as out. If B is given as input we get YOU ENTERED B AS OUTPUT. If other than A or B is given as input we get YOU ENTERED OTHER ALPHABIT as output.

Now my question is if you write the following program…..*&---------------------------------------------------------------------**& Report ZSAMPLE **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT ZSAMPLE .

Page 96: ABAP

PARAMETERS Z.CASE Z. WHEN 'a'. WRITE / 'YOU ENTERED A'. WHEN 'B'. WRITE 'YOU ENTERED B'. WHEN OTHERS. WRITE 'YOU ENTERED OTHER ALPHABIT'.ENDCASE.

Here in this program in when condition ‘A’ is changed to ’a’. What will be the out if enter a in the selection-screen. Think it and read the following lines.

The output will be YOU ENTERED OTHER ALPHABIT. But why? Because the input characters in the selection-screen are automatically converted to upper case. This we have discussed earlier. This is the property of selection-screen. Here my intension is to specify that what ever you give in the case statement in when condition, give with in quotes only upper case letters. Other wise you get abnormal results. That you have to remember it. You can try this thing.

LOOP TERMINATING STATEMENTS

1. EXIT2. STOP3. CONTINUE4. CHECK

1. EXIT :- We have already discussed about it. Exit statement is used to terminate the loop. The statements after the loop will be executed normally. Let us analyse the following program.

*&---------------------------------------------------------------------**& Report ZLOOPS **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT ZLOOPS .do. write / sy-index. if sy-index eq 10. exit. endif.enddo.write / 'HELLO'.

The output of the above program will be …..

Page 97: ABAP

When sy-index becomes 11 the loop will be terminated and we are having a write statement after the loop. That will be executed normally. That is the reason why we are getting HELLO in the output along with the numbers.

2. STOP:- Whenever stop statement is used in the program, immediately after the execution of the STOP statement the whole program will be terminated. That means no statement after execution of STOP will be executed. STOP statement completely terminates the program.

Try to analyze the following program.

REPORT ZLOOPS .do. write / sy-index. if sy-index eq 10. stop. endif.enddo.write / 'HELLO'.

The output of this program will be …..

Page 98: ABAP

You can see that the write statement which we have written the after the loop is not executed. That is the reason why we are not getting HELLO in the output. When system enters in to if statement when sy-index becomes 10, system executes STOP statement which immediately terminates whole program. STOP can be used out side the loop also. Remember no statement after execution of STOP will be executed.

3. CONTINUE:- This statement terminates present loop iteration and goes to next loop iteration. Analyze this program.

REPORT ZLOOPS .do.if sy-index eq 2.continue.endif. write / sy-index. if sy-index eq 10. exit. endif.enddo.

The output of this program will be ……..

Page 99: ABAP

You can clearly see that there is no 2 in the output. Because in the program I have written the logic that the system should execute continue statement when sy-index becomes 2. The write statement is written after if statement containing continue statement. That is the reason write statement is not executed when sy-index is 2 and it is not printed in the output. You debug this program then you understand it better.

3. CHECK:- This statement returns true or false. If check returns true the statements after it will be executed. If it returns false the statements after it will not be executed. Even though check returns false value the loop will be continued.Analyze this following example.

REPORT ZLOOPS .do. write / sy-index. if sy-index eq 10. exit. endif.check sy-index eq 2.write / sy-index.enddo.

The output of this program will be ……..

Page 100: ABAP

2 is printed two times. Check condition in this program returns true value when sy-index becomes 2. Then only the write statement written after the check will be executed.

Let us assume that the CHECK statement is written outside the loop and it is writtening false value. Then all the statements written after it will not be executed. That means it acts like STOP. That is If CHECK is written outside the loop and if it returns false value it acts like STOP.

STRING OPERATIONS

TRANSLATE:- This keyword is used to convert character type variables from one case to another case.

Syntax is …….

TRANSLATE <VARIABLE NAME> TO LOWER CASE/UPPER CASE.

Sample program is ………..

REPORT ZLOOPS .

PARAMETERS A(10).TRANSLATE A TO LOWER CASE.

Page 101: ABAP

If RAMESH is given as input to this program output will be ramesh. You can also use upper case key word with translate. But there is no use because what ever we give in selection-screen will be automatically converted to upper case by default.

STRING LENGTH:- STRLEN keyword is used to find out string length.

Syntax is….. STRLEN( VARIABLE NAME ).

Sample program is……..

REPORT ZLOOPS .parameters: a(20).data len type i.len = strlen( a ).write len.

If I give RAMESH as input to this program I will get 6 as output, because RAMESH string is containing 6 characters.

CONCATENATION OF STRINGS:- CONCATENATE key word id used to concatenate strings into a single string.

Syntax is ….. CONCATENATE <STRING1> <STRING2> INTO <STRING3> SEPARATED BY SPACE/<’CHARACTER’>.

Sample program is …..

REPORT ZLOOPS .parameters: a(10), b(10).data c(20).concatenate a b into c.write c.

If I give input RAMESH for A and REDDY for B I get output as RAMESHREDDY. Let us assume that I want space between two strings, i.e. space between RAMESH and REDDY I should write program like this.

REPORT ZLOOPS .parameters: a(10), b(10).data c(20).concatenate a b into c separated by space.write c.

If I give input RAMESH for A and REDDY for B I get output as RAMESH REDDY. Space will come between the strings. If I want , between the strings I should use following line in the program instead of concatenate line present in the above program.

Page 102: ABAP

concatenate a b into c separated by ‘,’.

If I use this line in the program I will get comma between the strings.When ever we are giving space in the concatenate syntax it should not be in the quotes,

because space is a key word. If any other character is required between the strings other than space that character should be given in the quotes.

SPLITTING A STRING:- Let us assume that I require to split a string at a particular character. Let us say that I want to split a string at comma (,). For this I have to use SPLIT keyword. Syntax is ….

SPLIT <STRING> AT <‘CHARACTER’> INTO <STRING1> <STRING2>…….<STRINGN>.

Sample program is ……

REPORT ZLOOPS .parameters: a(20).data: b(10), c(10).split a at ',' into b c.write : / b, / c.

If to the above program if I give input as RAMESH,REDDY. It will be splitted into 2 variables B and C. In to B it will push RAMESH and into C it will push REDDY.In to the above program if give input as INDIA,USA,UK,AUS. Till INDIA it will be moved to B and USA,UK,AUS will be moved to C variable. That means when ever we say that particular string should be splitted into N number of variables, the system will search for (N-1) commas and accordingly it will split the string.

REPLACING A CHARACTER WITH SOME OTHER CHARACTER:- For this purpose we have to use REPLACE keyword. The syntax is as follows…..

REPLACE <’CHARACTER’> WITH <’CHARACTER1’> INTO <STRING>.

Sample program can be seen below. This program is used to replace all characters present in a string A with space.

REPORT ZLOOPS .parameters: a(20).

do.if a ca ','.replace ',' with space into a.else.exit.endif.

Page 103: ABAP

enddo.

write a.

Here in the above program we used a keyword CA which means contains any.You can debug the program you will understand better about the logic.

If you want to see documentation for any keyword present in ABAP just type the keyword in ABAP editor and keep cursor on the keyword and press F1. It will open beautiful documentation regarding the keyword.

OFFSETTING:- It is a mechanism used to move the control to particular position of a string. That means let us assume that I want 3rd character form the string. Then I can go for offsetting. The system interprets string positions as below.

R A M E S H0 1 2 3 4 5

Instead of starting from 1 system gives the positions from 0. That means if I want 3rd character physically I should search for the 2nd character as per system representation.

The syntax for offsetting is ……

<DESTINATION STRING > = <SOURCE STRING>+<SYTEM REP CHAR POSITION><(NO OF CHARS REQUIRED)>.

Here + is called offsetting mechanism. The difference between mathematical operate + and this offsetting mechanism + is that, when ever we use mathematical operator + we give space before and after the + but in this offsetting mechanism + the is no space before and after the +. That is the difference.

Consider the following example. I give the input as RAMESH into variable A. I want to move 3 rd

character from this variable into B variable.Then

A = RAMESH B = A+2(1).Then M will be move to B.If I want 3rd and 4th characters into B, Then I have to change above statement as ….

B = A+2(2). Both ME will be moved into B.If I want to move all character from third position ( I am talking about physical positions) into B, Then I have to say..

B = a+2. Don’t give any thing in brackets.If I want entire string into B, I have to say…B = A+0. whole RAMESH will be moved into B.

Execute the following program and analyze the things.

REPORT ZLOOPS .parameters: a(20).

Page 104: ABAP

data b(20).

b = a+2(1).write b.

LOGIC FOR FINDING THE LAST CHARACTER OF A STRING.

REPORT ZLOOPS .parameters: a(20).data len type i.data b.len = strlen( a ).len = len - 1.

b = a+len.write b.

SY-FDPOS:- It is a system variable used to find the position where the search is successful. Let us assume that you are searching for a comma in a string and you want to find out the position where comma is present in the string. Then we can use this system variable. But it acts abnormally. If string is not containing the particular character for which you are searching sy-fdpos system variable takes the declared length of a string which you are searching. You can execute the following program and see the results.

REPORT ZLOOPS .parameters: a(30).

if a ca ','.write sy-fdpos.else.write sy-fdpos.endif.

Append: New record to be appended in the itab.

Modify: Modify is used 1) to update already existing record in itab. 2) to insert new record in z-table

Insert: this is used to insert new record in the z-table.

Update: This is also used to update/modify already existing record in z-table.

ALV program: Line program.

REPORT ZPROGRAM_6 no standard page heading line-size 100.

uline.write: /1 sy-vline.

Page 105: ABAP

3(10) 'Name' inverse on color 6, 14 sy-vline, 16(15) 'Designation', 33 sy-vline, 35(10) 'Contact'. 100 sy-vline. uline.

write: /1 sy-vline. 3(10) 'Ashish', 14 sy-vline, 16(15) 'Consultant', 33 sy-vline, 35(10) '123456789', 100 sy-vline. uline.

MODULARIZATION

It is a technique of splitting larger code into smaller block of code. It is done for easy understanding, easy debugging and to decrease the code. We can achieve this in SAP using 4 concepts.

1. Events2. Subroutines3. Include programs4. Function modules

Note: Events we have already discussed above.

SUBROUTINES

When ever same logic is needed to be executed many times in a program, create a subroutine and call the subroutine when ever the logic is needed to be executed.

Perform statement is used to create the subroutine and to call the subroutine. A subroutine can be created with passing the variables and without passing the variables. The logic of the subroutine is written between form and endform. It is not required to start the subroutine name with Z OR Y.

First we will see how to create the subroutine with passing the variables.

See the following example.

REPORT ZSELECT20 .parameters: a type i, b type i.

data c type i.

perform add using a b changing c.

Page 106: ABAP

write: / 'the sum of two numbers is', c.*&---------------------------------------------------------------------**& Form add*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** -->P_A text* -->P_B text* <--P_C text*----------------------------------------------------------------------*FORM add USING A B CHANGING C.

c = a + b.ENDFORM. " add

No need to write the form and endform manually. When you double click the perform name written in perform statement (ADD) automatically system will create form and endform. Between the form and endform write the logic what ever you want.

Now we will see how to create a subroutine without passing the variables.

REPORT ZSELECT20 .tables mara.select-options s_matnr for mara-matnr.data: begin of itab occurs 0, matnr type mara-matnr, mbrsh type mara-mbrsh, mtart type mara-mtart, end of itab.

perform select.perform display.*&---------------------------------------------------------------------**& Form select*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM select .

select matnr mbrsh mtart from mara into table itab where matnr in s_matnr.

ENDFORM. " select*&---------------------------------------------------------------------**& Form display*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM display .

Page 107: ABAP

loop at itab.write: / itab-matnr, itab-mbrsh, itab-mtart. endloop.ENDFORM. " displaystart-of-selection.write 'hello'.

No statement after form and endform is accessible. After form and endform only form and endform is accessible. If you want to access any statement after form and endform we have to use start-of-selection event.

Usually subroutines are local to a program. They are not stored in database. They are not self executable. If you want to call a subroutine ADD (say) created in some X program from Y program , you have to write this syntax in Y program

Perform <perform name><(program name)>.Perform add(X).

INCLUDE PROGRAMS

These programs are also used for reusability. Include program name should start with either Z or Y. There are two ways to create include programs.

1. Directly from SE38 we can create include program. Here we have to choose program type as include program.

Page 108: ABAP

2. Directly from the program also we can create include program. In the program write Include <include program name>. Keep cursor on the include program name and double click. If the program is not available, it will ask for the creation, say yes and move forward.

Page 109: ABAP
Page 110: ABAP

After creation of include program if it is needed to call the include program from another program use the statement include <Include program name>.

Search Help Programming:

REPORT zrprogram_at_selection_events .

DATA : lv_year TYPE char4,

lv_year1 TYPE char4,

lv_field TYPE dfies-fieldname,

lt_help TYPE TABLE OF zfiscal_year,

ls_help TYPE zfiscal_year,

Page 111: ABAP

lt_return TYPE TABLE OF ddshretval,

ls_return TYPE ddshretval.

PARAMETERS : p_year TYPE char7,"MATCHCODE OBJECT zfiscal_year_sh,

p_date TYPE dats,

p_check TYPE char10.

AT SELECTION-SCREEN OUTPUT.

lv_year = sy-datum+0(4) + 1.

lv_year1 = sy-datum+0(4).

CONCATENATE sy-datum+0(4)'-' lv_year+2(2) INTO p_year.

p_date = sy-datum.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_year.

DO 10 TIMES.

IF sy-index = 1.

lv_year = sy-datum+0(4) + 1.

lv_year1 = sy-datum+0(4).

CONCATENATE sy-datum+0(4)'-' lv_year+2(2) INTO ls_help-ficalyr.

APPEND ls_help TO lt_help.

Page 112: ABAP

CLEAR ls_help.

ELSE.

CLEAR lv_year.

lv_year = lv_year1 + 1.

CONCATENATE lv_year1 '-' lv_year+2(2) INTO ls_help-ficalyr.

APPEND ls_help TO lt_help.

CLEAR ls_help.

ENDIF.

lv_year1 = lv_year1 + 1.

ENDDO.

lv_field = 'P_YEAR'.

**F4 Help

CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'

EXPORTING

retfield = lv_field

dynpprog = sy-repid

dynpnr = sy-dynnr

Page 113: ABAP

value_org = 'S'

TABLES

value_tab = lt_help[]

return_tab = lt_return.

IF lt_return[] IS NOT INITIAL.

READ TABLE lt_return INTO ls_return INDEX 1.

IF sy-subrc = 0.

p_year = ls_return-fieldval.

ENDIF.

ENDIF.

AT SELECTION-SCREEN.

p_check = 'ABCDEFGH'.

Button Programming:

Pushbutton: *&---------------------------------------------------------------------**& Include ZRPROGRAM_BUTTONS_S01 **&---------------------------------------------------------------------*

SELECTION-SCREEN : BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS : p_num1 TYPE i, p_num2 TYPE i.SELECTION-SCREEN : END OF BLOCK b1.

***CHECKBOX DECLARATION*SELECTION-SCREEN : BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.*PARAMETERS : check1 type checkbox,* check2 type checkbox,* check3 type checkbox,* check4 type checkbox.*SELECTION-SCREEN : END OF BLOCK b2.

***RADIOBUTTON DECLARATION*SELECTION-SCREEN : BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.*PARAMETERS : RAD1 radiobutton group rad default 'X',* RAD2 radiobutton group rad,* RAD3 radiobutton group rad,* RAD4 radiobutton group rad.*SELECTION-SCREEN : END OF BLOCK b2.

Page 114: ABAP

***PUCHBUTTON DECLARATIONSELECTION-SCREEN : BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.SELECTION-SCREEN : PUSHBUTTON /2(10) but1 USER-COMMAND cmd1, PUSHBUTTON 15(10) but2 USER-COMMAND cmd2, PUSHBUTTON 28(10) but3 USER-COMMAND cmd3, PUSHBUTTON 40(10) but4 USER-COMMAND cmd4.SELECTION-SCREEN : END OF BLOCK b2.

SELECTION-SCREEN : BEGIN OF BLOCK b3 WITH FRAME TITLE text-003.PARAMETERS : p_num3 TYPE i.SELECTION-SCREEN : END OF BLOCK b3.

INITIALIZATION. but1 = 'Add'. but2 = 'Subtract'. but3 = 'Multiply'. but4 = 'Divide'.

*&---------------------------------------------------------------------**& Include ZRPROGRAM_BUTTONS_F01 **&---------------------------------------------------------------------*

*&---------------------------------------------------------------------**& Form frm_calculation*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*FORM frm_calculation .

* IF check1 = 'X'.* p_num3 = p_num1 + p_num2.* ELSEIF check2 = 'X'.* p_num3 = p_num2 - p_num1.* ELSEIF check3 = 'X'.* p_num3 = p_num1 * p_num2.* ELSEIF check4 = 'X'.* p_num3 = p_num1 / p_num2.* ENDIF.

* IF rad1 = 'X'.* p_num3 = p_num1 + p_num2.* ELSEIF rad2 = 'X'.* p_num3 = p_num2 - p_num1.* ELSEIF rad3 = 'X'.* p_num3 = p_num1 * p_num2.* ELSEIF rad4 = 'X'.* p_num3 = p_num1 / p_num2.* ENDIF.

* IF sy-ucomm = 'CMD1'.* p_num3 = p_num1 + p_num2.* ELSEIF sy-ucomm = 'CMD2'..* p_num3 = p_num2 - p_num1.

Page 115: ABAP

* ELSEIF sy-ucomm = 'CMD3'..* p_num3 = p_num1 * p_num2.* ELSEIF sy-ucomm = 'CMD4'.* p_num3 = p_num1 / p_num2.* ENDIF.* CASE sy-ucomm. WHEN 'CMD1'. p_num3 = p_num1 + p_num2.

WHEN 'CMD2'. p_num3 = p_num2 - p_num1.

WHEN 'CMD3'. p_num3 = p_num1 * p_num2.

WHEN 'CMD4'. p_num3 = p_num1 / p_num2. ENDCASE.

ENDFORM. " frm_calculation

Profram for intering data in table:*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_T01 **&---------------------------------------------------------------------*

TABLES: zprogram_book.DATA: itab TYPE TABLE OF zprogram_book WITH HEADER LINE.

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_S01 **&---------------------------------------------------------------------*

SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: book_id TYPE zprogram_book-book_id, book_nam TYPE zprogram_book-book_name, book_aut TYPE zprogram_book-book_auth, book_pub TYPE zprogram_book-book_public, book_pri TYPE zprogram_book-book_price.

SELECTION-SCREEN: END OF BLOCK b1.

SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.SELECTION-SCREEN: SKIP 2,PUSHBUTTON 4(10) a1 USER-COMMAND insert,PUSHBUTTON 16(10) a2 USER-COMMAND update,PUSHBUTTON 28(10) a3 USER-COMMAND modify,PUSHBUTTON 40(10) a4 USER-COMMAND delete.SELECTION-SCREEN: END OF BLOCK b2.

INITIALIZATION.

a1 = 'INSERT'. a2 = 'UPDATE'. a3 = 'MODIFY'. a4 = 'DELETE'.

Page 116: ABAP

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_F01 **&---------------------------------------------------------------------**&---------------------------------------------------------------------**& Form insertion_data*&---------------------------------------------------------------------** text*----------------------------------------------------------------------**FORM insertion_data . CASE sy-ucomm. WHEN 'INSERT'. itab-book_id = book_id. itab-book_name = book_nam. itab-book_auth = book_aut. itab-book_public = book_pub. itab-book_price = book_pri. INSERT INTO zprogram_book VALUES itab. IF sy-subrc = 0. MESSAGE 'Data Insetred in the Table' TYPE 'S'. else. message 'Record Already Exist' type 'S'. ENDIF.

WHEN 'UPDATE'. itab-book_id = book_id. itab-book_name = book_nam. itab-book_auth = book_aut. itab-book_public = book_pub. itab-book_price = book_pri. UPDATE zprogram_book FROM itab. IF sy-subrc = 0. MESSAGE 'Data updated in the Table' TYPE 'S'. ENDIF.

WHEN 'MODIFY'. itab-book_id = book_id. itab-book_name = book_nam. itab-book_auth = book_aut. itab-book_public = book_pub. itab-book_price = book_pri. MODIFY zprogram_book FROM itab. IF sy-subrc = 0. MESSAGE 'Data Modified in the Table' TYPE 'S'. else. message 'Record Already Exist' type 'S'.

ENDIF.

WHEN 'DELETE'. itab-book_id = book_id. itab-book_name = book_nam. itab-book_auth = book_aut. itab-book_public = book_pub. itab-book_price = book_pri. DELETE zprogram_book FROM itab. IF sy-subrc = 0. MESSAGE 'Data Deleted the Table' TYPE 'S'. ENDIF.

Page 117: ABAP

ENDCASE.

ENDFORM. " insertion_data

Program for check box:

*&---------------------------------------------------------------------**& Report ZPROGRAM_BOOK_CHECKBOX **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT zprogram_book_checkbox .

SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: a TYPE i, b TYPE i, c(4) TYPE c.SELECTION-SCREEN: END OF BLOCK b1.

SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.PARAMETERS: add TYPE checkbox USER-COMMAND c1, sub TYPE checkbox USER-COMMAND c2, mult TYPE checkbox USER-COMMAND c3, div TYPE checkbox USER-COMMAND c4.SELECTION-SCREEN: END OF BLOCK b2.

AT SELECTION-SCREEN. CASE sy-ucomm. WHEN 'C1'. c = a + b. clear: sub, mult, div. WHEN 'C2'. c = a - b. clear: add, mult, div.

WHEN 'C3'. c = a * b. clear: Add, sub, div.

WHEN 'C4'. c = a / b. clear: Add, sub, mult. ENDCASE.

Entering Data through checkbox:

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_CHECKBOX1 **&---------------------------------------------------------------------*

** Table declarationTABLES: zprogram_book.

Page 118: ABAP

DATA: wa type zprogram_book.

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_CHECKBOX2 **&---------------------------------------------------------------------*

** First Selection ScreenSELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: book_id TYPE zprogram_book-book_id, book_nam TYPE zprogram_book-book_name, book_aut TYPE zprogram_book-book_auth, book_pub TYPE zprogram_book-book_public, book_pri TYPE zprogram_book-book_price.SELECTION-SCREEN: END OF BLOCK b1.

** Second Selection Screen.SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.PARAMETERS: insert TYPE checkbox user-command C1, update TYPE checkbox user-command C2, modify TYPE checkbox user-command C3, delete TYPE checkbox user-command C4.SELECTION-SCREEN: PUSHBUTTON /15(10) a1 USER-COMMAND done.SELECTION-SCREEN: END OF BLOCK b2.

INITIALIZATION.

a1 = 'DONE'.

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_CHECKBOX3 **&---------------------------------------------------------------------**&---------------------------------------------------------------------**& Form table_maintence*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*

FORM table_maintence. CASE sy-ucomm. WHEN 'C1'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri.

INSERT zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE ' Data Inserted in the Table' TYPE 'S'. ENDIF. CLEAR: update, modify, delete. WHEN 'C2'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. UPDATE zprogram_book FROM wa. IF sy-subrc = 0.

Page 119: ABAP

MESSAGE 'Data updated in the Table' TYPE 'S'. ENDIF. CLEAR: insert, modify, delete.

WHEN 'C3'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. MODIFY zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE 'Data Modified in the Table' TYPE 'S'. ELSE. MESSAGE 'Record Already Exist' TYPE 'S'.

ENDIF. CLEAR: update, insert, delete. WHEN 'C4'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. DELETE zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE 'Data Deleted the Table' TYPE 'S'. ENDIF.

CLEAR: update, modify, insert. ENDCASE.ENDFORM. " table_maintence

Entering data through Radio Button:

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_RADIO1 **&---------------------------------------------------------------------*TABLES: zprogram_book.DATA: wa type zprogram_book.

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_RADIO2 **&---------------------------------------------------------------------*** First Selection ScreenSELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: book_id TYPE zprogram_book-book_id, book_nam TYPE zprogram_book-book_name, book_aut TYPE zprogram_book-book_auth, book_pub TYPE zprogram_book-book_public, book_pri TYPE zprogram_book-book_price.SELECTION-SCREEN: END OF BLOCK b1.

** Second Selection Screen.

SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.PARAMETERS: rad1 RADIOBUTTON GROUP rad USER-COMMAND radio DEFAULT 'X',

Page 120: ABAP

rad2 RADIOBUTTON GROUP rad, rad3 RADIOBUTTON GROUP rad, rad4 RADIOBUTTON GROUP rad, rad5 RADIOBUTTON GROUP rad.SELECTION-SCREEN: END OF BLOCK b2.

*&---------------------------------------------------------------------**& Include ZPROGRAM_BOOK_RECORD_RADIO3 **&---------------------------------------------------------------------**&---------------------------------------------------------------------**& Form table_maintence_radio*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*

FORM table_maintence_radio . CASE sy-ucomm.

WHEN 'RADIO'. IF rad1 = 'X'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri.

INSERT zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE ' Data Inserted in the Table' TYPE 'S'. ENDIF. ELSEIF rad2 = 'X'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. UPDATE zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE 'Data updated in the Table' TYPE 'S'. ENDIF.

ELSEIF rad3 = 'X'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. MODIFY zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE 'Data Modified in the Table' TYPE 'S'. ELSE. MESSAGE 'Record Already Exist' TYPE 'S'. ENDIF.

ELSEIF rad4 = 'X'. wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri. DELETE zprogram_book FROM wa.

Page 121: ABAP

IF sy-subrc = 0. MESSAGE 'Data Deleted the Table' TYPE 'S'. ENDIF.

ELSEIF rad5 ='X'. "Deisplay Record CLEAR wa. SELECT SINGLE * FROM zprogram_book INTO wa WHERE book_id = book_id. IF sy-subrc = 0. book_nam = wa-book_name. book_aut = wa-book_auth. book_pub = wa-book_public. book_pri = wa-book_price. ENDIF.

ENDIF.

ENDCASE.

ENDFORM. " table_maintence_radio

Data Entry in the table by Function Key:

*&---------------------------------------------------------------------**& Include ZPROGRAM_FUNCTION_KEYS_T01 **&---------------------------------------------------------------------*

** Table declarationTABLES: zprogram_book, sscrfields.DATA: wa type zprogram_book.

*&---------------------------------------------------------------------**& Include ZPROGRAM_FUNCTION_KEYS_S01 **&---------------------------------------------------------------------*

** First Selection ScreenSELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.PARAMETERS: book_id TYPE zprogram_book-book_id, book_nam TYPE zprogram_book-book_name, book_aut TYPE zprogram_book-book_auth, book_pub TYPE zprogram_book-book_public, book_pri TYPE zprogram_book-book_price.SELECTION-SCREEN: END OF BLOCK b1.

** Second Selection Screen.SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002.SELECTION-SCREEN : FUNCTION KEY 1, FUNCTION KEY 2, FUNCTION KEY 3, FUNCTION KEY 4, FUNCTION KEY 5.SELECTION-SCREEN: END OF BLOCK b2.

Page 122: ABAP

INITIALIZATION.

sscrfields-functxt_01 = 'Insert'. sscrfields-functxt_02 = 'Update'. sscrfields-functxt_03 = 'Modify'. sscrfields-functxt_04 = 'Delete'. sscrfields-functxt_05 = 'Display'.*&---------------------------------------------------------------------**& Include ZPROGRAM_FUNCTION_KEYS_F01 **&---------------------------------------------------------------------*

FORM table_maintence.

CASE sy-ucomm.

WHEN 'FC01'. "Insert Record wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri.

INSERT zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE ' Data Inserted in the Table' TYPE 'S'. ENDIF.

WHEN 'FC02'. "Update Record UPDATE zprogram_book SET book_name = book_nam book_auth = book_aut book_public = book_pub book_price = book_pri WHERE book_id = book_id. IF sy-subrc = 0. MESSAGE 'Data Updated in the Table' TYPE 'S'. ENDIF.

WHEN 'FC03'. "Modify Record wa-book_id = book_id. wa-book_name = book_nam. wa-book_auth = book_aut. wa-book_public = book_pub. wa-book_price = book_pri.

MODIFY zprogram_book FROM wa. IF sy-subrc = 0. MESSAGE ' Data modified in the Table' TYPE 'S'. ENDIF.

WHEN 'FC04'. "Delete Record DELETE FROM zprogram_book WHERE book_id = book_id. IF sy-subrc = 0. MESSAGE ' Data deleted from the Table' TYPE 'S'. ENDIF.

WHEN 'FC05'. "Deisplay Record CLEAR wa. SELECT SINGLE * FROM zprogram_book INTO wa

Page 123: ABAP

WHERE book_id = book_id. IF sy-subrc = 0. book_nam = wa-book_name. book_aut = wa-book_auth. book_pub = wa-book_public. book_pri = wa-book_price. ENDIF.

ENDCASE.

ENDFORM. " table_maintence

Programing for interactive ALV:

*&---------------------------------------------------------------------**& Report ZRPROGRAM_ALV_EDIT **& **&---------------------------------------------------------------------**& **& **&---------------------------------------------------------------------*

REPORT zrprogram_alv_edit .

TYPE-POOLS : slis.TABLES : vbak, vbap.

DATA : gt_vbak TYPE TABLE OF vbak, "itab gt_vbap TYPE TABLE OF vbap, "itab gs_vbak TYPE vbak, "wa gs_vbap TYPE vbap. "wa

TYPES : BEGIN OF gty_data, vbeln TYPE vbeln_va, erdat TYPE erdat, erzet TYPE erzet, ernam TYPE ernam, kunnr TYPE kunag, posnr TYPE posnr_va, matnr TYPE matnr, arktx TYPE arktx, name1 TYPE name1_gp, END OF gty_data.DATA : gt_data TYPE TABLE OF gty_data, gs_data TYPE gty_data.

***for ALVDATA : gt_fieldcat TYPE TABLE OF slis_fieldcat_alv, gs_fieldcat TYPE slis_fieldcat_alv.

SELECT-OPTIONS : s_vbeln FOR vbak-vbeln, s_werks FOR vbap-werks.

START-OF-SELECTION.

SELECT * FROM vbak INTO TABLE gt_vbak WHERE vbeln IN s_vbeln

Page 124: ABAP

AND vbtyp = 'C'. "Pick only Sale order (VBTYP=C)

IF gt_vbak[] IS NOT INITIAL. SORT gt_vbak BY vbeln.

SELECT * FROM vbap INTO TABLE gt_vbap FOR ALL ENTRIES IN gt_vbak WHERE vbeln = gt_vbak-vbeln AND werks IN s_werks.

IF gt_vbap[] IS NOT INITIAL.

SORT gt_vbap BY vbeln.

LOOP AT gt_vbap INTO gs_vbap.

READ TABLE gt_vbak INTO gs_vbak WITH KEY vbeln = gs_vbap-vbeln. IF sy-subrc = 0. gs_data-vbeln = gs_vbak-vbeln. gs_data-erdat = gs_vbak-erdat. gs_data-erzet = gs_vbak-erzet. gs_data-ernam = gs_vbak-ernam. gs_data-kunnr = gs_vbak-kunnr.

gs_data-posnr = gs_vbap-posnr. gs_data-matnr = gs_vbap-matnr. gs_data-arktx = gs_vbap-arktx.

APPEND gs_data TO gt_data. CLEAR gs_data. ENDIF.

ENDLOOP.

IF gt_data[] IS NOT INITIAL. PERFORM frm_build_fieldcatalog. PERFORM frm_display_data. ENDIF.

ENDIF.

ENDIF.*&---------------------------------------------------------------------**& Form frm_build_fieldcatalog*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*FORM frm_build_fieldcatalog .

REFRESH gt_fieldcat. gs_fieldcat-fieldname = 'VBELN'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '10'.

Page 125: ABAP

gs_fieldcat-hotspot = 'X'. gs_fieldcat-seltext_l = 'Sales Order'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'POSNR'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '10'. gs_fieldcat-seltext_l = 'Item No.'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'ERDAT'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '15'. gs_fieldcat-seltext_l = 'Creation Date'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'ERZET'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '15'. gs_fieldcat-seltext_l = 'Creation Time'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'ERNAM'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '15'. gs_fieldcat-seltext_l = 'User Name'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'KUNNR'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '15'. gs_fieldcat-seltext_l = 'Customer Code'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

gs_fieldcat-fieldname = 'NAME1'. gs_fieldcat-tabname = 'GT_DATA'. gs_fieldcat-outputlen = '35'. gs_fieldcat-seltext_l = 'Customer Name'. APPEND gs_fieldcat TO gt_fieldcat. CLEAR gs_fieldcat.

ENDFORM. " frm_build_fieldcatalog*&---------------------------------------------------------------------**& Form frm_display_data*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text

Page 126: ABAP

*----------------------------------------------------------------------*FORM frm_display_data .

DATA lv_ucommand TYPE slis_formname. lv_ucommand = 'USER_COMMAND'.

CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING i_callback_program = sy-repid i_callback_user_command = lv_ucommand it_fieldcat = gt_fieldcat[] i_default = 'X' i_save = 'A' TABLES t_outtab = gt_data[]. IF sy-subrc <> 0.* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF.

ENDFORM. " frm_display_data

*&--------------------------------------------------------------------**& Form USER_COMM*&--------------------------------------------------------------------** text*---------------------------------------------------------------------** -->LV_FIELD text*---------------------------------------------------------------------*FORM user_command USING lv_ucomm TYPE sy-ucomm lv_field TYPE slis_selfield.

. CASE lv_ucomm. WHEN '&IC1'.

IF lv_field-fieldname = 'VBELN'. SET PARAMETER ID 'AUN' FIELD lv_field-value. CALL TRANSACTION 'VA03' AND SKIP FIRST SCREEN. ELSE. MESSAGE 'Please click on Sales Order field.' TYPE 'S'. ENDIF.

ENDCASE.

ENDFORM. "USER_COMMand