《ABAP Programming》由会员分享,可在线阅读,更多相关《ABAP Programming(135页珍藏版)》请在金锄头文库上搜索。
1、Page 1ABAP TrainingABAP ProgrammingDavid SunPage 2ABAP Programming LanguageAdvanced Business Application ProgrammingPage 3ReportingPrograms 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 sc
2、heduled to run at specific intervals.Page 4Non-SAPLegacySystemGeneral ProgrammingModule Pool ProgrammingBatch Input ProcessingModulePoolInter-System CommunicationSequential Dataset ProcessingPage 5Terms to RememberReport:An ABAP program whose output is a listModule Pool:A dialog program which is a c
3、ollection of screensList:The output generated by an ABAP report programProgramA series of ABAP statementsABAP EditorABAP EditorPage 7ReportingABAPDevelopmentReporting and ABAP DevelopmentPage 8Programming Environment - The ABAP EditorPage 9Programming EnvironmentOnline DebuggingPage 10Basic Function
4、s of the ABAP EditorProgram source entry areaFind andRepeat FindToggles fromdisplay to change modeUndoABAP HelpSyntax CheckStandard toolbarCut, copy and paste to and from a bufferPage 11The PROGRAM Menu OptionPage 12The EDIT Menu OptionPage 13The GOTO Menu OptionPage 14The UTILITIES Menu OptionPage
5、15The BLOCK/BUFFER Menu OptionPage 16The SETTINGS Menu OptionTo set Editor mode, use the menu pathSettings- Editor modePreferred settings: PC mode with line numbering With compression logic Key word largePage 17DATA COUNT TYPE I.DATA TITLE(25).MOVE 1 TO COUNT.MOVE President TO TITLE.WRITE TITLE.WRIT
6、E COUNT.Basic ABAP Program SyntaxABAP ProgramStatement.Word 1Word 2Word 3Word 4Key wordParameter, field, or constantPage 18Chaining 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:
7、 1 TO COUNT,President TO TITLE.Page 19Comments 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.Page 20ABAP Program StructureProgram Name AreaUse REPORT for listing programsUse PROGRAM for onl
8、ine programsDeclaration SectionUsed for defining tables, variablesand constantsStatement SectionUsed for coding executableABAP statementPage 21ABAP Program AttributesType:1-Executable ProgramI-Include ProgramM-Module PoolF-Function GroupS-Subroutine PoolProgram title is requiredApplication:S-BasisU-
9、EDM (Enterprise Data Model)V-Sales and DistributionY-Customer Head OfficeZ-Customer Branch*-For all ApplicationsPage 22Running an ABAP ProgramFrom the ABAP Editor:With the program displayed,ProgramExecuteAn Alternative Method:From the System Menu, choose Services Reporting to launch the programOne F
10、inal Method:From the ABAP Editor: Initial Screen, type the program name, then click on the Execute push-buttonPage 23The 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
11、:06*Notice that there is an automatic space between the fields written to the list.Page 24ABAP 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 Philad
12、elphia *Ticket Date 01/01/1997 Ticket Time 18:01:00-* Department of Public Safety *Page 25ABAP 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 P
13、hiladelphia *Ticket Date 01/01/1997 Ticket Time 18:01:00-* Department of Public Safety * Page 26“WRITE” Statement Extended SyntaxWRITE ./p(I)/ = Line Feedp = Column PositionI = Output LengthProgram Field orText Literal Format OptionsPage 27WRITE * City of Philadelphia *.SKIP.WRITE: / Ticket Date, 15
14、 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” StatementPage 28Writing Icons and SymbolsINCLUDE .INCLUDE .W
15、RITE: /10 ICON_DATE AS ICON, SY-DATUM, SYM_LEFT_HAND AS SYMBOL.Execute programs “SHOWICON” and “SHOWSYMB” to display the systems icons and symbols.Page 29Maintaining Page HeadersThe title comes from the programs attributes.List header will replace title on first line of standard header.Up to four li
16、nes of column headings can be maintained for the list.Page 30Numbered Texts (Text Symbols)Text symbols are referenced by a unique three-character code.WRITE: / TEXT-001, BIRTHDAY, / TEXT-002, SY-DATUM.Page 31C: Character TextI: IntegerP: Packed #F: Floating Point #N: Numeric TextD: DateT: TimeX: Hex
17、adecimal #ABAP Elementary Data TypesPage 32DATA: PLAYER(35)TYPE C,NICKNAME(35),POINTSTYPE I,GAMESTYPE IVALUE 10,AVERAGE(5)TYPE P,STARTER,ACQUIREDTYPE D.Declaring VariablesPage 33C: (blank)I: zeroP: zeroF: zeroesN: zeroesD: 00000000T: 000000X: 00The “CLEAR” statement sets a field back to its initial
18、value, not its default value.Initial ValuesPage 34DATA: 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 ValuesPage 35DATA: PLAYER(35)TYPE CVALUE Julius Erving,NICKNAME(35),A
19、CQUIREDTYPE 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” FieldsPage 36CONSTANTS: TEAM1(20)TYPE CVALUE 76ers,TEAM2LIKE TEAM1 VALUE Celtics,TOT_GAMES TY
20、PE IVALUE 82.If you attempt to change the value of a constant, a syntax error will occur.The “VALUE” additionis required.Declaring ConstantsPage 37TYPES: NAME(35)TYPE C,TEAMS(20)TYPE C.DATA:PLAYERTYPE NAMEVALUE Troy Aikman,NICKNAMELIKE PLAYER.CONSTANTS: TEAM1 TYPE TEAMSVALUE Cowboys,TEAM2 LIKE TEAM1
21、 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 TypesPage 38Standard LengthStandard LengthC C = = defined lengthdefined lengthI I= = 1212P P = = (2 * defi
22、ned length) + 1(2 * defined length) + 1F F = = 2222N N = = defined lengthdefined lengthD D = = 1010T T = = 8 8X X = = (2 * defined length)(2 * defined length)JustificationJustificationC C = = left-justifiedleft-justifiedI I= = right-justifiedright-justifiedP P = = right-justifiedright-justifiedF F =
23、 = right-justifiedright-justifiedN N = = left-justified left-justifiedD D = = left-justified left-justifiedT T = = left-justified left-justifiedX X = = left-justified left-justifiedOutput Characteristic for Data TypesPage 39DATA: FLOAT TYPE FVALUE 98.7654321E2,PACKTYPE PVALUE 12,INTTYPE I VALUE 32.W
24、RITE:/ 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 FieldsPa
25、ge 40DATA: 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 FieldsPage 41COUNTER = COUNTER + 1.SALARY = BASE * BONUS_PERCENT
26、.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 ExpressionsPage 42DATA: CUSTOMER(10) TYPE C,INV_DATE LIKE SY-DATUM.CUSTOMER = 12
27、34567890.INV_DATE = 19960626.WRITE: / CUSTOMER+8(2), xx,INV_DATE(4).* Start of MonthINV_DATE+6(2) = 01.CUSTOMER+6 = ABCD.WRITE: / CUSTOMER, -, INV_DATE.90 xx 1996123456ABCD - 06/01/1996Use an offset and length to display or change portions of a field.Sub-Fields in ABAPPage 43DATA: DAYSOLD TYPE P,DOB
28、 TYPE D,TODAY LIKE SY-DATUM.DOB = 19621230.TODAY = SY-DATUM.DAYSOLD = TODAY - DOB.WRITE: You are, DAYSOLD, days old.You are 12410 days old.Date fields store values as “YYYYMMDD”.Date Calculations in ABAPPage 44PARAMETERS: NUM TYPE I,NAME(20) DEFAULT AARON.ADD 10 TO NUM.WRITE: / NUM, -, NAME. 32 - AA
29、RON“Selection Screen”Declaring Fields with PARAMETERSPage 45These selection texts will be used on the selection screen instead of the parameter names.Selection TextsPage 46DATA: NUM TYPE I VALUE 12.FIELD-SYMBOLS: , TYPE I, LIKE NUM.ASSIGN:NUM TO ,NUM TO ,NUM TO .WRITE: /Line 1:, NUM, , , . = 32.WRIT
30、E: /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 ABAPPage 47DATA: TEXT_LINE(30) VALUE ABCDEFGHIJK.FIELD-SYMBOLS .ASSIGN TEXT_LINE+2(5) TO .* this assigns 5 characters of text_line star
31、ting at* position 3 to the field string.WRITE: / text line =, TEXT_LINE.ULINE.WRITE: / field symbol=, .ULINE. = 1234567890.WRITE: / field symbol =, .ULINE.WRITE: / text line =, TEXT_LINE.Dynamic Assignment of Partial StringsPage 48PARAMETERS FIELD(8) DEFAULT SY-UZEIT.FIELD-SYMBOLS .ASSIGN (FIELD) TO
32、 .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:06FIELDSY-UZEITSelection ScreenListDynamic Field AssignmentPage 49DBRetrieving Information From the DatabaseDataJohn SmithMary StilesPag
33、e 50Open SQLPortable across various databasesOpen SQL - a subset of standard SQLPage 51The Basic SELECT StatementDBMary StilesJohn SmithWork AreaSELECT *FROM .ENDSELECT.Page 52Example Using the SELECT StatementTABLES: KNA1.SELECT * FROM KNA1. WRITE: / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.Page 53The SELE
34、CT Statement with a WHERE ClauseTABLES: KNA1.SELECT * FROM KNA1 WHERE KTOKD = 0001. WRITE: / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.Page 54SY-SUBRCTABLES: KNA1.SELECT * FROM KNA1 WHERE KTOKD = 0001. WRITE: / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.IF SY-SUBRC 0. WRITE: / No records found.ENDIF.Page 55The INTO Cl
35、auseTABLES: KNA1.SELECT KUNNR, NAME1 FROM KNA1 INTO (KNA1-KUNNR,KNA1-NAME1). WRITE : / KNA1-KUNNR, KNA1-NAME1.ENDSELECT.IF SY-SUBRC 0. WRITE: / No records found.ENDIF.Page 56INTO CORRESPONDING-FIELDSTABLES: KNA1.SELECT KUNNR, NAME1 FROM KNA1 INTO CORRESPONDING-FIELDS OF KNA1. WRITE : / KNA1-KUNNR, K
36、NA1-NAME1.ENDSELECT.IF SY-SUBRC 0. WRITE: / No records found.ENDIF.Page 57Basic Flow Control in ABAPPage 58The 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.Page 59Logical ExpressionsLogical Expressions use :REL
37、ATIONAL OPERATORSLOGICAL OPERATORSSTRING COMPARISON OPERATORSPage 60Comparison SyntaxIs Equal to=, EQIs not equal to , , GTGreater than or equal to =, = , GELess than , LTLess than or equal to =, =, LERelational OperatorsPage 61Logical OperatorsANDORNOTThe hierarchy of the logical operators is:NOT,
38、AND and then OR.(ie different from creating views)Page 62String Comparison OperatorsComparisonSyntaxContains onlyContains anyContains stringContains patternContains not onlyContains not anyContains no stringContains no patternCOCACSCPCNNANSNPPage 63The CASE StatementCASESY-UCOMM.Dont forgetthose per
39、iods!WhenSAVE.WhenSRTD.WhenPICK.WhenGETD.WhenSRTA.Page 64The DO LoopDO.WRITE :/ Hello world!.ENDDO. J =4.DO J TIMES.WRITE :/ Hello world!.ENDDO. Page 65The WHILE LoopIf expression evaluates to TRUE, code in loop is executed. If expression evaluates to FALSE, code in loop is NOT executed, and control
40、 moves to after ENDWHILE.Page 66Nested Loops and Control StructuresDO 2 TIMES. WRITE :/ SY-INDEX. DO 3 TIMES. WRITE : / , SY-INDEX. ENDDO.ENDDO. Page 67The ON CHANGE OF StatementSELECT * FROM YCUSTOMER. ON CHANGE OF YCUSTOMER-COUNTRY OR YCUSTOMER-STATE. . ENDON.ENDSELECT.Page 68The CHECK StatementDO
41、 10 TIMES. CHECK SY-INDEX = 4. WRITE :/ SY-INDEX.ENDDO.Page 69The EXIT StatementIF SY-SUBRC 0. EXIT.ENDIF. Page 70The CONTINUE StatementDO 10 TIMES. IF SY-INDEX 4. CONTINUE . ENDIF. WRITE :/ SY-INDEX.ENDDO.Page 71Address ListStructureStructureData StructuresAddress ListInternal TableInternal TableLN
42、LNFNFNCityCityST.ST.LNLNFNFNCityCityST.ST.LNLNFNFNCityCityST.ST.LNLNFNFNCityCityST.ST.Page 72Declaring 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-FL
43、AG.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?Page 73REPORT Yxxxxxxx.TYPES: BEGIN OF ADDR,FL
44、AG,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 , . . . , . . . , . .
45、 . , END OF .DATA: TYPE . FlagID Name1 CityAddress StructurePage 74Populating 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-CORRESPOND
46、ING EMPLOYEE TO ADDRESS. WRITE: / ADDRESS-FLAG, ADDRESS-ID, ADDRESS-NAME, ADDRESS-CITY. CLEAR ADDRESS.ENDSELECT.EMPLOYEEAddressID Name1 City000000001 Electronics Inc. Waldorf MOVE-CORRESPONDING EMPLOYEE TO ADDRESS.Flag ID Name City000000001 WaldorfClear .Page 75Internal Table TypesStandardSortedHash
47、edPage 76REPORT Y170DM38.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,IDLIKE EMPLOYEE-ID,NAME1LIKE EMPLOYEE-NAME1,COUNTRY LIKE 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.EN
48、DSELECT.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 C
49、OUNTRYCreating an Internal Table with Header LinePage 77Internal Table KeysImplicit KeyAll character fieldsExplicit KeyUser-defined-e.g. WITH UNIQUE/NON-UNIQUE KEY FIELD1 FIELD2 .Page 78Size of an Internal TablePage 79APPEND SORTED BY .APPEND .Department Salary123456Department SalaryHeaderLoading an
50、 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,000Page 80REPORT Y170DM42.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRY LIKE EMPLOYEE-COUNTRY,IDLIKE EMPLOYEE-ID,SALARYLIKE EMPLOY
51、EE-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 LineMor
52、e 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 interna
53、l table.Example 1Example 2ORPage 81Internal Table with Header Line EMPLOYEEEMPLOYEE COUNTRY ID FORMA NAME1 SORTL . . . ID NAME1COUNTRYHeader LineABPage 82Internal Table with Header Line ID NAME1 COUNTRYEMPLOYEEEMPLOYEEUSA00000001 Company Baker DistributorsBAKER. . . COUNTRY ID FORMA NAME1 SORTL . .
54、.Header Line1Page 83Internal Table with Header Line ID NAME1 COUNTRY00000001 Baker Distributors USAEMPLOYEEEMPLOYEEHeader Line21USA00000001 Company Baker DistributorsBAKER. . . COUNTRY ID FORMA NAME1 SORTL . . .Page 84Internal Table with Header Line USA 00000001 Company Baker Distributors BAKER . .
55、. ID NAME1 COUNTRY00000001Baker DistributorsUSA00000001Baker DistributorsUSAEMPLOYEEEMPLOYEE COUNTRY ID FORMA NAME1 SORTL . . .Header Line2312310.This header line is attached to the body of the internal table.1Page 85Internal Table with Header Line ID NAME1 COUNTRY00000001 Baker Distributors USA0000
56、0002 Diversified Indust.USA00000002 Diversified Indust. USAUSA 00000002 Company Diversified Indust. DIVERS . . .EMPLOYEEEMPLOYEE COUNTRY ID FORMA NAME1 SORTL . . .Header Line5612310.4Page 86Creating an Internal Table without a Header LineREPORT Y170DM40.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,IDLIKE EM
57、PLOYEE-ID,NAME1LIKE EMPLOYEE-NAME1,COUNTRY LIKE 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. ID NAME1 COUNTRYAPPEND to .The TYPES statem
58、ent 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.Page 87Separate Internal
59、Table Work AreaPerformance IssuesNested Internal TablesInternal Table without a Header Line WHY?Page 88Internal Table without a Header LineEMPLOYEEEMPLOYEE COUNTRY ID FORMA NAME1 SORTL . . .Work AreaAB ID NAME1 COUNTRYPage 89Internal Table without a Header Line ID NAME1 COUNTRY ID NAME1COUNTRY 00000
60、001 Baker Distributors USA00000001 Baker Distributors USA USA 00000001 Company Baker Distributors BAKER . . .EMPLOYEEEMPLOYEE COUNTRY ID FORMA NAME1 SORT . . .Work Area12312310.This work area is not attached to the body of the internal table.Page 90Transferring ABAP Dictionary Table StructuresREPORT
61、 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.Notice the MOVE statement in
62、stead of a MOVE-CORRESPONDING.Page 91Automatic Field ConversionMOVE-CORRESPONDING or MOVE field to fieldIndividual field type conversionMOVEStructure to structureField to structureStructure to field-Intermediate C type -Followed by adoption of new typesPage 92Mass Reading from Database Tables into I
63、nternal 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 o
64、ccurs.Page 93Processing 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
65、 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.If no internal table entries qualify under the logical expression, the statement within the loop is not
66、executed and SY-SUBRC is set to 4.This LOOP AT statement allows for a logical expression in a WHERE clause to limit the processing of the internal table.Page 94System Field SY-TABIXREPORT Y170DM46.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRYLIKE EMPLOYEE-COUNTRY,NAME1LIKE EMPLOYEE-NAME1, END OF EMP.
67、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,
68、EMPTAB-NAME1.ENDLOOP.screen outputSY-TABIXPage 95Accumulating Data within an Internal TableREPORT Y170DM43.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRY LIKE EMPLOYEE-COUNTRY,SALESLIKE EMPLOYEE-SALES, END OF EMP.DATA: EMPTAB TYPE STANDARD TABLE OF EMP INITIAL SIZE 10 WITH HEADER LINE.SELECT * FROM EM
69、PLOYEE. 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.0
70、0screen outputPage 96Sorting an Internal TableREPORT Y170DM44.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRY LIKE 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-CORRESP
71、ONDING 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
72、table.screen outputPage 97REPORT 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
73、.ENDSELECT.READ TABLE .Reading a Single Table EntryPage 98Reading 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 CO
74、MPARING . . . .8) READ TABLE COMPARING ALL FIELDS.9) READ TABLE TRANSPORTING . . . .10) READ TABLE TRANSPORTING NO FIELDS.Page 99Maintaining Internal TablesSELECT * FROM EMPLOYEE. MOVE-CORRESPONDING EMPLOYEE TO EMPTAB. APPEND EMPTAB.ENDSELECT.READ TABLE EMPTAB INDEX 1.MOVE ABC TO EMPTAB-NAME1.MODIFY
75、 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. Page 100Working
76、 with an Internal Tablewithout a Header LineAPPEND TO .COLLECT INTO .INSERT INTO .MODIFY FROM .READ TABLE INTO .LOOP AT INTO .Page 101Deleting an Internal TableCLEAR Initialises the header line.Internal table lines remain unchanged.REFRESH Deletes all table lines.Storage space is not released.Paging
77、 is released.Header line remains unchanged.FREE Deletes all table lines.Storage space is released.Header line remains unchanged.Page 102Information about an Internal TableREPORT Y170DM49.TABLES: EMPLOYEE.TYPES: BEGIN OF EMP,COUNTRY LIKE EMPLOYEE-COUNTRY,NAME1LIKE EMPLOYEE-NAME1,END OF EMP,DATA:EMPTA
78、B 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_C
79、OUNT.DESCRIBE TABLE LINES OCCURS .screen outputPage 103REPORT 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
80、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 outputPage 104REPORT YDEMOSB8.Call calculated_taxCall
81、calculated_taxSubroutineCalculate_taxCalculate taxCalculate taxREPORT YDEMOSB7.What Are SubroutinesPage 105REPORT YDEMOSB1.Form subABAP Function BuilderFunction moduleZZCALCModularizationREPORT YDEMOSB2.Perform sub(YDEMOSB1)REPORT YDEMOSB1.Perform subForm subREPORT YDEMOSB3.Call Function ZZCALCExter
82、nal CallFunctionModuleCallPage 106991a1a2a3Call Calculate_taxTransfer values of fields a1 a2Get value of field a3Actual parameters a1 a2 a3Formal parametersf1 f2f3Subroutine calculate_tax99 1f1f2f3f3 = f1 +f2 . . . .Actual / Formal ParametersParameter transferParameter transferMain Main ProgramProgr
83、amSubroutineSubroutinePage 107a1a1f1f1SubroutinePass by Value and ResultPass by Value and ResultSubroutinePass by ValuePass by Valuea1a1f1f1SubroutinePass by ReferencePass by Referencea1a1f1f1Methods of Passing ParametersPage 108REPORT Y170D091.TABLES: .DATA: .PERFORM USING .FORM USINGVALUE()VALUE()
84、.ENDFORM.Declaring and Calling a Subroutine - Pass by Value(1) & Reference(2) Pass by reference Pass by valuePage 109Pass by valueDeclaring and Calling a Subroutine - Pass by Value and Result(3)REPORT YSDEM000.TABLES: . .DATA: . .PERFORM USING CHANGING.FORM USINGVALUE()VALUE()CHANGING VALUE().f 3 =“
85、A”.ENDFORM.Pass by value and resultPage 110Global versus Local Datareporty170dm86.data: num(9) value 999999999.data:idlike tabna-id,name like tabna-name1. . . perform sub1. . . * - *FORM SUB1* -*form sub1. data:beginof tab occurs 10,“ - local dataidlike tabna-id,name1 like tabna-name1,end of tab. lo
86、cal: num .“ - local data. . . endform.Global DataLocal DataPage 111Statement Value Upon Entering Value Upon Value Upon EnteringStatement Value Upon Entering Value Upon Value Upon Enteringbetween Subroutine First Time Returning to Subroutine Nextbetween Subroutine First Time Returning to Subroutine N
87、extFORM Main Program TimeFORM Main Program TimeENDFORM ENDFORM DATADATA Whatever the local If declared Re-initializes basedWhatever the local If declared Re-initializes based DATA statement globally, returns on local DATA DATA statement globally, returns on local DATA initializes initializes to old
88、value, statement to old value, statement otherwise not otherwise not recognized recognized STATICS STATICS Whatever the local If declared Last set value fromWhatever the local If declared Last set value from STATICS statement globally, returns inside subroutine STATICS statement globally, returns in
89、side subroutine initializes initializes to old value, to old value, otherwise not otherwise not recognized recognizedLOCALLOCAL Last set value from Last set value Last set value from Last set value from Last set value Last set value from main program from main main program main program from main mai
90、n program program programLocal Data in SubroutinesPage 112REPORT 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
91、 This is passing the TABNA work area onlywork area onlyThis is passing the This is passing the ZTAB structureZTAB structurePage 113Passing Internal Tables as ParametersREPORT Y170D093.DATA : BEGIN OF TAB OCCURS 10, F1 LIKE TABNA-COUNTRY, F2 LIKE TABNA-NAME1, . . . END OF TAB.DATA : X. . . .PERFORM S
92、UB1 TABLES TAB . USING X. . .FORM SUB1 TABLES FRED STRUCTURE TAB USING Z.LOOP AT FRED.WRITE: / FRED-F1 FRED-F2.ENDLOOP.ENDFORM .Page 114External SubroutinesREPORT Y170D096.TABLES : TABNA,T001, T005.START-OF-SELECTION.PERFORMSUB1(Y170D097) . . . .REPORT Y170D097.TABLES : TABNA,T001, T001G.START-OF-SE
93、LECTION.FORM SUB1 . . . .NEW-PAGE.ENDFORMPERFORM () USING . . .Roll AreaStorage AllocationTABNATABNAT001T001T005T005T001GT001GY170D108Y170D108Y170D109Y170D109Function BuilderFunction BuilderPage 116Function ModulesFunction BuilderFM_01 .FM_02 .FM Group : FIBUProgram 1CALL FUNCTIONFM_0. . .Program 3C
94、ALL FUNCTIONFM_02. . .FM_03 .FM_04 .FM Group : XYZProgram 2CALL FUNCTIONFM_02. . .Page 117Function Module PartsFM_01 .FM_02 .FM Group : FIBUFM Group : FIBUFM_03 .FM_04 .FM Group : XYZ FM Group : XYZ Section I AdministrationSection II InterfaceChapter 1 ImportChapter 2 ChangingChapter 3 ExportChapter
95、 4 TablesChapter 5 ExceptionsSection III DocumentationSection IV Source CodeSection V Global DataSection VI Main ProgramFM -02Page 118Creating a Function GroupPage 119AdministrationPage 120InterfacesProgram XYZ.Call functionY_DEMO_FUNC Function ModuleY_DEMO_FUNCImportChangingExportTablesExceptionsPa
96、ge 121Import/Export Parameter InterfaceParameter nameLIKETYPEDefault valueFlag parameter as optionalPass parameterby referencePage 122Parameter nameLIKETYPEFlag parameter as optionalTable Parameters/Exceptions Interface & DocumentationPage 123function y_demo_function_module. -Local interface:IMPORTI
97、NGREFERENCE(FIELD1) LIKE TABNA-COUNTRYEXPORTINGVALUE(FIELD3) LIKE TABNA-NAME1TABLESTAB STRUCTURE TABNACHANGINGVALUE(FIELD2) LIKE TABNA-IDEXCEPTIONSINVALID_DATASYSTEM_ERROR -endfunction.*”*”*”*”*”*”*”*”*”*”*”*”*”*”Function Module Source CodePage 124. . . IF.RAISE INVALID_OPERATOR.* MESSAGE. . . RAISI
98、NGINVALID_OPERATOR.ENDIF. . . Function ModuleExceptionsINVALID_OPERATORPage 125case operator.when +.result = operand1 + operand2.when -.result = operand1 - operand2.when /.if operand2 0.result = operand1 / operand2.else.raise division_by_zero.endif.when result = operand1 operand2.when others.raise i
99、nvalid_operator.endcase.*Example - Raising ExceptionsPage 126Calling a Function Modulereport ymodemo message-id yj.parameters:operand1 type i,operator,operand2 like operand1.data:result type p decimals 2.call function Y_CALCULATORexportingoperand1= operand1operator= operatoroperand2= operand2importi
100、ngresult= resultexceptionsinvalid_operator= 1division_by_zero= 2others= 3.Page 127exceptionsinvalid_operator = 1division_by_zero = 2others= 3.casesy-subrc.when1.messagee001.when2.messagee005.when3.messagee007.endcase.Calling a Function Module (Continued)Page 128Program OrganisationFUNCTION FA.LU01LU
101、01FUNCTION FB.LU02LU02FUNCTION-POOL Message-ID ZZ.DATA: “Global DATALTOPLTOPLUXX INCLUDE L U01.INCLUDE L U02.*System-defined include files*User-defined include filesINCLUDE LTOP.INCLUDE LUXXSAPL SAPL Page 129Subroutine Includes for Function GroupsFORM SUB1 USING . . . .ENDFORM.FORM SUB2 USING . . .
102、.ENDFORM.FUNCTION . . .PERFORM SUB1 USING . . .ENDFUNCTION.System-defined include files INCLUDE L TOP. Global DataUser defined include files INCLUDE L F01. SubroutinesABAP program L F01CallMain ProgramMain ProgramPage 130FORM SUB1 USING.DATA: . . .MOVE. . . TO X.ENDFORM.SubroutinesL F01Global Data /
103、 Local Memory in the Function GroupFUNCTION . . .DATA: . . .MOVE X TO . . .ENDFUNCTION.ProgramGlobal DataGlobal DataFUNCTION-POOL .DATA: XTABLES: . . .L TOPPage 131Test EnvironmentExport ParametersImport parametersFM: Y170 DEMODoes it work?TablesPage 132Managing Function ModulesAdministrationAdminis
104、trationPage 133Remote Function Call (RFC)External programExternal programExternal Program. . .RfcOpen (. . .)RfcCallReceive (. . .)RfcClose (. . .)ProgramProgramCALL FUNCTION. . .DESTINATION. . .EXPORTING. . .IMPORTING. . .TABLES. . .EXCEPTIONS. . .Function GroupFunction GroupFUNCTION-POOL . . . .Function ModuleFunction ModuleFUNCTION REMOTE_CALL. . .RAISE ERROR. . .ENDFUNCTION.ABAPABAP/4/4RFCLidRFCLidPage 134Displaying Function ModulePage 135Modularization:The Include Technique