05_sap abap introduction

Upload: erdk89

Post on 13-Oct-2015

217 views

Category:

Documents


14 download

DESCRIPTION

05_sap Abap Introduction

TRANSCRIPT

  • ABAP Programming LanguageSrinivasulu Nettem

    *

    ABAP Programming LanguageAdvanced Business Application Programming

    *

    ABAP EditorABAP DictionaryRepository BrowserMenu PainterScreen PainterRepository InformationSystemTest & Analysis ToolsFunction BuilderData ModelerWorkbench OrganizerABAP Workbench

    *

    Reporting

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

    *

    Non-SAPLegacySystemGeneral ProgrammingModule Pool ProgrammingBatch Input ProcessingInter-System CommunicationSequential Dataset Processing

    *

    Terms to RememberReport:An ABAP program whose output is a listModule Pool:A dialog program which is a collection of screensList:The output generated by an ABAP report programProgramA series of ABAP statements

    *

    ReportingABAPDevelopmentReporting and ABAP Development

    *

    Programming Environment - The ABAP Editor

    *

    Programming EnvironmentOnline Debugging

    *

    Basic Functions of the ABAP EditorProgram source entry areaFind andRepeat FindToggles fromdisplay to change modeUndoABAP HelpSyntax CheckStandard toolbarCut, copy and paste to and from a buffer

    *

    The PROGRAM Menu Option

    *

    The EDIT Menu Option

    *

    The GOTO Menu Option

    *

    The UTILITIES Menu Option

    *

    The BLOCK/BUFFER Menu Option

    *

    The SETTINGS Menu OptionTo set Editor mode, use the menu pathSettings-> Editor mode

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

    *

    DATA COUNT TYPE I.DATA TITLE(25).MOVE 1 TO COUNT.MOVE President TO TITLE.WRITE TITLE.WRITE COUNT.Basic ABAP Program SyntaxABAP ProgramStatement.Word 1Word 2Word 3Word 4Key wordParameter, field, or constant

    *

    Chaining Statements in ABAPDATA COUNT TYPE I.DATA TITLE(25).MOVE 1 TO COUNT.MOVE President TO TITLE.WRITE TITLE.WRITE COUNT.WRITE: TITLE, COUNT.DATA:COUNT TYPE I,TITLE(25).MOVE: 1 TO COUNT,President TO TITLE.

    *

    Comments in ABAPA double quotation mark () anywhere on a line makes everything that follows a comment.An asterisk (*) in column1 makes the entire linea comment line.

    *

    ABAP Program StructureProgram Name AreaUse REPORT for listing programsUse PROGRAM for online programsDeclaration SectionUsed for defining tables, variablesand constantsStatement SectionUsed for coding executableABAP statement

    *

    ABAP Program AttributesType:1-Executable ProgramI-Include ProgramM-Module PoolF-Function GroupS-Subroutine PoolProgram title is requiredApplication:S-BasisU-EDM (Enterprise Data Model)V-Sales and DistributionY-Customer Head OfficeZ-Customer Branch*-For all Applications

    *

    Running an ABAP ProgramFrom the ABAP Editor:With the program displayed,ProgramExecuteAn Alternative Method:From the System Menu, choose Services Reporting to launch the programOne Final Method:From the ABAP Editor: Initial Screen, type the program name, then click on the Execute push-button

    *

    The ABAP WRITE StatementWRITE ********************.SKIP 2.WRITE: The date today is:, SY-DATUM, The current time is:, SY-UZEIT.SKIP 2.WRITE ********************.

    1-----------------------------------------------------------------------------------********************

    The date today is: 12/30/1996 The current time is: 12:32:06********************Notice that there is an automatic space between the fields written to the list.

    *

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

    ***** City of Philadelphia *****

    Ticket Date 01/01/1997 Ticket Time 18:01:00-----------------------------------------------------

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

    *

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

    ***** City of Philadelphia *****

    Ticket Date 01/01/1997 Ticket Time 18:01:00------------------------------------------------------------

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

    *

    WRITE Statement Extended SyntaxWRITE ./p(I)/ = Line Feedp = Column PositionI = Output Length

    Program Field orText Literal

    Format Options

    *

    WRITE ***** City of Philadelphia *****.SKIP.WRITE: / Ticket Date, 15 SY-DATUM.WRITE: / Ticket Time, 15 SY-UZEIT.SKIP.WRITE ***** Department of Public Safety *****.NEW-PAGE.WRITE: Comments:. 1-------------------------------------------------------------------------------------- ***** City of Philadelphia *****

    Ticket Date 01/01/1997 Ticket Time 18:01:00

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

    2 ---------------------------------------------------------------------------------------Comments: NEW-PAGE Statement

    *

    Writing Icons and SymbolsINCLUDE .INCLUDE .

    WRITE: /10 ICON_DATE AS ICON, SY-DATUM, SYM_LEFT_HAND AS SYMBOL.Execute programs SHOWICON and SHOWSYMB to display the systems icons and symbols.

    *

    Maintaining Page HeadersThe title comes from the programs attributes.List header will replace title on first line of standard header.Up to four lines of column headings can be maintained for the list.

    *

    Numbered Texts (Text Symbols)Text symbols are referenced by a unique three-character code.WRITE: / TEXT-001, BIRTHDAY, / TEXT-002, SY-DATUM.

    *

    C: Character TextI: IntegerP: Packed #F: Floating Point #N: Numeric TextD: DateT: TimeX: Hexadecimal #ABAP Elementary Data Types

    *

    DATA:PLAYER(35)TYPE C,NICKNAME(35),POINTSTYPE I,GAMESTYPE IVALUE 10,AVERAGE(5)TYPE P,STARTER,ACQUIREDTYPE D.Declaring Variables

    *

    C: (blank)I: zeroP: zeroF: zeroesN: zeroesD: 00000000T: 000000X: 00The CLEAR statement sets a field back to its initial value, not its default value.Initial Values

    *

    DATA:PLAYER(35)TYPE C,NICKNAME(35) VALUE Dr. J,POINTSTYPE IVALUE 255,GAMESTYPE IVALUE 10,AVERAGE(5)TYPE PVALUE 25.5,STARTERVALUE Yes,ACQUIREDTYPE DVALUE 19760610.Assigning Default Values

    *

    DATA:PLAYER(35)TYPE CVALUE Julius Erving,NICKNAME(35),ACQUIREDTYPE D.DATA:PLAYER(35)TYPE CVALUE Julius Erving,NICKNAMELIKE PLAYER,ACQUIREDLIKE SY-DATUM.Use the LIKE addition to declare fields with the same format (i.e., data type and length) Declaring Like Fields

    *

    CONSTANTS:TEAM1(20)TYPE CVALUE 76ers,TEAM2LIKE TEAM1 VALUE Celtics,TOT_GAMESTYPE IVALUE 82.If you attempt to change the value of a constant, a syntax error will occur.The VALUE addition is required.Declaring Constants

    *

    TYPES:NAME(35)TYPE C,TEAMS(20)TYPE C.DATA:PLAYERTYPE NAMEVALUE Troy Aikman,NICKNAMELIKE PLAYER.CONSTANTS:TEAM1TYPE TEAMSVALUE Cowboys,TEAM2LIKE TEAM1 VALUE Packers.A user-defined data type created with the TYPES statement is used to specify a fields data type in the TYPE addition of the DATA or CONSTANTS statements.User-Defined Data Types

    *

    Standard LengthC=defined lengthI=12P=(2 * defined length) + 1F=22N=defined lengthD=10T=8X=(2 * defined length)JustificationC=left-justifiedI=right-justifiedP=right-justifiedF=right-justifiedN= left-justifiedD= left-justifiedT= left-justifiedX= left-justifiedOutput Characteristic for Data Types

    *

    *

    DATA:FLOAT TYPE FVALUE 98.7654321E2,PACKTYPE PVALUE 12,INTTYPE I VALUE 32.

    WRITE:/ FLOAT,/ FLOAT EXPONENT 1 DECIMALS 3,/ FLOAT EXPONENT 0 DECIMALS 2,/ PACK,/ PACK DECIMALS 1,/ INT DECIMALS 2.9.876543210000000E+03987.654E+019876.5412 12.0 32.00 These fields are not aligned because of the different standard output lengths of the numeric type fields.Output for Numeric Fields

    *

    DATA:TITLE(25),SALARY TYPE P,CNVSALARY LIKE SALARY,MOVE President TO TITLE.COMPUTE SALARY = 5000000.CNVSALARY = SALARY * 3.ADD 1000 TO SALARY.MOVE TO .[COMPUTE] = .ADD TO .SUBTRACT FROM .MULTIPLY BY .DIVIDE BY .Assigning Values to Fields

    *

    COUNTER = COUNTER + 1.SALARY = BASE * BONUS_PERCENT.LENGTH = STRLEN( NAME ).ANSWER = ( 10 + SQRT( NUM1 ) ) / ( NUM2 - 10 ). Spacing is very important when using arithmetic expressions!!!FunctionsSQRT, EXP, LOG,SIN, COS, STRLEN, . . .Operators+ - * / **DIV and MODArithmetic Expressions

    *

    90 xx 1996123456ABCD ----- 06/01/1996Use an offset and length to display or change portions of a field.Sub-Fields in ABAP

    *

    You are 12410 days old.Date fields store values as YYYYMMDD.Date Calculations in ABAP

    *

    PARAMETERS:NUM TYPE I,NAME(20) DEFAULT AARON.

    ADD 10 TO NUM.

    WRITE: / NUM, ----, NAME. 32 ---- AARONSelection ScreenDeclaring Fields with PARAMETERS

    *

    These selection texts will be used on the selection screen instead of the parameter names.Selection Texts

    *

    DATA: NUM TYPE I VALUE 12.FIELD-SYMBOLS:, TYPE I, LIKE NUM.

    ASSIGN:NUM TO ,NUM TO ,NUM TO .

    WRITE: /Line 1:, NUM, , , .

    = 32.

    WRITE: /Line 2:, NUM, , , .A field symbol is a pointer that assumes a fields address, not a fields value.Line 1: 12121212Line 2: 32323232Working with Field Symbols in ABAP

    *

    Dynamic Assignment of Partial Strings

    *

    PARAMETERS FIELD(8) DEFAULT SY-UZEIT.FIELD-SYMBOLS .

    ASSIGN (FIELD) TO .

    IF SY-SUBRC = 0.WRITE: / The contents of field, FIELD, .ELSE.WRITE: / Failure assigning field, FIELD, to field symbol.ENDIF. The contents of field SY-UZEIT 12:32:06Selection ScreenListDynamic Field Assignment

    *

    Retrieving Information From the DatabaseDataJohn SmithMary Stiles

    *

    Open SQLPortable across various databasesOpen SQL - a subset of standard SQL

    *

    The Basic SELECT StatementDBMary StilesJohn SmithWork AreaSELECT *FROM [..]ENDSELECT.

    *

    Example Using the SELECT Statement

    TABLES: KNA1.

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

    *

    The SELECT Statement with a WHERE Clause

    TABLES: KNA1.

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

    *

    SY-SUBRCTABLES: KNA1.

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

    IF SY-SUBRC 0.WRITE: / No records found..ENDIF.

    *

    The INTO ClauseTABLES: KNA1.

    SELECT KUNNR NAME1FROM KNA1INTO (KNA1-KUNNR, KNA1-NAME1).WRITE : / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.

    IF SY-SUBRC 0.WRITE: / No records found..ENDIF.

    *

    INTO CORRESPONDING-FIELDSTABLES: KNA1.

    SELECT KUNNR NAME1FROM KNA1INTO CORRESPONDING-FIELDS OF KNA1.WRITE : / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.

    IF SY-SUBRC 0.WRITE: / No records found..ENDIF.

    *

    Basic Flow Control in ABAP

    *

    The IF StatementIF X =5. WRITE :/ The value of X is 5.ELSEIF X =6. WRITE :/ The value of X is 6.ELSE . WRITE :/ X is neither 5 nor 6.ENDIF.

    *

    Logical Expressions

    Logical Expressions use :

    RELATIONAL OPERATORSLOGICAL OPERATORSSTRING COMPARISON OPERATORS

    *

    Relational Operators

    *

    Logical Operators

    The hierarchy of the logical operators is:NOT, AND and then OR.(ie different from creating views)

    *

    Good Programming Practice withLogical OperatorsIf not ( X = 0 )or not ( Y = 1 andZ = X or X = 3and ( Z = 5 )Bad

    *

    String Comparison OperatorsComparisonSyntaxContains onlyContains anyContains stringContains patternContains not onlyContains not anyContains no stringContains no patternCOCACSCPCNNANSNP

    *

    The CASE Statement

    *

    The DO Loop

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

    *

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

    *

    Nested Loops and Control StructuresDO 2 TIMES. WRITE :/ SY-INDEX. DO 3 TIMES. WRITE : / , SY-INDEX. ENDDO.ENDDO.

    *

    The ON CHANGE OF StatementSELECT * FROM YCUSTOMER. ON CHANGE OF YCUSTOMER-COUNTRY OR YCUSTOMER-STATE. [.] ENDON.ENDSELECT.

    *

    The CHECK StatementDO 10 TIMES. CHECK SY-INDEX 4. CONTINUE . ENDIF. WRITE :/ SY-INDEX.ENDDO.

    *

    Address ListStructureData StructuresAddress ListInternal Table

    *

    Declaring a Structure - Method #1 1REPORT YN1C0008. 2 3TABLES: TABNA. 4DATA:BEGIN OF ADDRESS, 5FLAGTYPE C, 6IDLIKE TABNA-ID, 7NAME1LIKE TABNA-NAME1, 8CITYLIKE TABNA-CITY, 9END OF ADDRESS.10MOVEXTO ADDRESS-FLAG.11MOVE0001TO ADDRESS-ID.12MOVESmithTO ADDRESS-NAME1.13MOVEPhiladelphia TO ADDRESS-CITY.1415WRITE ADDRESS.1617181920212223Basic Syntax:DATA: BEGIN OF . . . . . . . . . END OF . FlagID Name1 CityAddress StructureIs this statement necessary for the code?

    *

    REPORT Yxxxxxxx.TYPES: BEGIN OF ADDR,FLAG,IDLIKE EMPLOYEE-ID,NAME1LIKE EMPLOYEE-NAME1,CITYLIKE EMPLOYEE-CITY, END OF ADDR.DATA: ADDRESS TYPE ADDR.

    MOVE: X TO ADDRESS-FLAG,00001 TO ADDRESS-ID,Smith TO ADDRESS-NAME1,Philadelphia TO ADDRESS-CITY.

    WRITE ADDRESS.Declaring a Structure - Method #2Basic Syntax:TYPES: BEGIN OF , . . . , . . . , . . . , END OF .DATA: TYPE .

    *

    Populating a Structure withField-by-Field TransportREPORT Y170DM37.TABLES: EMPLOYEE.DATA: BEGIN OF ADDRESS,FLAG,IDLIKE EMPLOYEE-ID,NAMELIKE EMPLOYEE-NAME1,CITYLIKE EMPLOYEE-CITY, END OF ADDRESS.

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

    AddressID Name1 City000000001 Electronics Inc. Waldorf MOVE-CORRESPONDING EMPLOYEE TO ADDRESS.Flag ID Name City000000001 WaldorfClear .

    *

    Internal Table TypesStandardSortedHashed

    *

    REPORT Y170DM38.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,IDLIKE EMPLOYEE-ID,NAME1LIKE EMPLOYEE-NAME1,COUNTRYLIKE EMPLOYEE-COUNTRY, END OF EMP.

    DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.The TYPES statement defines the structure and data type for the internal table.The DATA statement with an INITIAL SIZE creates the actual internal table capable of storing data. Because of the WITH HEADER LINE addition, this internal table is created with a header line.Header Line ID NAME1 COUNTRYCreating an Internal Table with Header Line

    *

    Internal Table KeysImplicit KeyAll character fieldsExplicit KeyUser-definede.g. WITH [ UNIQUE/NON-UNIQUE ] KEY FIELD1 FIELD2 ...

    *

    Size of an Internal Table

    *

    APPEND SORTED BY .APPEND .Department Salary

    123456Department SalaryHeaderLoading an Internal Table with a Header LineR&D400,000PROD 7,800,000MKTG 1,000,000SALES 500,000HR 140,000IT 50,000R&D400,000MKTG 1,000,000SALES 500,000PROD 7,800,000IT 50,000HR 140,000

    *

    REPORT Y170DM42.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRYLIKE EMPLOYEE-COUNTRY,IDLIKE EMPLOYEE-ID,SALARYLIKE EMPLOYEE-SALARY, END OF EMP.DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB SORTED BY SALARY.ENDSELECT.Loading an Internal Table with a Header LineMore than ten entries can be saved in the internal table.A maximum of ten entries can be saved in the internal table. Any entries that exceed the top ten will be deleted.With both versions of the APPEND statement, memory space for ten records is allocated when the first record is written to the internal table.Example 1Example 2OR

    *

    Internal Table with Header Line COUNTRY ID FORMA NAME1 SORTL . . . ID NAME1COUNTRYHeader LineAB

    *

    Internal Table with Header Line ID NAME1 COUNTRYUSA00000001CompanyBaker DistributorsBAKER. . . COUNTRY ID FORMA NAME1 SORTL . . .Header Line1

    *

    Internal Table with Header Line

    *

    Internal Table with Header Line USA 00000001 Company Baker Distributors BAKER . . . ID NAME1 COUNTRY00000001Baker DistributorsUSA00000001Baker DistributorsUSA COUNTRY ID FORMA NAME1 SORTL . . .Header Line...This header line is attached to the body of the internal table.

    *

    Internal Table with Header Line ID NAME1 COUNTRY00000001 Baker Distributors USA00000002 Diversified Indust...USA00000002 Diversified Indust... USAUSA 00000002 Company Diversified Indust.. DIVERS . . .EMPLOYEE COUNTRY ID FORMA NAME1 SORTL . . .Header Line...

    *

    Creating an Internal Table without a Header LineREPORT Y170DM40.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,IDLIKE EMPLOYEE-ID,NAME1LIKE EMPLOYEE-NAME1,COUNTRYLIKE EMPLOYEE-COUNTRY, END OF EMP.

    DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10, EMPTAB_WA TYPE EMP.

    SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB_WA. APPEND EMPTAB_WA TO EMPTAB.ENDSELECT.APPEND to .The TYPES statement defines the structure and data type for the internal table and its work areaWork AreaThe DATA statement with an INITIAL SIZE creates the actual internal table without a header line. The DATA statement without the INITIAL SIZE creates the work area for the internal table.

    *

    Separate Internal Table Work AreaPerformance IssuesNested Internal TablesInternal Table without a Header Line WHY???

    *

    Internal Table without a Header Line COUNTRY ID FORMA NAME1 SORTL . . .Work Area ID NAME1 COUNTRY

    *

    Internal Table without a Header Line ID NAME1 COUNTRY ID NAME1COUNTRY 00000001 Baker Distributors USA00000001 Baker Distributors USA USA 00000001 Company Baker Distributors BAKER . . . COUNTRY ID FORMA NAME1 SORT . . .Work AreaThis work area is not attached to the body of the internal table.

    *

    Transferring ABAP Dictionary Table StructuresREPORT Y170DM41.TABLES: EMPLOYEE.DATA: EMPTAB LIKE STANDARD TABLE OF EMPLOYEE INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE. MOVE EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.The internal table EMPTAB will have the exact same structure as the dictionary table EMPLOYEE.

    *

    Automatic Field ConversionMOVE-CORRESPONDING or MOVE field to fieldIndividual field type conversionMOVEStructure to structureField to structureStructure to fieldIntermediate C type Followed by adoption of new types

    *

    Mass Reading from Database Tables into Internal TablesREPORT Y170DM69.

    TABLES: EMPLOYEE.

    DATA: EMPTAB LIKE STANDARD TABLE EMPLOYEE INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE INTO TABLE EMPTAB WHERE COUNTRY = USA.SELECT * FROM . . .1. INTO TABLE .2. APPENDING TABLE .Notice no ENDSELECT is needed here because no loop processing occurs.

    *

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

    *

    System Field SY-TABIXREPORT Y170DM46.TABLES: EMPLOYEE.

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

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

    *

    Accumulating Data within an Internal TableREPORT Y170DM43.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRYLIKE EMPLOYEE-COUNTRY,SALESLIKE EMPLOYEE-SALES, END OF EMP.DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. COLLECT EMPTAB.ENDSELECT.LOOP AT EMPTAB. WRITE: / EMPTAB-COUNTRY, EMPTAB-SALES.ENDLOOP.COLLECT .CountrySalesD400,000USA1,000,000GB500,000D7,800,000Header LineA371,065.00CH 45,305.00D8,200,000.00F0.00GB500,000.00NL577,000.00NO234.00USA1,000,000.00HK0.00screen output

    *

    Sorting an Internal TableREPORT Y170DM44.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRYLIKE EMPLOYEE-COUNTRY,NAME1LIKE EMPLOYEE-NAME1,SALESLIKE EMPLOYEE-SALES, END OF EMP.DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.SORT EMPTAB BY SALES DESCENDING.LOOP AT EMPTAB. WRITE: / ITAB-COUNTRY, ITAB-NAME1, ITAB-SALES.ENDLOOP.Sorting options:1)SORT - sorts the entries of the internal table in ascending order.2) SORT BY - sorts the table on one or more fields within the table.screen output

    *

    Control Level ProcessingAT FIRSTAT NEW < field >AT END < field >AT LAST

    *

    REPORT Y170DM47.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP, COUNTRY LIKE EMPLOYEE-COUNTRY, NAME1 LIKE EMPLOYEE-NAME1, END OF EMPTAB.

    DATA:EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.

    SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.

    READ TABLE .Reading a Single Table Entry

    *

    Reading a Single Table Entry - OptionsREAD TABLE options:1)READ TABLE .2) READ TABLE WITH KEY = = .3) READ TABLE WITH TABLE KEY = ... = .4) READ TABLE WITH KEY = .5) READ TABLE WITH KEY . . . BINARY SEARCH.6) READ TABLE INDEX .7) READ TABLE COMPARING . . . .8) READ TABLE COMPARING ALL FIELDS.9) READ TABLE TRANSPORTING . . . .10) READ TABLE TRANSPORTING NO FIELDS.

    *

    Maintaining Internal TablesSELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.

    READ TABLE EMPTAB INDEX 1.MOVE ABC TO EMPTAB-NAME1.MODIFY EMPTAB INDEX SY-TABIX.IF SY-SUBRC NE 0.WRITE / Attempt to modify failed..ELSE.WRITE: / EMPTAB-COUNTRY, EMPTAB-NAME1.ENDIF.INSERT EMPTAB INDEX 1.DELETE EMPTAB INDEX SY-TABIX.INSERT INDEX .MODIFY INDEX .DELETE INDEX .Check SY-SUBRC after every attempt to change an internal table entry.

    *

    Working with an Internal Tablewithout a Header LineAPPEND TO .COLLECT INTO .INSERT INTO .MODIFY FROM .READ TABLE INTO .LOOP AT INTO .

    *

    Deleting an Internal TableCLEAR Initialises the header line.

    Internal table lines remain unchanged.

    REFRESH Deletes all table lines.Storage space is not released.Paging is released.Header line remains unchanged.FREE Deletes all table lines.Storage space is released.Header line remains unchanged.

    *

    Information about an Internal TableREPORT Y170DM49.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRYLIKE EMPLOYEE-COUNTRY,NAME1LIKE EMPLOYEE-NAME1,END OF EMP,DATA:EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE,LINE_COUNT TYPE I,INITIAL_COUNT TYPE I.SELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.DESCRIBE TABLE EMPTABLINES LINE_COUNTOCCURS INITIAL_COUNT.WRITE: / lines:, LINE_COUNT, / occurs:, INITIAL SIZE_COUNT.DESCRIBE TABLE LINES OCCURS .screen output

    *

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

    *

    What Are Subroutines

    *

    ModularizationREPORT YDEMOSB2.

    Perform sub(YDEMOSB1)REPORT YDEMOSB3.

    Call Function ZZCALCExternal CallFunctionModuleCall

    *

    991a1a2a3Call Calculate_tax Transfer values of fields a1 a2 Get value of field a3Actual parameters a1 a2 a3Formal parametersf1 f2f3Subroutine calculate_tax99 1f1f2f3f3 = f1 +f2 . . . .Actual / Formal ParametersParameter transferMain ProgramSubroutine

    *

    a1f1Pass by Value and ResultPass by Valuea1f1Pass by Referencea1f1Methods of Passing Parameters

    *

    REPORT Y170D091. TABLES: .... DATA: .. . .PERFORM USING .. . .FORM USING VALUE() VALUE() .

    ENDFORM.Declaring and Calling a Subroutine - Pass by Value(1) & Reference(2)

    Pass by reference Pass by value

    *

    Pass by valueDeclaring and Calling a Subroutine - Pass by Value and Result(3)REPORT YSDEM000. TABLES: ... . DATA: ... .. . .PERFORM USING CHANGING.. . .FORM USING VALUE() VALUE() CHANGING VALUE()....f 3 =A....ENDFORM.Pass by value and result

    *

    Global versus Local DataGlobal DataLocal Data

    *

    Local Data in Subroutines

    *

    REPORT Y170D095.TABLES: TABNA.DATA: ZTAB LIKE TABNA.DATA: FLAG...PERFORM SUB1 USING TABNA.PERFORM SUB1 USING ZTAB....Passing Structures as ParametersFORM SUB1 USINGREC STRUCTURE TABNA.WRITE: /REC-COUNTRY,REC-NAME1.

    ENDFORM.This is passing the TABNA work area onlyThis is passing the ZTAB structure

    *

    Passing Internal Tables as Parameters

    *

    External SubroutinesREPORT Y170D096.TABLES : TABNA,T001, T005....START-OF-SELECTION....PERFORMSUB1(Y170D097) . . . ....REPORT Y170D097.TABLES : TABNA,T001, T001G....START-OF-SELECTION...FORM SUB1 . . . ....NEW-PAGE....ENDFORMPERFORM () USING . . .Roll Area

    Storage AllocationTABNAT001T005T001GY170D108Y170D109

    *

    Function ModulesFunction BuilderProgram 1

    CALL FUNCTIONFM_0. . .Program 3

    CALL FUNCTIONFM_02. . .Program 2

    CALL FUNCTIONFM_02. . .

    *

    Function Module PartsFM_01 ...FM_02 ...FM Group : FIBUFM_03 ...FM_04 ...FM Group : XYZ Section I Administration

    Section II InterfaceChapter 1 ImportChapter 2 ChangingChapter 3 ExportChapter 4 TablesChapter 5 Exceptions

    Section III Documentation

    Section IV Source Code

    Section V Global Data

    Section VI Main ProgramFM -02

    *

    Creating a Function Group

    *

    Administration

    *

    InterfacesProgram XYZ.

    Call functionY_DEMO_FUNCFunction ModuleY_DEMO_FUNCImportChangingExportTablesExceptions

    *

    Import/Export Parameter InterfaceParameter nameLIKETYPEDefault valueFlag parameter as optionalPass parameterby reference

    *

    Parameter nameLIKETYPEFlag parameter as optionalTable Parameters/Exceptions Interface & Documentation

    *

    Function Module Source Code

    *

    . . . IF... RAISE INVALID_OPERATOR. * MESSAGE. . . RAISING INVALID_OPERATOR. ENDIF.. . . Function ModuleExceptions

    *

    Example - Raising Exceptions

    *

    Calling a Function Module

    *

    Calling a Function Module (Continued)

    *

    Program OrganisationFUNCTION FA.LU01FUNCTION FB.LU02FUNCTION-POOL Message-ID ZZ. DATA: Global DATALTOPLUXX INCLUDE L U01. INCLUDE L U02....*System-defined include files

    *User-defined include filesINCLUDE LTOP. INCLUDE LUXXSAPL

    *

    Subroutine Includes for Function Groups

    *

    FORM SUB1 USING... DATA: . . . MOVE. . . TO X. ENDFORM.

    SubroutinesL F01Global Data / Local Memory in the Function GroupFUNCTION . . . DATA: . . . MOVE X TO . . .ENDFUNCTION.

    ProgramGlobal Data

    FUNCTION-POOL . DATA: X TABLES: . . .L TOP

    *

    Test Environment

    *

    Managing Function ModulesAdministration

    *

    Remote Function Call (RFC)External programExternal Program. . . RfcOpen (. . .) RfcCallReceive (. . .) RfcClose (. . .)ProgramCALL FUNCTION. . . DESTINATION. . . EXPORTING. . . IMPORTING. . . TABLES. . . EXCEPTIONS. . .Function GroupFUNCTION-POOL . . . .Function ModuleFUNCTION REMOTE_CALL . . . RAISE ERROR. . . . ENDFUNCTION.ABAP\/4RFCLid

    *

    Displaying Function Module

    *

    Modularization:The Include Technique

    *

    REPORT: ZRACER01.TABLES: LFA1, LFB1, LFC3.GET LFA1.GET LFB1.GET LFB3.Database Access IAuthorisation CheckingLogical DatabaseABAP Native SQLABAP Open SQLNo Authorisation CheckingPhysicalDatabase

    *

    SQL (SELECT)ABAP ProgramsREPORT: YNEWAPPL.TABLES...

    SELECT * FROM TABNA.

    ENDSELECT.DataDatabaseTABNALFA1LFC1

    *

    WHERE Clause: Single Access

    *

    Syntax: Restricted Loop ProcessingSELECT * FROM WHERE AND OR AND :: OR .ENDSELECT.EQ=GE>==>LELT 25. WRITE:/ carrid, connid, count, sum_weight. ENDSELECT.

    *

    Using ABAP Native SQLEXEC SQL.ENDEXEC.In this example, the programcreates a table in the Oracledatabase, which is not knownto the ABAP Dictionary.The newly created databasetable is populated using anSQL INSERT statement.

    *

    SELECT Using ABAP Native SQL

    *

    ABAP Native SQL and the PERFORMING OptionThe PERFORMING option creates a looping structure that for every row retrieved, the subroutine is called.

    *

    Authority Objects in SAP

    *

    The AUTHORITY-CHECK Statement

    AUTHORITY-CHECK OBJECT S_DEVELOP ID DEVCLASS FIELD YLJS ID OBJTYPE DUMMY ID OBJNAME DUMMY ID P_GROUP DUMMY ID ACTVT DUMMY.

    The option DUMMYsuppresses the check forthe specified field. The neteffect is that the user canperform any activity on development class YLJS.The AUTHORITY-CHECKlists the fields to be checked and verifies what the user is attempting to do against what the user is authorised to do.

    *

    Reacting to the AUTHORITY-CHECK Statement

    AUTHORITY-CHECK OBJECT S_DEVELOP ID DEVCLASS FIELD YLJS ID OBJTYPE DUMMY ID OBJNAME DUMMY ID P_GROUP DUMMY ID ACTVT DUMMY.IF SY-SUBRC 0. WRITE: / You are not authorised to development, class YLJS.. EXIT.ENDIF.

    *

    The EXPORT StatementEXPORT KNA1-KUNNR KNA1-BUKRS TO MEMORY.EXPORT SY-SUBRC TO MEMORY ID LJS1.

    *

    The IMPORT StatementIMPORT FROM MEMORY.

    *

    Catching Runtime ErrorsCATCH SYSTEM-EXCEPTIONS ARITHMETIC_ERRORS = 5CONVERSION_ERRORS = 6.[..]ENDCATCH.

    *

    Completing the CATCH CodeDATA: int type I, char(3) type C value ABC.[..]

    CATCH SYSTEM-EXCEPTIONS CONVERSION_ERRORS = 1. [..] MOVE char TO int.MOVE keyword to trigger CATCH [..]ENDCATCH.

    IF SY-SUBRC = 1. WRITE: / Conversion error has occurred.ENDIF.

    *

    Data Classes in SAP

    *

    Relationships Among Master Data and Transaction DataKNA1:

    KNB1:KNC1:

    *

    Accessing Master Data and Transaction DataVia ViewsVia Nested SELECT LoopsVia Logical Database Programs

    *

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

    *

    Logical Database ProgramsSELECTSELECTSELECTENDSELECTENDSELECTENDSELECTSecurityChecksLogical Database Program

    *

    Event-Driven ProgrammingSTART-OF-SELECTION.GET .GET LATE.END-OF-SELECTION.

    *

    Attaching Code to an EventEvent

    *

    The START-OF-SELECTION Event

    *

    The GET Event

    *

    The Structure of a Logical Database Program

    *

    The GET LATE Event

    *

    Behaviour of a Logical Database ProgramLogical Database Program

    *

    Selection Screens with Logical Database Programs

    *

    The END-OF-SELECTION Event

    *

    Selection Screens

    *

    SELECT-OPTIONS FOR [DEFAULT [TO ]]The SELECT-OPTIONS Statement

    *

    Selection Tables

    *

    Multi-Row Selection TablesTo get HereClick Here

    *

    Creating User-Friendly Selection TextsSelection ScreenMaintain Text Elements

    *

    The CHECK StatementSELECT-OPTIONS S1 FOR SY-INDEX.DO 10 TIMES.CHECK S1.WRITE: / SY-INDEX.ENDDO.Using CHECK with SELECT-OPTIONS12346910Selection TableContents:IBT110EEQ5EBT78

    *

    The REJECT StatementTABLES: KNA1, BSID.GET KNA1.WRITE: / KNA1-KUNNR, KNA1-NAME1.COUNTER = 0.GET BSID.ADD 1 TO COUNTER.IF COUNTER > 3. REJECT KNA1.ENDIF.WRITE: / BSID-BUDAT, BSID-DMBTR.GET KNA1 LATE.ULINE.The REJECT statement immediatelymoves to the specified record(in this case KNA1).

    *

    Declaring Fields with PARAMETERS

    *

    Creating Parameters as CheckboxesPARAMETERS: INCL_INV AS CHECKBOX DEFAULT X.TABLES: KNA1.SELECT *FROM KNA1.WRITE: / KNA1-KUNNR, KNA1-NAME1.IF INCL_INV = X. PERFORM GET_AND_WRITE_INV.ENDIF.ENDSELECT.

    *

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

    *

    Attaching Matchcodes to ParametersPARAMETERS: CUSTNO LIKE KNA1-KUNNRMATCHCODE OBJECT DEBI.

    *

    Formatting the Selection Screen

    *

    Additional Selection Screens

    SELECTION-SCREEN BEGIN OF SCREEN 1200. SELECT-OPTIONS S_CUSTOMER_NUM FOR KNA1-KUNNR.SELECTION-SCREEN END OF SCREEN 1200.

    [.]

    CALL SELECTION-SCREEN 1200.SELECT * FROM KNA1 WHERE KUNNR IN S_CUSTOMER_NUM.

    *

    Creating Pushbuttons on theApplication Toolbar

    *

    The Screen Fields Table:SSCRFIELDSNameKey TypeLength/decDescriptionSSCRFIELDS-UCOMMCHAR C70Interact.: Command fieldSSCRFIELDS-FROM_TEXTCHAR C12Text (length 12)SSCRFIELDS-TO_TEXTCHAR C12Text (length 12)SSCRFIELDS-FUNCTXT_01CHAR C20Selection screen: Text foSSCRFIELDS-FUNCTXT_02CHAR C20Selection screen: Text foSSCRFIELDS-FUNCTXT_03CHAR C20Selection screen: Text foSSCRFIELDS-FUNCTXT_04CHAR C20Selection screen: Text foSSCRFIELDS-FUNCTXT_05CHAR C20Selection screen: Text fo

    *

    Creating Pushbuttons on the Selection Screen

    *

    User Message

    *

    Error Message at the Selection ScreenAT SELECTION-SCREEN. AUTHORITY-CHECK OBJECT F_KNA1_BUKID ACTVT DUMMYID BUKRS FIELD BUKRS.IF SY-SUBRC 0.MESSAGE E000 WITH BUKRS.ENDIF.Using the AT SELECTION-SCREEN event, access to the output can be prevented until valid data is entered on the selection screenThe selection screen is continuously redisplayed until valid data is entered or the program is terminated

    *

    Table T100: Messages

    *

    Table T100: MessagesREPORT MESSAGE-ID .MESSAGE [WITH ].Example MESSAGE E001 WITH KNA1-KUNNR KNA1-BUKRS.Message TypesAAbendEErrorIInformationSSuccessWWarning

    *

    Creating Message IDs and MessagesREPORT Z1_KB MESSAGE-ID zkb.3. After maintaining the message class and clicking on the MESSAGE tab, the Maintain Message screen appears.1. Double-click on the newly entered Message ID.2. After being prompted to create the message class, the Maintain Message Class screen appears.

    *

    ExtractsGeneral InfoDetailDetailDetailDetailGeneral InfoDetailDetail

    *

    Header FieldsHeader +General InfoHeader +DetailHeader +DetailHeader +DetailHeader +DetailHeader +DetailHeader +General InfoHeader +DetailHeader +Detail

    *

    Field-Groups

    FIELD-GROUP: header, detail

    *

    Sales Document InformationDoc No Create date Creator1001 . ...1002 . ...1003 . ...Doc No Item No Mat No1001 10 Mat11001 20 Mat21001 30 Mat3

    VBAK - Sales Document: HeaderVBAP - Sales Document: Item1002 10 Mat21002 20 .1003 10 .. . .

    *

    INSERT statementINSERT: vbak-vbelnINTO header.INSERT:vbak-kunnrvbak-erdatINTO general.INSERT: vbap-posnrvbap-matnrINTO detail.

    *

    EXTRACT statementSELECT * FROM vbak.EXTRACT header.EXTRACT general.SELECT * FROM vbap WHERE vbeln = vbak-vbeln.EXTRACT detail.ENDSELECT.ENDSELECT.Header GeneralHeader DetailHeader DetailHeader DetailHeader DetailHeader General

    *

    Sorting and Looping at an Extract

    SORT.

    LOOP.

    ..

    ENDLOOP.

    *

    Extract vs Internal TablesEXTRACTINTERNAL TABLEAgainst:For:- Only one extract- Many internal tables- Few operations (SORT)- Many operations (Modify etc)

    For:Against:- Different records stored - Only one type of record- Use of SUM optimized- SUM hogs processor

    *

    Extracts - SummaryAn alternative to Internal TablesOnly one extract per programSome advantages, but not recommend More complex uses than seen in this chapter

    *

    The Online Debugging Tool

    *

    The Online Debugging DisplaySource CodeThe program and the event the debugger is processing.Execution controlbuttons.Click to display current statement.

    *

    Online Debugging Display ModesUse these buttonsto page through the codeOnline debuggingnavigation buttons

    *

    Displaying Field Contents Area for watch variables. These are user chosen variables that can be monitored as they change value during execution.Buttons for hexadecimal display

    *

    Contents of internal tableDisplaying the Contents of an Internal Table

    *

    The change buttonReplacing Field Values at Runtime

    *

    Changing Internal Tables at RuntimeInitial Values of an Internal TableDebuggerNew Values of an Internal Table

    *

    The Delete ButtonDeleting a Row from an Internal Table

    *

    Editing a Row of an Internal TableThe Change button

    *

    Adding a Row to an Internal TableThe Insert and Append Buttons

    *

    Debugging Strategies

    *

    Using Breakpoints

    *

    CASE WORLD_SERIES.

    WHEN COLORADO_ROCKIES.WRITE WORLDS GREATEST TEAM.WHEN OTHERS.WRITE MAYBE NEXT YEAR.BREAK-POINT.

    ENDCASE.Setting Static BreakpointsSetting a static breakpoint

    *

    Setting Dynamic BreakpointsDouble click here to add break pointUse menu path to add break point

    *

    Displaying Dynamic BreakpointsDouble click on the Stop icon to delete a break-point

    *

    Setting Breakpoints at Keywords or EventsMenu path to create / change / delete a break-point

    *

    Setting WatchpointsCreate watchpoint screenLogical Operators to compare watch point variables valueCreate watchpointbuttons

    *

    Watch points overview screenLogical Operators between watch pointsWatch point change/deleteButton to display watch point overview screen

    *

    Deleting and Deactivating Breakpoints

    *

    Deleting and Deactivating Dynamic Breakpoints

    *

    Debugging Without Breakpoints

    *

    Switching to the ABAP Editor from within the Debugger

    *

    Releasing the Database During Debugging

    *

    *ABAP is a programming language created and used by SAP for the development of application programs, including:ReportsScreensInterfacesData conversionsAll of R/3s applications and even parts of its basis system were developed in ABAP.ABAP is an event-driven programming language. User actions and system events control the execution of an application.

    ABAP used to be called ABAP/4 in release 3.x. The 4 stood for fourth generation language.*The ABAP Workbench is used by SAP for the development of standard and custom application software. The ABAP Workbench is also used to create dictionary objects. It consists of the following components:ABAP Editor is used to maintain programs.ABAP Dictionary is used to maintain Dictionary objects.Repository Browser is used to display a hierarchical structure of the components in a development class.Menu Painter is used to develop graphical user interfaces, including menubars and toolbars.Screen Painter is used to maintain screen components for an online program.Repository Information System contains information about development and runtime objects, such as data models, dictionary types and table structures, programs, and functions.Test and Analysis Tools, such as the Syntax Check and the Debugger.Function Builder, which allows you to creat and maintain function groups and function modules.Data Modeler, a tool which supports graphical modeling.Workbench Organizer, which maintains multiple development projects and manages their distribution.

    The ABAP Workbench used to be known as the ABAP/4 Development Workbench.

    *Report programs produce lists and can be divided into conventional reports and interactive reports.Conventional reports do not allow interaction by the user; therefore, the basic list contains extensive information that the user must often sort through to find the relevant data.Interactive reports allow interaction by the user; therefore, the user can produce secondary, detailed lists off of the basic list by choosing the relevant data and requesting more information.*Module pool programming (or online programming) involves the creation of a module pool (a collection of ABAP modules) and one or more screens. The modules are called by the screen processor during program execution.Batch input processing is used to ensure the safe transfer of data into the SAP system. This process is an automatic, protected data transfer to the SAP system which uses SAP transactions to validate data as it populates the SAP database. ABAP contains statements which conform to CPI-C standards (Common Program Interface - Communications). These are used for programming communications programs.ABAP can read and write sequential data sets.*Above is a list of common ABAP program terms.*The ABAP Editor is used to create, maintain, and execute ABAP programs. Some methods for executing ABAP programs include:The ABAP Editor :Tools ABAP Workbench ABAP Editor (pushbutton) The Reporting function:System Services ReportingABAP programs that you create must start with a Y or a Z and can be up to 30 characters in length.

    Program names were limited to 8 characters in the 3.x release.*The editor combines a character based text entry capability with graphical icons and menu options to perform many of the functions necessary to build complex ABAP applications.Move to a specific line by double-clicking on the line number. *The ABAP development environment provides a wide variety of tools required by the programmer for the development and testing of applications.Pictured above is the online debugging tool which enables the programmer to watch the program execute line by line.The online debugging tool provides the programmer with the capability to designate watch variables. These variables, once chosen, can be viewed as their values change from statement to statement while the program executes. The programmer can even change their values to simulate different processing scenarios.*The ABAP program editor provides many functions through the use of graphical push-buttons. Among these functions are:Toggle from display mode to edit modeCut, copy and pasteUndoFind and repeat findSyntax check - with limited auto correctionABAP help*Some of the functions under the PROGRAM Menu include:Other Program Enables the programmer to immediately load another program without going back to the ABAP Editor: Initial Screen.Save As Saves the contents of the editor under another name. Be careful, it is possible to overwrite another program.Pretty PrinterThis option formats the contents of the editor in terms of indentation and spacing. Helps with the readability of the program.

    Performance Tips:The Extended Syntax Check (menu path Program/Check/Extended prog. check) will identify dead code (code which, due to modifications, may no longer be called in program) and other inefficient code.

    *The more important functions under the EDIT menu include:Insert StatementThis option brings up a dialog box in which the user can choose a statement structure to insert. Once chosen, the editor will insert a statement format at the location of the cursor with all of the options and requirements set. The programmer has only to fill in the blanks. Note: If the statement structure required is not listed, use the drop down box in the Other pattern option, where many more ABAP keywords are listed (eg IF, SELECT, CASE, WINDOW) as well as comment box templates. Use the menu path Utilities More utilities Edit pattern to set user defined statement structuresEdit LineThis option brings up a second submenu which gives the programmer a list of line commands. These include:Delete line (deletes the line the cursor is on).Split line (places all information to the right of the cursor on the line directly below the line the cursor is on).Insert line (inserts a line above the line the cursor is on).Others *The GOTO menu gives the programmer the ability to immediately navigate to any one of the following functions:Attributes (displays the particular attributes of that program).Text elements (an editor for titles and headers, selection texts and text symbols used for formatting reports).Variants (an editor for the creation, change or display of variants).Messages (an editor for message classes).All of these options will be covered in later chapters.*Under the UTILITIES menu the programmer can access the following utilities:Data Browser Where the contents of tables can be displayedHelpThis function is a repeat of the light blue i push-buttonBreakpoints The programmer can set or remove break-points that are used by the online debugging tool (the red stop pushbutton also provides this function)Program upload and download utilitiesAllows the programmer to transfer ABAP code to/from a local fileEdit LocallyAllows the programmer to edit the program in NotePad when not online. See Settings menu to choose path.Edit PatternSets regularly used user defined patterns for inserting using menu path Edit Insert Statement Others.*Using the BLOCK/BUFFER menu, the programmer can:Copy program code to any one of three (X, Y, Z) separately maintained clipboards (buffers). Program code can then be inserted into another program from these clipboards (buffers).To copy code to the windows clipboard, select the Copy to clipboard menu option.Comments can be inserted or removed from the code using the Insert Comment * and Delete Comment * menu options.*Using the Setting->Command Mode menu path, the user can:Select the mode in which to display the program in the ABAP EditorPC mode (point and click) with line numbering (preferred)PC mode without line numberingCommand mode - This mode is the same as version 2.2Compress logical expressions to make the code visible in the ABAP editor more readable.This option is available if with compression logic is selected. Code is compressed using the pushbuttons that automatically appear when the ABAP Editor is in this mode.Ex. Code will be easier to read if long IF statements are compressed so that only the IF and ENDIF can be seen.Use:to compress, and to uncompress.

    Choose the case in which the code is displayed from either:Lower caseUpper caseKey word large (only ABAP key words are in upper case)Set the path for local editing in Notepad To go to local editing use Utilities More Utilities Edit Locally*An ABAP program is comprised of a series of individual ABAP statementsEach statement must end with a period. (full-stop)Key words are always the first word in a statement.Words must be separated by at least one blank.ABAP statements can be indented and extend over several lines.

    *To avoid repeating key words, ABAP allows you to chain statements together if these statements begin with the same key word.The key word is followed by a colon.Each chained statement component is separated by a comma.Blanks can be inserted before and after the separators (which may be colons, commas, or periods).

    * Comments are inserted into the program in two ways:By placing an asterisk (*) in column 1, the complete line is designated as a comment line.By placing a double quotation mark (") within a line, the remainder of the line is considered a comment.

    Coding Recommendations:A specialised comment *EJECT (* in first column, no space between * and EJECT) can be used when printing out code. Code listed after the *EJECT will print on a new page without affecting the processing in the code itself.If you are modifying code you should comment out any unused code rather than delete it. You should also comment as to who is making the modifications, why they are being made, and when the changes were made.*ABAP programs must start with either the PROGRAM or REPORT statement. This statement is produced automatically when the program is created through the Repository Browser.The REPORT statement is used for ABAP reports programs.The PROGRAM statement is used for general ABAP programs (for example, module pool programs).All global data declarations must be grouped together at the beginning of the program in a declaration section.The statement section can consist of various processing blocks. This subject is dealt with in the remaining chapters of this course.Adhere to program naming standards dictated by the client.

    *One way to create a new program is:Go into the Program menu from the ABAP Editor:Initial ScreenSelect the Create menu option or use the Create function key.You can also create, maintain, and execute programs from the Repository Browser (this is the recommended method for creating programs).The program attributes must be maintained before proceeding.ABAP programs must be assigned to a development class or, if applicable, identified as a local, private object. (This is a requirement of SAPs Correction and Transport System.)The application, class, and type attributes are used for the management of ABAP programs.The application, title, and type attributes are required. Other attributes are optional, and only needed for specific read accesses or when you have additional requirements.F1 and F4 are help keys which allow you to search for the significance of the attributes or a list of allowable input values.Type 1 program type used to be called Online Program in previous releases. Due to the confusion with module pool programming, the description is now Executable Program.*The ABAP editor's Execute function is used to start an ABAP program directly from the editor.An ABAP module pool program is executed using transaction codes. *The WRITE statement outputs the contents of a field or constant in a format consistent with the data type.Successive WRITE statements output data on the same output line. When the line is full, output continues on the next line. The SKIP statement creates blank lines.Normally, ABAP produces two standard header lines for each page. The date and page number are displayed on the first header line along with the program title. The second header line is an underline.The date does not display until the report is printed.To have underlines show up on your screen, use the Paint Palette menubar option. Choose Options in the paint palette and click on the Colors in Lists tab. Be sure that Lines in Lists is turned on. If not, you will not see any lines displayed.Many system fields are available in an ABAP program. These system fields are defined as the ABAP Dictionary structure SYST. To reference system fields in a program, use SY-. For example, SY-DATUM indicates the current date and SY-UZEIT indicates the current time.You can use many methods to view the system ABAP Dictionary structure:ABAP DictionaryRepository Information SystemABAP Help in a program (use help pushbutton or F1)*ABAP provides many methods for formatting data. You can specify when to start a new line of output, start columns, and/or output length with the following statement:WRITE /. . . .The forward slash (/) in the WRITE statement indicates to start the output on a new line.The ULINE statement creates an underline.You can specify the exact location for an underline by referencing a line feed, position, and/or length with the following statement:ULINE /.*The UNDER addition to the WRITE statement allows you to specify a field be printed in the same start column (left justified) directly beneath a field which has already been output.You must still code an explicit line feed (with a forward slash) to move to the next line. The UNDER addition does not act as a line feed.

    *The sequence for the format specification of the WRITE statement must be followed precisely if more than one specification is used.Formatting options include:LEFT-JUSTIFIED RIGHT-JUSTIFIEDCENTEREDNO-GAP (deletes the gaps between consecutively displayed fields).USING EDIT MASK (specifies a format template).USING NO EDIT MASK (switched off any format template specified in the ABAP Dictionary).NO-ZERO (replaces leading zeros with blanks; if the contents of a field are equal to zero, the output consist entirely of blanks).There are many other formatting options. Consult the Extended Help text.*The NEW-PAGE statement starts a new page.This statement will not create an empty page.There are many interesting extensions to NEW-PAGE, such as PRINT ON. Look in Online Help for more information.

    *Certain symbols and icons can be written on a report. You must load the include programs and/or (the angle brackets are part of the name) with the INCLUDE statement.To write an icon to the report, use the following syntax:WRITE AS ICON.To write a symbol to the report, use the following syntax:WRITE AS SYMBOL.To display the complete list of icons, execute the program SHOWICON. For symbols, execute the program SHOWSYMB. You can go to the initial screen of the ABAP Editor (transaction code SE38) to execute these programs.

    Coding Recommendations:The INCLUDE statement can also be used to include separate data declarations that are used by many programs. For example: commonly used function export/import parameters, constants for TRUE/FALSE YES/NO flags, BDC_TAB, etc.

    *Text elements can be used to maintain a programs title and column headings, selection texts, and text symbols. These text elements can be maintained in multiple languages, so the display to the user will depend on the users specified logon language.We will cover text symbols on the next page. Selection texts will be covered in the next chapter when we learn the PARAMETERS statement.Maintain a list heading and up to four lines of column headings for a report by using the GoTo Text elements Titles/headings menu path).The text placed in the List header field will replace the default title (short text of the program) on the programs standard heading output.*Numbered texts (text symbols) are used most often for writing text to the screen that is language dependent.Maintain numbered texts using the GoTo Text elements Text Symbols menu path).It is possible to maintain numbered texts separately for different languages. Consult the SAPs online help for information on maintaining text elements in multiple languagesThe two methods of using numbered texts (text symbols) are:TEXT-xxx [where xxx is a unique three-character code](xxx) [where xxx is a unique three-character code]The TEXT-xxx method allows you to assign text to a text symbol for easier maintainability and coding. Therefore, you can refer to a long sentence as TEXT-xxx instead of writing in code the sentence every time it needs to be written to a list. The text contained in the text symbol will be written out in the users current logon language as long as it is maintained in that language. Otherwise nothing will be written out.The (xxx) method also allows for easier language maintenance. In case the text symbol (xxx) is not maintained in the users logon language then the is used. However, this method loses the benefit of not having to code the same sentence many times.*In an ABAP program, you can use eight system-defined, elementary data types to declare data objects:Character Text (standard length = 1; allowed length = no maximum)Numeric Text (standard length = 1; allowed length = no maximum)This data type should be used for numeric fields that will not be calculated (i.e., social security number and telephone number).Integer (standard length is machine specific and cannot be changed)This data type stores a binary number with a range of values from -21477483648 to +2147483647.Packed Number (standard length = 8; allowed length = 1 to 16)With this data type, two digits are stored in a single byte and the last half byte is used to store the sign. This data type is recommended for commercial calculations.Floating Point Number (standard length is machine specific and cannot be changed)With this data type, two digits are stored in a single byte and the last half byte is used to store the sign. This data type is recommended for mathematical/scientific calculations.Date (standard length = 8 and cannot be changed)This data type stores data in the YYYYMMDD formatTime (standard length = 6 and cannot be changed)This data type stores data in the HHMMSS formatHeXadecimal (standard length = 1; allowed length = no maximum)*To declare a variable (or field) in an ABAP program, use the DATA statement:DATA () TYPE VALUE .The only required parameter in this statement is the of the variable.A variables name can be up to 30 characters in length.This name should begin with a letter and the remainder of the name should consist of letters, numbers, or an underscore.SPACE is a reserved word in ABAP. The variables is specified in parentheses immediately after the (no spaces in between the name and the length).If no length is specified, the variable will be the standard length for the data type (see previous page).The variables is specified after the TYPE addition.If no data type is specified, the variable will be type C.To define a default value for the variable, use the VALUE addition.This default value is different than the initial value automatically assigned to a data object (see next page).In the example code above, what is the data type and length of the STARTER variable?Coding Recommendations:The function, STRLEN, can be used to find the length of a character string.*All data objects declared have an associated initial value. This initial value depends on the data type:C:blankN:00 (the number of zeroes depends on the defined length)I:0P:0F: 00E+00 (the number of zeroes depends on the system length)D:00000000T:000000X:00The CLEAR statement sets a field back to its initial value, not its default value.*Use the following rules when assigning default values to data objects:Default values for the character-based data types (C and N) must be a text literals (i.e. enclosed in single quotes. ).For example, see the NICKNAME variable above illustrates this rule.Default integer values for the numeric data types (I, P, and F) may or may not be enclosed in single quotes.For example, the POINTS variable above uses single quotes, but the GAMES variable does not.Default fractional values for the numeric data types (P and F) must be a text literals (i.e. enclosed in single quotes); otherwise, the decimal point would indicate the end of the statement.For example, the AVERAGE variable above illustrates this rule.For a packed or floating point number to be stored with a decimal, it must be defined with the DECIMALS addition. For example, AVERAGE(5) TYPE P DECIMALS 2 VALUE 25.5.Default values for date (D) and time (T) variables must be enclosed in single quotes.For example, the ACQUIRED variable above illustrates this rule.In the example code above, what is the value of the STARTER variable?*To declare fields with the same format (i.e. data type and length), use the LIKE addition instead of the TYPE addition to the data declaration.Defining fields in this manner makes it easy to change the format of several fields because you only need to make a change to the data type or length once in the program.In the LIKE addition, the can be:A previously-defined program field or field string (we will cover field strings in a future chapter)For example, the NICKNAME field above is defined LIKE PLAYER.An ABAP dictionary fieldFor example, the ACQUIRED field above is defined LIKE SY-DATUM.Remember that structures are considered table types in the ABAP Dictionary.The LIKE addition only applies to the data type and length, not a default value assigned to the referenced field.For example, the NICKNAME field above defined LIKE PLAYER will be a 35-length character field. However, the NICKNAME field will not have the Julius Erving default value assigned to it.*To declare a constant in an ABAP program, use the CONSTANTS statement. The basic syntax of this statement is: CONSTANTS () TYPE VALUE .A constants can be up to 30 characters in length.This name should begin with a letter and the remainder of the name should consist of letters, numbers, or an underscore.SPACE is a reserved word in ABAP.Like the constants , the VALUE addition is required because a constant must have a value. The constants is specified in parentheses immediately after the (no spaces in between the name and the length).If no length is specified, the constant will be the standard length for the data type.The constants is specified after the TYPE addition.If no data type is specified, the constant will be type C.You can use the LIKE addition instead of the TYPE addition as described on the previous page.You cannot change the value of a constant in an ABAP program (syntax error).

    Coding Recommendations: Hard-coded literals should be avoided. Use CONSTANTS if this clarifies the code.*To declare a user-defined data type in an ABAP program, use the TYPES statement. The basic syntax of this statement is: TYPES () TYPE .A user-defined data types can be up to 30 characters in length.This name should begin with a letter and the remainder of the name should consist of letters, numbers, or an underscore.SPACE is a reserved word in ABAP.The VALUE addition cannot be used because this statement only defines a data type. This statement does not allocate any memory for a field and, therefore, cannot have a value. The user-defined data types is specified in parentheses immediately after the (no spaces in between the name and the length).If no length is specified, the user-defined data type will be the standard length for the data type.The user-defined data types is specified after the TYPE addition.If no data type is specified, the user-defined data type will be type C.You can use the LIKE addition instead of the TYPE addition.*With the WRITE statement, a data object written to the list will have the standard output length associated to its data type (see above slide). If you want to change the output length of a field written to the report, you must specify the length in parentheses before the field name. For example, to write out a length 20 character field named VAR1 in only 10 spaces, use the following WRITE statement:WRITE: /5 The value is, (10) VAR1.For packed and integer fields, leading zeros are converted to blanks.For packed and integer fields, commas are inserted between thousands.With the WRITE statement, a data object written to the list will be justified within its field length according to the standard justification associated to its data type (see above slide). If you want to change a fields justification, you must use the LEFT-JUSTIFIED, RIGHT-JUSTIFIED, or CENTERED additions after the field name. For example, to make an integer field left justified, use the following WRITE statement:WRITE: /5 The total count is, COUNT LEFT-JUSTIFIED.*You can determine the number of decimal places to display in all numeric fields (i.e., integer, packed, and floating point fields) with the DECIMALS addition to the WRITE statement:WRITE DECIMALS .ABAP performs automatic rounding of numeric fields.You can explicitly round numeric fields with the ROUND statement.You can determine the value of the exponent to display in floating point fields with the EXPONENT addition to the WRITE statement:WRITE EXPONENT .If you want a packed field to store a decimal value, the DECIMAL addition must be used when defining the field. For example:DATA DECIMALS .The DECIMALS addition can also be used when defining parameters, constants, or user-defined data types.

    Coding Recommendations:A common cause of error occurs using the WRITE command with prices/values. Ensure to always use the CURRENCY option. Ex: WRITE: nnnnnnn CURRENCY nnn.*You have numerous alternatives to assign values to fields:MOVE TO .[COMPUTE] = .The key word COMPUTE is optional.ADD TO .SUBTRACT FROM .MULTIPLY BY .DIVIDE BY .There are other alternatives that we will cover in later chapters.The system carries out automatic type conversion if variables are not of the same type.If a character field is to be converted to a packed field, only numbers, the plus/minus sign, and the decimal point are allowed. The plus/minus sign will be placed at the end of the packed field.If a packed field is to be converted to a character field, the numerical value is formatted (decimal point, sign) and the leading zeros are converted to blanks.For information for all conversions between variables of different types, see the ABAP editor documentation for MOVE (type MOVE and hit F1).UNPACK is a specific conversion keyword moving values from a packed variable (type P) to a character one (type C).*The valid operators for arithmetic expressions are: +, -, *, /, **, DIV and MOD.** indicates exponentiation (i.e., 3 ** 2 means 3 to the power of 2).DIV indicates the quotient (i.e., 10 DIV 3 evaluates to 3).MOD indicates the remainder (i.e., 10 MOD 3 evaluates to 1).Arithmetic functions also exist in ABAP. Some of these functions include: SQRT, EXP, LOG, SIN, COS, and STRLEN.The order of operation in arithmetic expressions is:ParenthesesFunctionsExponentiation*, /, DIV, and MOD+ and -All operators and parenthesis in an arithmetic expression must be separated by at least one space. Functions must be followed immediately by an opening parentheses:Incorrect: ANSWER=(10+SQRT(NUM1))/(NUM2 - 10).Correct: ANSWER = ( 10 + SQRT( NUM1 ) ) / ( NUM2 - 10 ).Before calculations are performed, field values of non-numeric fields are automatically converted to numerical values.There is no limit to the nesting levels for parentheses in arithmetic expressions.*ABAP allows you to display and change portions of a field by specifying an offset and length.To display a portion of a field, use the following WRITE statement:WRITE +().For example, to write the third, fourth, and fifth characters of a field named CUSTOMER, the WRITE statement would be:WRITE CUSTOMER+2(3).To change a portion of a field, use the following statement: +() = .For example, to change the month of a date field named BIRTHDAY, the statement would be:BIRTHDAY+4(2) = 11.The offset and length can be used together (as the previous examples illustrate) or separately.*Remember that date fields are stored YYYYMMDD.You can perform calculations on dates, but you must keep in mind that the system can only work in terms of a number of days. For example:You can add seven days to a date field.You cannot add two weeks to a date field. This value would have to be converted into a number of days.If you perform calculations on a date field, the date field is converted to a packed number that represents the number of days since the beginning of 01/01/0001.

    Coding Recommendations:There are numerous SAP functions that will perform date calculations. Ex: RP_CALC_DATE_INTERVAL, DATE_COMPUTE_DAY, DATE_GET_WEEK, DATE_CHECK_PLAUSIBILITY, POPUP_TO_SELECT_MONTH, EASTER_GET_DATE.Conversion functions usually have the word CONVERT or CONVERSION in their name. Ex: CONVERSION_EXIT_PERI_INPUT converts dates from the format MMYYYY to YYYYMM (if passed in as MMYY, it is passed out as YYYYMM), CONVERSION_EXIT_INVDT_INPUT converts date in format DDMMYYYY to SAP inverted date format - plus many other variations.

    *To declare a variable (or field) in an ABAP program that can be given a value at runtime, use the PARAMETERS statement. The basic syntax is: PARAMETERS () TYPE DEFAULT .The only required addition in this statement is the of the parameter.A parameters name can be up to 8 characters in length.This name should begin with a letter and the remainder of the name should consist of letters, numbers, or an underscore.SPACE is a reserved word in ABAP. The parameters is specified in parentheses immediately after the (no spaces in between the name and the length).If no length is specified, the variable will be the standard length for the data type (see page 1).The parameters is specified after the TYPE addition.If no data type is specified, the variable will be type C.To define a default value for the parameter, use the DEFAULT addition.This default value is different from the initial value automatically assigned to a data object (see page 3).When you execute a program using the PARAMETERS statement, a selection screen is displayed for you to enter values into the parameters. To continue program execution from the selection screen, click on the Execute pushbutton (or press the F8 key).*Text elements can be used to maintain a programs title and column headings, selection texts, and text symbols. These text elements can be maintained in multiple languages, so the display to the user will depend on the users specified logon language.Maintain the selection texts by selecting the Selection texts option in the Text Elements function (GoTo Text elements menu path).The text placed in the Text field for a parameter will be used on the selection screen instead of the name of the parameter. Using selection texts allows you to create meaningful text on the selection screen.*A field symbol is a place holder for a field (i.e. a pointer). A field symbol does not reserve space for the field, but points to the field (i.e., a field symbol assumes the address of the field, not the value).A field symbol can point to single fields or field strings (structures). Remember that the TABLES statement creates a field string with the appropriate ABAP Dictionary structure.When working with field symbols, angle brackets (< >) must be used.The FIELD-SYMBOLS statement is used to declare a field symbol.A field symbols name can be up to 30 characters in length. This name should begin with a letter and the remainder of the name should consist of letters, numbers, or an underscore.If a field symbol is defined without attributes, it takes on the attributes of the field assigned to it.If a field symbol is given a data type and length (either explicitly or with the LIKE addition), the system verifies that the field symbol has the same attributes as the field assigned to it.The ASSIGN statement associates a field to a field symbol at runtime (i.e., when the program is executed).If you change the value to a field symbol, you are really changing the value of the field assigned to the field symbol. If you write the value of the field symbol, you are really writing the value of the field assigned to the field symbol.

    *With the ASSIGN statement, you can assign a portion of a field to a field symbol by specifying the fields offset and length.In the example above, the field symbol FSYMBOL is assigned to five characters of the variable TEXT_LINE starting with the third character. If a change is made to the field symbol, only these five characters of the variable will be changed.The output from the code above would be:Text Line =ABCDEFGHIJKField Symbol = CDEFGField Symbol = 12345Text Line = AB12345HIJK

    *With the ASSIGN statement, you can assign a field to a field symbol where the name of the field is not known until the program is executed. This is called dynamic field assignment.For example, in the code above a field name is being entered as a parameter. The field entered will be assigned to a field symbol.To perform a dynamic field assignment, you must enclose in parentheses the variable that contains the appropriate field name. For example:ASSIGN (FIELD) TO .After a dynamic field assignment, the value of SY-SUBRC indicates whether a field was assigned to the field symbol. If the assignment was successful (i.e., the variable in parentheses contained a valid field name), SY-SUBRC will be set to zero.If the assignment was not successful (i.e., the variable in parentheses did not contain a valid field name), SY-SUBRC will be set to a non-zero number.If you are going to assign a field string created with the TABLES statement to a field symbol, execution time is minimised if you use the ASSIGN TABLE FIELD option.*Information is retrieved from the database for use in our programs via a special language known as Structured Query Language, or SQL. SQL is a language specifically designed for use with relational database systems. It is used in many systems, not just SAP. However, ABAP has certain SQL commands built-in, so the connection between ABAP and SQL is fairly seamless.SQL has three main components, which are used for different purposes:Data Manipulation Language (DML): For retrieving and updating information in the database.Data Definition Language (DDL): For defining database objects and specifying the structure of the data in the database. In SAP, these functions are handled primarily by the ABAP Dictionary and the Database Utility.Data Control Language (DCL): For controlling access to DML and DDL functions.This course covers the first category only: Data Manipulation LanguageThe DML provides the four basic data operations: Select (retrieve)InsertUpdateDelete*As noted on the previous page, SQL is a standard language used across many different systems. The majority of the functionality provided by SQL remains the same across all systems, but some database manufacturers have added their own proprietary extensions to SQL. Additionally, the syntax of SQL has minor variations across systems.SAP had to ensure that SQL statements in ABAP programs would be compatible with each of the underlying database systems supported by SAP. This was accomplished through the development of Open SQL (also called SAP SQL).Open SQL is a subset of standard SQL with a specific syntax recognised by ABAP. The run-time environment of the R/3 System automatically translates Open SQL statements to the appropriate syntax for the underlying database system. Therefore, code written in Open SQL will run on any database system supported by SAP. Note: Sometimes, for technical reasons, it is advantageous to know which database system an application is intended for. However, if Open SQL is used, it is not necessary to know this. SAP itself was written using Open SQL because it was intended to run on multiple systems.*In all versions of SQL, the SELECT statement is used to read records from a database table. The most basic form of the SELECT statement is:SELECT * FROM .This statement retrieves all columns and all rows from the specified table. In ABAP, the data is placed into a work area created by the TABLES statement.The TABLES statement serves two purposes:It declares to the program which ABAP Dictionary tables will be accessed.It creates a work area where individual records from the table can be stored. The work area is an area in memory, just like a program variable, and it is sized so that it can hold exactly one record from the specified table.The Open SQL SELECT statement automatically places records from the database into the work area. Since the work area can only hold one record at a time, the SELECT statement automatically creates a looping structure. One record is transferred from the database to the work area with each loop pass.The SELECT loop is delimited by the ENDSELECT statement. The statements inside the loop are executed once for each record retrieved.*For example, to write the ID and name of all customers in the system, we could write the code that appears on the above slide.Note: The SELECT statement is used in all versions of SQL. However, the specific syntax and functionality discussed here is specific to Open SQL. Except where otherwise noted, all references in this course to SQL are to Open SQL.Note that individual fields within the work area are referenced by using the work area name, followed by a hyphen, followed by the individual field name.To see a list of the fields that are available in a table, you can:Double-click on the name of the table in your program code in the ABAP Editor. You will be taken to the dictionary definition of that table.Choose table structure in the ABAP Help function.Use the ABAP Repository Information System.Use the Edit More functions Enter command menu option and type SHOW in the command line.Change the Editor Mode to Command Mode and type SHOW in the command line.*Suppose that, instead of displaying information for all customers, we only wanted to display information for customers belonging to a certain account group.We could accomplish this by using the WHERE clause of the SELECT statement. The WHERE clause restricts the records that are retrieved from the database.The code on the above slide demonstrates the use of the WHERE clause (KTOKD is the account group field).When using the WHERE clause, you must specify a logical expression. To the left of the relational operator, you must specify a field from the table in the FROM clause. To the right of the relational operator, you must specify a program variable or a literal value. Complex WHERE clauses can be built using AND, OR, and NOT.*The system field SY-SUBRC is set after each SELECT from the database.If at least one record was found that matched the selection criteria, SY-SUBRC is set to zero. Otherwise, SY-SUBRC is set to a non-zero value (currently, SY-SUBRC is set to 4). It is good programming practice to check SY-SUBRC after each SELECT. That way, if no records are found, an appropriate message can be displayed to the user (or your program can take appropriate action). If no records are found, failing to check SY-SUBRC may cause your program to appear to do nothing. SY-SUBRC should be checked immediately after the ENDSELECT statement not inside the SELECT loop.*As an alternative to SELECT *, it is possible to select only those columns required by the program.This form has the advantage of transferring significantly less data from the database server to the application server.When selecting individual columns from a database table, an INTO clause is required. Data is not automatically placed into the corresponding fields of the table work area. The INTO clause must contain the same number of columns as the SELECT clause. The INTO clause may refer to individual fields from the table work area or to any other variable in your program.Note: There can be no commas after column names in the SELECT clause. All of the variables in the INTO clause are enclosed in a single set of parentheses and are separated by commas. Also, there must not be a space between the parentheses and the variable names in the INTO clause.

    Performance Tips:SELECT INTO is much more efficient than SELECT *. This form should be used whenever possible.

    *The above statement does exactly the same thing as the statement on the previous page: it selects customer number and name and puts them into the KNA1 table work area fields KNA1-KUNNR and KNA1-NAME1.The SELECT ... INTO CORRESPONDING-FIELDS OF replaces coding the individual fields that the values are selected into from the database table and results in code that is easier to read without any performance losses. When this statement is used with the the values from the database table are placed in the work area of the internal table (i.e. the header line) and then need to be appended to the body of the table - see chapter 8 for more information on internal tables. *This chapter introduces some of the basic statements ABAP provides to control program flow.*The most basic flow control statement in any programming language is the IF statement. The IF statement is used to ensure statements are executed only if certain conditions are met. The counterpart to the IF statement is the ENDIF statement. Every IF statement must have a corresponding ENDIF. The statements between the IF and the ENDIF are executed only if the condition specified in the IF statement evaluates to true.If the initial IF condition is false, the optional ELSE and ELSEIF statements can be used to execute other blocks of statements. A period is required after every statement in the IF structure.In the example below, only one of the WRITE statements will be execute:IF X = 5. WRITE: / The value of X is 5.ELSEIF X = 6. WRITE: / The value of X is 6.ELSE. WRITE: / The value of X is neither 5 nor 6.ENDIF.

    Performance Tips: Ensure the first IF statements are most frequently true for better performance.*The conditions tested in IF statements are known as logical expressions. Logical expressions are constructed using relational, logical, and string comparison operators.Relational operators indicate whether:Two values are equalOne value is greater than anotherA value falls within a specific rangeA variable is equal to a certain pre-defined valueLogical operators link multiple logical expressions using AND, OR, and NOT.String comparison operators are special operators used to manipulate variables of type C.Each of these is discussed in more detail on the following pages.

    Coding Recommendations:For a logical AND statement in an IF construct, put the most likely FALSE case first, and conversely for a logical OR statement put the most likely TRUE statement first.*ABAP supports all standard equality and inequality operators.Additionally, ABAP supports the operators IN, BETWEEN, and IS INITIAL. (Certain bitwise comparisons are also available. Consult the online help.)The IN operator is used to test whether a value belongs to a list of values contained in a selection table. You will learn how to use selection tables in a later chapter.The BETWEEN operator is used to test whether a value lies within a range. The range specified by BETWEEN is inclusive. For example, the statement:IF X BETWEEN 1 AND 5.is equivalent toIF X >= 1 AND X 0 ) )OR ( CURR_LEVEL = 0 ) ).*String comparison operators can be used to compare strings and portions of strings. With the pattern comparison operators, the following special characters can be used:*This indicates a pattern of any characters+This indicates any single character#This is used before a * or a + to indicate that the * or + is to be taken literally. It also has other special uses. Consult the online help for details.The system field SY-FDPOS is set after each string comparison. Depending on the type and outcome of the string comparison operation, SY-FDPOS is either set to the length of one string, or to the offset of one string within another. Consult the online help for detailed information on how SY-FDPOS is set.The offset of a character within a string refers to the number of places from the beginning of the string that the character occurs. For example, in the string ABAP is great!, the offset of B is 1. The offset of the first character in any string is 0; the offset of the second character is 1; and so on.The operators CP and NP are not case-sensitive. All other string comparison operators are case-sensitive.*The CASE statement is used to distinguish between mutually exclusive options. It is used when a single variable can take on one of several known values. Each of the possible known values is specified in a WHEN clause, which heads a block of code to be executed when the variable takes on that value.The WHEN OTHERS clause can be used to provide a default action if the variable does not equal one of the specified values. It is good programming practice to include a WHEN OTHERS clause in a CASE statement.Each clause of the CASE statement must end with a period. The entire CASE statement structure must end with the ENDCASE statement.

    Performance Tips:Use the CASE statement instead of multiple IFs and ELSEIFs where possible. This is better for two reasons, firstly it is easier to read, and secondly, after about five IF checks, the performance of the CASE statement is more efficient.*A DO loop is used to unconditionally execute a block of code multiple times. By default, a DO statement creates an infinite loop. For example, the following code would never terminate:DO. WRITE: / Hello, world!.ENDDO.It is possible to specify the number of loop iterations by adding the n TIMES parameter to the DO statement (n can be a literal or a variable). For example, the following loop executes 4 times.J = 4.DO J TIMES. WRITE: / Hello, world!.ENDDO.Alternately, it is possible to terminate a DO loop by issuing one of the following statements inside the loop: EXIT, STOP, or REJECT. When one of these statements is encountered, the DO loop immediately terminates. More detail about these statements is covered later (STOP and REJECT will be covered in future chapters).DO loops must be delimited by the ENDDO statement.*In contrast to the DO loop, a WHILE loop conditionally executes a block of code, possibly multiple times.The WHILE statement must always be followed by a logical expression. Before each loop iteration (including the first), the logical expression is evaluated. If the expression evaluates to true, the code inside the loop is executed. If the expression is false, the code inside the loop is not executed, and control moves to the first statement after the ENDWHILE statement.As with a DO loop, an EXIT, REJECT, or STOP statement immediately terminates the loop.The system variable SY-INDEX represents the index of the current loop pass (starting with 1 for the first loop pass). Outside a loop, SY-INDEX is zero.*It is possible to nest flow control statements.Inside nested loops, SY-INDEX automatically reflects the correct index for each level of the nested loop. Consider the following example:DO 2 TIMES. WRITE: / SY-INDEX. DO 3 TIMES. WRITE: / , SY-INDEX. ENDDO.ENDDO.The output from the above code would be:1 1 2 32 1 2 3

    *The ON CHANGE OF statement is used inside a loop (usually a SELECT loop). It is used to determine whether the specified variable is different from what it was during the prior pass through the loop.In the first loop pass, the ON CHANGE OF statement always evaluates to true. Outside a loop, ON CHANGE OF always evaluates to true.It is possible to specify multiple fields in an ON CHANGE OF statement by separating the fields with an OR. In this case, the statement evaluates to true if any of the fields have changed since the last loop pass. For example:SELECT * FROM YCUSTOMER. ON CHANGE OF YCUSTOMER-COUNTY OR YCUSTOMER-STATE. [