21
ABAP – SYNTAX’S 1.Data Types And Definitions 1. Defining a DATA: Syntax: DATA var[(length)] [TYPE type] [DECIMALS number] [VALUE initial value] DATA var LIKE table-field [VALUE initial value]. 2. Grouping the variables using RECORDS: Syntax: DATA BEGIN OF record name. DATA field1 TYPE. DATA field2 TYPE. . . DATA fieldn TYPE. DATA END OF record name. 1. INCLUDE STRUCTURE: Syntax: DATA BEGIN OF record name. INCLUDE STRUTURE <database table name>. DATA END OF record name. 4.User Defined DATA TYPES: Syntax: TYPES name[(length)] [TYPE type] [DECIMALS number] TYPES name LIKE table-field. TYPES: BEGIN OF rectyp. : TYPES END OF rectyp. (eg). TYPES Bank_Acct Type C. DATA Cust-Acc TYPE Bank_Acct. DATA Perso-Acc TYPE Bank_Acct. 5.CONSTANTS: Syntax: Page 1 of 21

Abap Syntax

Embed Size (px)

Citation preview

Page 1: Abap Syntax

ABAP – SYNTAX’S

1.Data Types And Definitions

1. Defining a DATA:Syntax:

DATA var[(length)] [TYPE type] [DECIMALS number] [VALUE initial value]DATA var LIKE table-field [VALUE initial value].

2. Grouping the variables using RECORDS:Syntax:

DATA BEGIN OF record name.DATA field1 TYPE.DATA field2 TYPE...DATA fieldn TYPE.DATA END OF record name.

1. INCLUDE STRUCTURE: Syntax:

DATA BEGIN OF record name. INCLUDE STRUTURE <database table name>.DATA END OF record name.

4.User Defined DATA TYPES:Syntax:

TYPES name[(length)] [TYPE type] [DECIMALS number] TYPES name LIKE table-field.TYPES: BEGIN OF rectyp.:TYPES END OF rectyp.

(eg).TYPES Bank_Acct Type C.DATA Cust-Acc TYPE Bank_Acct.DATA Perso-Acc TYPE Bank_Acct.

5.CONSTANTS:Syntax:

CONSTANTS var[(length)] [TYPE type] [DECIMALS number] VALUE initial value [IS INITIAL].

CONSTANTS var LIKE table-field VALUE initial value [IS INITIAL].CONSTANTS: BEGIN OF rec.

………END OF rec.

Page 1 of 15

Page 2: Abap Syntax

6.RUNTIME PARAMETERS.Syntax:

a. PARAMETERS param[(length)] [TYPE type] [LIKE field] [DEFAULT val] [LOWER CASE] [AS CHECKBOX] [RADIOBUTTON GROUP num] [OBLIGATORY].

b.SELECT – OPTIONS:Syntax:

SELECT–OPTIONS var FOR field [DEFAULT val] [DEFAULT val option][DEFAULT [NOT] val TO val] [MEMORY ID id][MATCHCODE OBJECT object] [LOWER CASE][NO INTERVALS] [NO EXTENSION] [OBLIGATORY].

7.RANGES:Syntax:

RANGES var FOR field [DEFAULT val] [DEFAULT val option][DEFAULT [NOT] val TO val]

8.FIELD – SYMBOLS:Syntax: FIELD–SYMBOLS <fs>.9.Assigining Values To Variables Using MOVE.Syntax:

MOVE value TO var.Var = value.MOVE P_INT_EMP[] TO W_INT_EMP[].

2.Displaying and Printing Data (Formatting ) :

1. WRITE:Syntax:

WRITE /column position(length) data.2. Advanced Features of WRITE:Syntax:

WRITE filed [USING EDIT MASK mask] [USING NO EDIT MASK mask][NO-ZERO] [NO-SIGN] [DD/MM/YY] [DD/MM/YYYY] [MM/DD/YY] [MM/DD/YYYY] [CURRENCY currency].

3. SKIP & POSITION:Syntax:

SKIP. ( To skip few lines).POSITION n. (Decides where the position of the cursor is to be placed)

2. Displaying MESSAGE:Syntax:

MESSAGE message type message number [WITH text].5.Formatting Commands:Syntax:

FORMATT [INTENSIFIED] [INTENSIFIED OFF](for making text appear Bold)[COLOR color] [COLOR OFF][INVERSE] [INVERSE OFF] (to make background color as

foreground color and vice-versa)[RESET].

Page 2 of 15

Page 3: Abap Syntax

3. Manipulating Data.

1.Working With Numeric Data:Syntax:

COMPUTE var = expression.ADD value TO var. (var = var + value)SUBTRACT value FROM var. (var = var - value)MULTIPLY value BY var. (var = var * value)DIVIDE value BY var. (var = var / value)

Using Sequential ADD:ADD field1 then field2 UNTIL fieldn [TO var] [GIVING var].

Using CORRESPONDONG Command.ADD-CORRESPONDING rec1 TO rec1.SUBTRACT-CORRESPONDING rec1 FROM rec1.MULTIPLY -CORRESPONDING rec1 BY rec1.DIVIDE-CORRESPONDING rec1 BY rec1.

2. Manipulating With Strings:. SUBSTRINGS:Syntax: Var+offset(length).

(eg) varb = ‘123456’MOVE ‘x’ to varb+3(2) will give the o/p 123x_6.

SHIFTSyntax: SHIFT var [CIRCULAR] [RIGHT] [LEFT]. SHIFT var BY n PLACES [CIRCULAR] [RIGHT] [LEFT]. SHIFT var UP TO character [CIRCULAR] [RIGHT] [LEFT]. SHIFT c LEFT DELETING LEADING val. SHIFT c RIGHT DELETING TRAILING val. TRANSLATESyntax: TRANSLATE var to UPPER CASE. TRANSLATE var to LOWER CASE. TRANSLATE var USING string. ( To replace a single character with another.) OVERLAYSyntax: OVERLAY var1 WITH var2. [only var3] REPLACESyntax: REPLACE string1 WITH string2 INTO temp.[LENGTH len] SEARCHSyntax SEARCH var FOR string [ABBREVIATED] [STARTING AT num]

[ENDING AT num] [AND MARK] .

Page 3 of 15

Page 4: Abap Syntax

SPLITSyntax: SPLIT str AT char INTO var1, var2, … varn.

SPLIT str AT char INTO TABLE itab. CONCATENATESyntax: CONCATNATE var1 var2 var3 into var4 [SEPARATED BY char] CONDENCESyntax: CONDENCE var [NO-GAPS].

4 Using Conditional Operators:Comparing Character Fields:

1. CO (Contains Only)2. CA (Contains Any)3. CS (Contains String)4. CP (Contains Pattern).

6 Working With Internal Tables:type 1: DATA: BEGIN OF ITAB OCCURS N.

F1 TYPE C, F2 TYPE N.

DATA: END OF ITAB.The OCCURS parameter n defines how many tables lines are created

initially. If necessary, you can increase the size later. Otherwise, the OCCURS parameter is of no significance.

DATA: BEGIN OF LINETYPE,NAME (25) TYPE C,AGE TYPE I,END OF LINETYPE.

DATA: PERSON LIKE LINETYPE OCCURS 20 WITH HEADER LINE

Inserting a record to Internal table

PERSON-NAME = ‘MICHAEL’.PERSON-AGE = ‘25’.APPEND PERSON. - Insert a record into the internal table.CLEAR PERSON. - Clear the record from the header line.

To read a record from the Internal table

READ TABLE ITAB.READ TABLE ITAB INTO WA.READ TABLE ITAB WITH KEY K1 = V1 K2 = V2 … KN=VN

READ TABLE ITAB INDEX idx.

To Sort an Internal tableSORT ITAB.SORT ITAB BY f1 f2 …fn.

Page 4 of 15

Page 5: Abap Syntax

SORT ITAB DESCENDING SORT ITAB ASCENDING

To Loop through the internal table.

LOOP AT ITAB.LOOP AT ITAB INTO WA.LOOP AT ITAB FROM n1 TO n2.

Places all internal table entries from the entry with the index ( SY-TABIX ) = n1 to the entry with the index = n2 inclusive in the output area in turn. NoteIf either one of the additions " FROM n1 " or " TO n2 " is missing, then the table is processed either from the first entry or up to the last entry (according to what is missing).

ExampleOutput table entries 7 and 8:

DATA: BEGIN OF T OCCURS 100, BAREA (5), BLNCE (5), END OF T.

LOOP AT T FROM 7 TO 8. WRITE: / T-BAREA, T-BLNCE.ENDLOOP.

LOOP AT INTAB WHERE log exp.

Example.LOOP AT T WHERE BAREA > 0. WRITE: / T-BAREA, T-BLNCE.ENDLOOP.

which has the same effect as:

LOOP AT T. CHECK T-BAREA > 0. WRITE: / T-BAREA, T-BLNCE.ENDLOOP.

To append a record into the internal table

APPEND [wa TO|INITIAL LINE TO] itab. APPEND LINES OF itab1 [FROM idx1] [TO idx2] TO itab2. APPEND [wa TO] itab SORTED BY f.

Appends a new line to the end of the internal table itab .

If you specify wa TO , the new line is taken from the contents of the explicitly specified work area wa .

Page 5 of 15

Page 6: Abap Syntax

If you use INITIAL LINE TO , a line filled with the correct value for the type is added.

If the specification before itab is omitted, the new line is taken from the internal tbale itab .

After the APPEND , the system field SY-TABIX contains the index of the newly added table entry.

Examples

Generate a list with customer numbers:

TABLES SCUSTOM.DATA: CUSTOMER LIKE SCUSTOM-ID OCCURS 0.

APPEND SCUSTOM-ID TO CUSTOMER.

Append a blank line or a line with its initial value to the above list:

APPEND INITIAL LINE TO CUSTOMER

Type 2:APPEND LINES OF itab1 [FROM idx1] [TO idx2] TO itab2.

EffectAppends the internal table itab1 or an extract from itab1 to the end of the internal table itab2. By specifying FROM idx1 or TO idx2 you can restrict the line area taken from the source table itab1. If there is no FROM specification, it begins with the first line of itab1. If there is no TO specification, it ends with the last line of itab1. This means that the complete table is appended if neither a FROM nor a TO is specified.

After the APPEND , the system field SY-TABIX contains the index of the last table entry appended, i.e. the total number of entries from both tables. NoteBy comparing the values of SY-TABIX before and after the APPEND statement, you can determine how many lines were appended to the table. ExampleMerge two tables with whole numbers:

DATA: ITAB1 TYPE I OCCURS 100, ITAB2 TYPE I OCCURS 100.

APPEND 2 TO ITAB1.APPEND 3 TO ITAB1.APPEND 5 TO ITAB1.APPEND 7 TO ITAB1.

APPEND 3 TO ITAB2.APPEND INITIAL LINE TO ITAB2.

Page 6 of 15

Page 7: Abap Syntax

APPEND LINES OF ITAB1 FROM 2 TO 20 TO ITAB2.

The table ITAB2 now contains five lines with the values 3, 0, 3, 5 and 7.

NotePerformance

This variant is 3 to 4 times faster than using a LOOP to process the source table and append the entries line-by-line to the target table.

Type 3APPEND [wa TO] itab SORTED BY f. EffectInserts the new entry into table and re-sorts the table by the sub-field f in descending order. This only makes sense if the table was sorted beforehand. When the number of table entries reaches the OCCURS parameter value, the last entry is deleted if the value f of a new entry is greater (particularly suitable for ranked lists). You can only sort by one sub-field.

If you specify wa TO , the new line is taken from the contents of the explicitly specified work area wa . Otherwise, it comes from the header line of the internal table itab . Example

DATA: BEGIN OF COMPANIES OCCURS 3, NAME(10), SALES TYPE I, END OF COMPANIES.

COMPANIES-NAME = 'big'.COMPANIES-SALES = 90.APPEND COMPANIES.

COMPANIES-NAME = 'small'.COMPANIES-SALES = 10.APPEND COMPANIES.

COMPANIES-NAME = 'too small'.COMPANIES-SALES = 5.APPEND COMPANIES.

COMPANIES-NAME = 'middle'.COMPANIES-SALES = 50.APPEND COMPANIES SORTED BY SALES.

The table now has three (-> OCCURS 3 ) entries. The line with the contents 'too small' in the sub-field NAME is deleted from the table because the entry for 'middle' has a greater value in the sub-field SALES . This entry now appears in the second table line (after 'big' and before 'small' ).

Notes

Page 7 of 15

Page 8: Abap Syntax

Whenever an internal table is processed with APPEND SORTED BY , it should always be filled in this way. If you specify APPEND with the parameter SORTED BY , the system always searches the entire table. Therefore, it is sometimes better to create the table with a simple APPEND and then use SORT to sort in descending ot ascending order afterwards.

To Delete a record from the Internal table

1. DELETE itab. 2. DELETE itab INDEX idx. 3. DELETE itab FROM idx1 TO idx2. 4. DELETE itab WHERE condition. 5. DELETE ADJACENT DUPLICATES FROM itab.

Deletes one or more lines from an internal table. NoteThe deletion of lines within a LOOP ... ENDLOOP loop is performed in a sequence of loop passes.

Variant 1DELETE itab. EffectThe current entry of the internal table itab is deleted in a LOOP loop. Return code value The is set to 0. NoteAfter deleting the current entry in an internal table in a LOOP loop, the effect of further update operations on the current entry without an INDEX specification is not guaranteed and may changed in later Releases.

Variant 2DELETE itab INDEX idx. EffectDeletes the idx entry from the internal table itab .

The return code value is set as follows:

SY-SUBRC = 0 The entry was deleted. SY_SUBRC = 4 The entry does not exist.

Variant 3DELETE itab FROM idx1 TO idx2. EffectDeletes the line area from index idx1 to idx2 from internal table itab . At least one of the two parameters FROM idx1 or TO idx2 should be specified. If parameter FROM is missing, the area from the start of the table to line idx2 is deleted. If parameter TO is missing, the area from line idx1 to the end of the table is deleted. Start index idx1 must be greater than 0.

Page 8 of 15

Page 9: Abap Syntax

The return code value is set as follows:

SY-SUBRC = 0 At least one entry was deleted. SY_SUBRC = 4 None of the entries were deleted.

Variant 4DELETE itab WHERE condition. Additions

1. ... FROM idx1 2. ... TO idx2 EffectDeletes all entries from internal table itab, which satisfies the condition.

The return code value is set as follows:

SY-SUBRC = 0 At least one entry was deleted. SY_SUBRC = 4 None of the entries were deleted.

Addition 1... FROM idx1 Effect

The line area to be investigated is restricted to the lines up to index idx1 . If the addition FROM idx1 is missing, a search is carried out from the beginning of the table. The addition FROM must come before the WHERE condition.

Addition 2... TO idx2

EffectRestricts the line area to be investigated to the lines up to index idx2 . If the addition TO idx2 is missing, a search is carried out until the end of the table. The addition TO must come before the WHERE condition. ExampleDelete all lines in a name table between lines 5 and 36, if the entry begins with one of the letters 'A' to 'C' :

DATA: BEGIN OF NAMETAB OCCURS 100, NAME(30) TYPE C, END OF NAMETAB....DELETE NAMETAB FROM 5 TO 36 WHERE NAME CA 'ABC'.

Variant 5DELETE ADJACENT DUPLICATES FROM itab.

Additions1. ... COMPARING f1 f2 ... 2. ... COMPARING ALL FIELDS

Page 9 of 15

Page 10: Abap Syntax

EffectDeletes neighboring, duplicate entries from the internal table itab . If there are n duplicate entries, the first entry is retained and the other n - 1 entries are deleted.

Two lines are considered to be duplicated if their default keys match.

The return code value is set as follows:

SY-SUBRC = 0 At least one duplicate exists, at least one entry deleted. SY_SUBRC = 4 No duplicates exist, no entry deleted.

Addition 1... COMPARING f1 f2 ... EffectTwo lines of the internal table itab are considered to be duplicates if the specified fields f1 , f2 , .... match. Addition 2... COMPARING ALL FIELDS EffectTwo lines are considered to be duplicates if all fields of the table entries match. NotesThe DELETE ADJACENT DUPLICATES statement is especially useful if the internal table itab is sorted by fields (whether in ascending or descending order), which were compared during duplicate determination

7 Working With Data Dictionary:

Domain Is an Object to describe the type of field in which data resides. Eg Car Data Element This describes what resides inside the Domain. Eg Maruthi-800. Fields These are the basic description of under which group data resides. eg Sedan

8. SAP SQL. Various Types of queries:

Select:1. SELECT MANDT BUKRS BELNR INTO TABLE INT_TAB FROM BKPF.

WHERE BUKRS = 'R300'.

2. SELECT * FROM BKPS INTO TABLE INT_TAB.

3. SELECT * FROM BKPS INTO TABLE INT_TAB

WHERE BUKRS = 'R300'

4. SELECT SINGLE * FROM BKPS INTO TABLE INT_TAB.

5. SELECT SUM( SALARY ) DEPT_NO INTO (GRPSAL,DEPTNO)

FROM ZBALA_EMP

GROUP BY DEPT_NO.

6. SELECT * FROM EKPO WHERE EBELN BETWEEN ‘0000454’ AND ‘0000894’

AND WERKS IN ( ‘P002, ‘P003’, ‘P005’ ).

Page 10 of 15

Page 11: Abap Syntax

ENDSELECT.

7. SELECT VBAP~VBELN VBAP~POSNR VBAP~MATNR PLAF~PLNUM INTO (XVBELN,XPOSNR,XMATNR,XPLNUM)

FROM ( PLAF INNER JOIN VBAP ON PLAF~KDAUF = VBAP~VBELN

AND PLAF~KDPOS = VBAP~POSNR ) WHERE VBAP~VBELN = '7262'.

8. SELECT-OPTIONS IENO FOR ZBALA_EMP-EMPNO.

SELECT * FROM ZBALA_EMP INTO TABLE INT_TAB

WHERE EMPNO IN IENO.

Insert:1. INSERT INTO ZBALA_EMP values INT_BALA.

2. INSERT

3. INSERT

Update:1. UPDATE BKPF SET BELNR = ‘1111’ WHERE BUKRS = 'R300'.

2. UPDATE BKPF FROM INT_TAB.

Delete:1. DELETE BKPF.

2. DELETE FROM BKPF WHERE BUKRS = 'R300'.

3. DELETE BKPF FROM INT_TAB.

9. Working with External Files:

REPORT ZBALA0705_01 .

TABLES: ZEMP.*----------------------------* Data Declaration.*----------------------------DATA: BEGIN OF INT_TAB OCCURS 0. INCLUDE STRUCTURE ZEMP.DATA: END OF INT_TAB.

DATA: W_DATAFILENAME(50) TYPE C VALUE 'SARA.TXT'.DATA: W_MESSAGE(100) TYPE C.*----------------------------* Data Selection*---------------------------- SELECT * FROM ZEMP INTO TABLE INT_TAB.*----------------------------------* Open a file for writing.*----------------------------------OPEN DATASET W_DATAFILENAME FOR OUTPUT IN TEXT MODE.*-------------------------------* Loop Thru the Record*-------------------------------LOOP AT INT_TAB. TRANSFER INT_TAB TO W_DATAFILENAME.ENDLOOP.

Page 11 of 15

Page 12: Abap Syntax

*-------------------------------* Close the file AND refersh the internal table.*-------------------------------REFRESH INT_TAB.CLOSE DATASET W_DATAFILENAME.*---------------------------------* open the file for reading*---------------------------------DATA: R_COUNT TYPE I.

OPEN DATASET W_DATAFILENAME FOR INPUT IN TEXT MODE MESSAGE W_MESSAGE.

WHILE SY-SUBRC EQ 0. READ DATASET W_DATAFILENAME INTO INT_TAB. COMPUTE R_COUNT = R_COUNT + 1. APPEND INT_TAB. CLEAR INT_TAB.ENDWHILE.

WRITE: /20 'FILE READ FROM THE DATA FILE SARA.TXT'.ULINE.

LOOP AT INT_TAB. WRITE: /20 INT_TAB.ENDLOOP.

WRITE: /20 'No of records :', R_COUNT.*---------------------------------* Close the file.*---------------------------------

CLOSE DATASET W_DATAFILENAME.

13. Working With Logical Database:

A Logical Database provides access to a group of tables. It takes care of all the necessary joins needed to access all the tables. To start with we have to go to the menu option Goto -> Attributes: and set the logical database using it’s 3 character identification we needed.

The commands available are - 1. GET <table name>.2. GET <table name> LATE.3. CHECK <expression>. Used to limit the amount of data to be returned.

14. Writing A Report:

Some of the tables:

1. BKPF - Accounting Document Header 2. BSEG - Accounting Document Segment3. KNA1 - General Data in Customer Master

Page 12 of 15

Page 13: Abap Syntax

4. VBPA - Sales Document : Partner5. VBRP – Billing : Item Data.6. BSIS – Accounting : Secondary Index for G/L Accounts.

(Contains data from BKPF and BSEG .)

Points to be noted down before starting to write a Report:

1. Verify the Data2. Data Selection.

Choosing the correct table. Determining the Order in which data has to be selected. Determine whether to choose Internal Table or Field-Group to use

1. If data to be retrieved is of very large volume use Field-Group2. Else use Internal Table.

Specify the Data Types of the data that is to be used.

15. Writing A Data Extract:

16. Writing A BDC Program:

A BDC (Batch Data Communication) session is a combination of ABAP/4 programming and built-in SAP functionality. It simulates the act of a user entering data into an SAP transaction. The system would take the data from an ABAP/4 pgm and feed to an SAP transaction screen by screen.

Transaction Code SHDB

Steps Involved in writing a BDC program:

BDC-OKCODEBDC-CURSOR. Structure of BDCDATA:Program To store the Transaction Name.Dynpro To store Screen Number.Dynbegin To indicate the screen begins. (Default value is ‘X’).Fnam To store the field name.Fval To store the field value.

Submitting the BDC Table:1. Through CALL TRANSACTION command (Processes one transaction at a time)Syntax;

CALL TRANSACTION trans [USING bdctab MODE mode] [UPDATE upd][MESSAGES INTO messtab].

Page 13 of 15

Page 14: Abap Syntax

2. Through BDC_INSERT (Processes multiple transaction at a time).Syntax:

BDC_OPEN_GROUP.BDC_INSERT.BDC_CLOSE_GROUP

17. SAP Security & Authorization:

Security is referred to as Authorizations and the ability to perform an operation in the system is to referred to as Authorization Object.

Authorizations Restricts the access to the user.Authorization Object Grants the ability to perform the operation.Authorization Fields Each Authorization Object will contain up to 10

Authorization Fields and each field will corresponds to a SAP data element.

User Master Record Each user will contain a master record that contains all the Authorization that he can perform.

Authority-Check This command checks whether user is authorized or not.

18. ABAP Debugger:

19. Performance Analysis:

1. Runtime Analysis Tool. (SE30):2. SQL Trace. (ST05):

20. Performance Tuning:

Tips for writing a Sql-Query:1. Always specify your conditions in the where-clause instead of checking with

check-statements2. When we r sure that we r going to get only one record it is better use Single

Command because it requires one communication with the database system where as the Select-Endselect needs two.

3. Use a select list or a view instead of Select *.4. Use sub queries instead of using nested Select loops.5. It is always faster to use the Into Table version of a Select statement than to use

Append statements.

ADVANCED ABAP

1. Selection Screen Controls:

Page 14 of 15

Page 15: Abap Syntax

1. To Generate Titles and Boxes:Syntax:

SELECTION-SCREEN BEGIN OF BLOCK block1 <WITH FRAME> <TITLE title1 ><NO INTERVALS>

PARAMETERS SELECTION-SCREEN COMMENT <format> <name>

[FOR FIELD fldname]

SELECTION-SCREEN ULINE. SELECTION-SCREEN PUSHBUTTON<format> <name>

USER-COMMAND <ucom>. SELECTION-SCREEN POSITION num. SELECTION-SCREEN END OF BLOCK block1.2.To Skip lines:Syntax. SELECTION-SCREEN SKIP num.3.To Create Push Buttons on the ToolBar:Syntax: SELECTION-SCREEN FUNCTION KEY num.

2. Function Modules:Steps involved are:

1. Go to the Transaction screen se37.2. Create a function group, and then create a function module under that

group.3. Set the Import and Export values.4. Save and activate the transaction.5. Go to se38 create open program and click the Pattern option in the menu

to inherit the written function module.6. Execute to get the output.

3. Remote Function Calls:Steps involved are: Let Us consider the port 800 as server and 810 as Client.

Server Side1. We will have our Remote Function residing here. 2. After competing the RF we have to release it.3. Go to the Transaction SM59 Create an RFC Destination under R/3

connection. Point the client port no 800 in that screen.Client Side1. We will have our Calling Program residing here. 2. In the Call Function we have to add

Destination ‘< RFC Destination name>’.3. Execute the pgm.

Page 15 of 15