open sql and internal tables

48
ABAP Training

Upload: rajesh-kumar

Post on 22-Nov-2015

65 views

Category:

Documents


0 download

DESCRIPTION

Open SQL

TRANSCRIPT

OPEN SQL STATEMENTS

ABAP Training

OPEN SQL

1) Open SQL is a set of ABAP statements that performs operations like Read, Modify or Delete data in the SAP database. 2) Open SQL is independent of the database system, so the syntax of the open SQL is uniform for all the databases supported by SAP.3) All open SQL statements are passed to the database interface. The DB interface converts the open SQL to native SQL and passes it on to the database. 4) Using Open SQL enables you to access any database tables available to the SAP system regardless of the manufacturer be it Oracle, Informix etc.5) The difference between Open SQL and Native SQL is as follows: A database interface translates SAPs Open SQL statements into SQL commands specific to the database in use. Native SQL statements access the database directly.

Use of Open SQL

List of OPEN SQL Statements

Return CodesSY-SUBRC : AftereveryOpen SQL statement, the system field SY-SUBRC contains the value 0 if the operation was Successful, a value other than 0 if not.2) SY-DBCNT : After an open SQL statement, the system field SY-DBCNT contains the Number of database lines processed.

Memory Space

Internal Tables 1) Aninternal tableis a Temporary table stored in RAM on the application server.

2) It is created and filled by a program during execution and is discarded when the program ends.

3) Like a database table, an internal table consists of one or more rows with an identical structure, but unlike a database table, it cannot hold data after the program ends. Use it as temporary storage for manipulating data or as a temporary private buffer.

4) An internal table consists of a body and an optional header line.

5) Thebodyholds the rows of the internal table. All rows within it have the same structure. The term "internal table" itself usually refers to the body of the internal table.

6) Theheader lineis a field string with the same structure as a row of the body, but it can only hold a single row. It is a buffer used to hold each record before it is added or each record as it is retrieved from the internal table.

Internal Tables To define an internal table body, useOCCURS Non the definition of any field string excepttables.occurscreates the body of the internal table. The memory for the body is not allocated until the first row is added to it. Withoutoccurs, you only have a field string. To define an internal table with a header line, you must include eitherbegin oforwith header linein the definition. A header line is automatically created ifbegin ofappears in the definition. If you uselikeinstead ofbegin of, the internal table will not have a header line unless you addwith header lineafter theoccursclause.10) The only time you would create an internal table without a header line is in the case of a nested internal table. A nested internal table cannot have a header line.

Internal Tables Basic Ways of Defining Internal Tables with and Without a Header Line. Report ztx1101. data: begin of it1 occurs 10, "has a header line 3 f1, 4 f2, 5 f3, 6 f4, end of it1. data: it2 like ztxlfa1 occurs 100. "doesn't have a header line data: it3 like ztxlfa1 occurs 100 with header line. "it does now Append Statement a) To add a single row to a internal table, you can use theappendstatement. b) Appendcopies a single row from any work area and places it in the body at the end of the existing rows. c) The work area can be the header line, or it can be any other field string having the same structure as a row in the body. Syntax for the append Statement : append [wa to] [initial line to] it. The statementappend initial line to itappends a row containing initial values (blanks and zeros) to the internal table. It is the same as executing the following two statements in succession:clear itandappend it.

Append Statement Afterappend,sy-tabixis set to the relative row number of the row just appended. For example, after appending the first row,sy-tabixwill be set to1. After appending the second row,sy-tabixwill be2, and so on. Example: Report ztx1103. data: begin of it occurs 3, f1(1), f2(2), end of it. it-f1 = 'A'. it-f2 = 'XX'. append it to it. "appends header line IT to body IT write: / 'sy-tabix =', sy-tabix. it-f1 = 'B'. it-f2 = 'YY'. append it. Append Statement write: / 'sy-tabix =', sy-tabix. it-f1 = 'C'. append it. "the internal table now contains three rows. write: / 'sy-tabix =', sy-tabix. Output: sy-tabix = 1 sy-tabix = 2 sy-tabix = 3 .

NOTE : The statementappend it to itappends the header line nameditto the body namedit. The statementappend itdoes the same thing, because the default work area is the header line.

Using the occurs Addition

a) Occursdoes not limit the number of rows that can be added to the internal table. For example, if you specifyoccurs 10, you can put more than 10 rows into the internal table. The number of rows you can put into an internal table is theoretically only limited by the amount of virtual memory available on the application server. b) Alternatively, you can specifyoccurs 0. If you do this, the system allocates 8KB pages of memory at a time. c) For peak performance and minimum wasted memory, choose anoccursvalue equal to the average maximum number of rows in the table. For example, if most of the time the internal table is filled with a maximum of 100 rows, but every once in a while it is filled with a maximum of 1,000 rows, set theoccursvalue to 100.

Reading Data from an Internal Table

Two statements are commonly used to read the data from an internal table: a) loop at b) read tableUseloop atto read multiple rows from the internal table. Useread tableto read a single row.

To read some or all rows from an internal table, you can use theloop atstatement.Loop atreads the contents of the internal table, placing them one at a time into a work area.

LOOP AT SYNTAX loop at it [into wa] [from m] [to n] [where exp]. end loop.

Iffromis not specified, the default is to begin reading from the first row.Iftois not specified, the default is to read to the last row. This Program Adds 3 Rows to Internal Table it from the Header Line.

LOOP AT Example report ztest1. data: begin of it occurs 3, f1(1), f2(2), end of it. it-f1 = 'A'. it-f2 = 'XX'. append it to it. "appends header line IT to body IT it-f1 = 'B'. it-f2 = 'YY'. append it. "same as line 8 it-f1 = 'C'. append it. "the internal table now contains three rows. sy-tabix = sy-subrc = 99. loop at it. "same as: loop at it into it write: / sy-tabix, it-f1, it-f2. end loop. write: / 'done. sy-tabix =', sy-tabix, / ' sy-subrc =', sy-subrc. Statements that Can Alter Loop Processing for Internal Tables 1) Exit Terminates the loop immediately. Processing continues at the statement immediately followingend loop.

Continue Goes immediately to theend loopstatement, bypassing all following statements within the loop. The next row is returned from the internal table and processing continues from the top of the loop. If there are no more rows to retrieve, processing continues at the first statement followingend loop.

3) Checkexp Ifexpis true, processing continues as if this statement had not been executed. If expis false, its effect is the same ascontinue.

Internal Tables

Types of Internal Tables

Difference of Internal Tables

Reading DataThe Open SQL statement for reading data from database tables is: SELECTINTOFROM[WHERE][GROUP BY ][HAVING ][ORDER BY ]. The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database. Reading Data

SELECT STATEMENT Group By Clause: The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.SYNTAX: SELECT [column-name1], [column-name2], aggregate_function (expression) ... FROM table-name WHERE [search-condition] GROUP BY [column-name1], [column-name2] ... ] ORDER BY [column-name1], [column-name2] [DESC] ] ... ;NOTE: Aggregate_functioncan be a function such asSUM,COUNT,MIN, orMAX.

Aggregate Functions

GROUP BY CLAUSEExamples: SELECT DEPT, AVG(SALARY) FROM EMPLOYEE GROUP BY DEPT ; DEPT AVG(SALARY) MKT 33500 MGT 45000 LIB 22000 RND 27500 FIN 420002) SELECT DEPT, BENEFITS, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT, BENEFITS ; GROUP BY CLAUSE DEPT BENEFITS SUM(SALARY) FIN FULL 42000 LIB PART 22000 MGT FULL 45000 MKT FULL 67000 RND FULL 30000 RND PART 25000Having Clause The having clause is usedwiththe group by clause when comparisons need to be made with those aggregate functions . SYNTAX: SELECTlines s1[AS a1] s2[AS a2]...agg sm[AS am] agg sn[AS an] GROUP BY s1s2.... HAVING cond. EXAMPLE: 1) select employee, sum(bonus) from emp_bonus group by employee having sum(bonus) > 1000. 2) SELECT customer, sum(salesamount) FROM sales GROUP BY customer HAVING sum(salesamount) > 10000;

Order By Clause The order by clause is used to sort the query result sets in either ascending or descending order. It is used in conjunction with the SELECT query. It has the following basic syntax. SYNTAX : SELECT statement... WHERE condition GROUP BY `fieldname(s)` HAVING [condition] ORDER BY `field_name(s)` [ASC | DESC]. NOTE : ASCis used as the default.Example: SELECT * FROM `members` ORDER BY `gender`,`date_of_birth` DESC.

Different Types of SELECT StatementsThe SELECT clause can be divided into two parts for lines and columns: SELECT ... a) specifies whether you want to read one or more lines. b) defines the column selection.Reading a Single Line : SELECT SINGLE ... WHERE ... Note:When ever we use select single, we must pass key field in where condition. **Declare internal table DATA : WA_MARA TYPE TABLE OF MARA. *use select * to read data SELECT SINGLE * FROM MARA INTO WA_MARA WHERE MATNR = '000001'. .

SELECT STATEMENTS2) using select * in sap abap. Select * is a statement which is used to read whole data from a database table. Example: **Declare internal table DATA : IT_MARA TYPE TABLE OF MARA. *use select * to read data SELECT * FROM MARA INTO TABLE IT_MARA .To get data based on a condition with all fields(columns) from Database table.

Declare internal table DATA : IT_MARA TYPE TABLE OF MARA. Read data SELECT * FROM MARA INTO TABLE IT_MARA WHERE MTART = 'FERT' .

SELECT STATEMENTS4) using select max in sap abap . NOTE : By using this query we can get highest numeric value of a column in SAP Database tables.SYNTAX: SELECT MAX( ) INTO () FROM .Example: DATA: LV_MAX TYPE LIFNR. SELECT MAX( LIFNR ) INTO (LV_MAX) FROM LIFNR . WRITE:/ LV_MAX.5) using select min in sap abap. NOTE: By using this query we can get minimum value of a column in SAP database table.

SELECT STATMENTSSyntax: SELECT MIN( ) INTO () FROM .Example : DATA LV_MIN TYPE LIFNR. SELECT MIN( LIFNR ) INTO (LV_MIN) FROM LFA1 . WRITE:/ LV_MIN.6) using select up to in sap abap . NOTE: BY using Select Up To query we will get the specific no of records from a data base table, it will get records from starting ( beginning ).Syntax : select * FROM INTO TABLE UP TO rows. Example: data : it_mara type TABLE OF mara. **Get 50 rows form startingselect * FROM mara INTO TABLE it_mara UP TO 50 rows.

SELECT STATEMENTS7) using select distinct in sap abap.

NOTE: Select Distinct is used to get distinct (unique) values of a particular column in SAP ABAP.Syntax: SELECT DISTINCT FROM INTO TABLE .

Example : REPORT ZSAPN_SELECT_DISTINCT .

TYPES: BEGIN OF TY_MARA, MTART TYPE MARA-MTART, END OF TY_MARA.

DATA : IT_MARA TYPE TABLE OF TY_MARA.DATA : WA_MARA TYPE TY_MARA.

SELECT DISTINCT MTART FROM MARA INTO TABLE IT_MARA.

LOOP AT IT_MARA INTO WA_MARA. WRITE:/ WA_MARA-MTART.ENDLOOP.

SELECT STATMNTS 8) using select order by in sap abap. NOTE: SELECT ORDERBY is used to fetch data from database table with sorted result set, by default the result will be sorted in ascending order, to sort in descending order you have to specify. Syntax: SELECT * FROM INTO TABLE ORDER BY ASCENDING/DESCENDING. Example: REPORT ZSAPN_SORT_ASCENDING . DATA : IT_MARA TYPE TABLE OF MARA. DATA : WA_MARA TYPE MARA. SELECT * FROM MARA INTO TABLE IT_MARA ORDER BY MATNR ASCENDING. LOOP AT IT_MARA INTO WA_MARA. WRITE:/ WA_MARA-MATNR. ENDLOOP.

SELECT STATEMENTS NOTE: The above statement is educational purpose only, in your real-time projects don`t use SELECT ORDERBY, it decreases performance of a program, instead use SORT after fetching data. SORT ASCENDING/DESCENDING.9) using wildcards in selects. SQL Wildcards are used to search for data in a database table, below are the examples of using wildcards in SAP ABAP.

Wild Card Characters

Wild Card Characters REPORT ZSAPN_WILDCARDS. DATA : IT_MARA TYPE TABLE OF MARA. DATA : WA_MARA TYPE MARA. SELECT * FROM MARA INTO TABLE IT_MARA WHERE matnr LIKE '11%'. LOOP AT IT_MARA INTO WA_MARA. WRITE:/ WA_MARA-MATNR. ENDLOOP.

SELECT FOR ALL ENTRIES9) Syntax FOR ALL ENTRIES IN itab WHERE ... coloperatoritab-comp ... 'FOR ALL ENTRIES' is used with internal tables. when u need data from three tables .

1) Retrieving of data from 3 tables we can use Inner Join or For All Entries. Comparing to Inner Join is always good to use FOR ALL ENTRIES option Performance increase. 2) Declare all primary keys of your database table in your select statement. It ensures that you have no duplicates in you hit list.

3) Check that the table used in the "For all entries" statement is not empty. This avoids executing the select statement if no result is expected.

FOR ALL ENTRIESPARAMETERS: p_city TYPE spfli-cityfrom.

TYPES: BEGIN OF entry_tab_type, carrid TYPE spfli-carrid, connid TYPE spfli-connid, END OF entry_tab_type.

DATA: entry_tab TYPE TABLE OF entry_tab_type, sflight_tab TYPE SORTED TABLE OF sflight WITH UNIQUE KEY carrid connid fldate.

SELECT carrid connid FROM spfli INTO CORRESPONDING FIELDS OF TABLE entry_tab WHERE cityfrom = p_city.

SELECT carrid connid fldate FROM sflight INTO CORRESPONDING FIELDS OF TABLE sflight_tab FOR ALL ENTRIES IN entry_tab WHERE carrid = entry_tab-carrid AND connid = entry_tab-connid.INSERT STATEMENT The INSERT statement is used to insert values into a single database table. SYNTAX: 1) INSERT FROM . 2) INSERT INTO VALUES . Example: TABLES SPFLI. DATA WA TYPE SPFLI. WA-CARRID = 'LH'. WA-CITYFROM = 'WASHINGTON'. ... INSERT INTO SPFLI VALUES WA. WA-CARRID = 'UA'. WA-CITYFROM = 'LONDON'. ... INSERT SPFLI FROM WA. SPFLI-CARRID = 'LH'. SPFLI-CITYFROM = 'BERLIN'. ... INSERT SPFLI.

UPDATE STATEMENT a)The UPDATE statement allows updating the values of selected columns of rows of a database table. b) Updates an existing record to the table. If the row (key) does not exist, issues an error. SYNTAX: UPDATESET() .

Example : 1) UPDATE PA0003 SET UNAME = SY-UNAME.

2) UPDATEemployees SETemployee_name = 'Mary Jones'WHEREemployee_id = 23 .

MODIFY STATEMENT 'MODIFY' statement changes the content of one or several internal table lines that can be specified using the table key or the table index . SYNTAX: MODIFY TABLE itab FROM wa [TRANSPORTING f1f2...].

data: idx type sy-tabix. data: itab type standard table of t508a. data: wa_tab type t508a.select * from t508a into table itabwhere zeity = '1' and mofid = '11'.

Modify Statement loop at itab INTO WA_TAB. idx = sy-tabix. WA_TAB-ENDDA = '88881231 MODIFY ITAB FROM WA_TAB INDEX IDX TRANSPORTING ENDDA. end loop. modify t508a from TABLE itab.

DELETE STATEMENT The DELETE statement deletes rows in a table.SYNTAX: DELETE FROM WHERE .NOTE: Here all the lines matching the condition () in the database table () will be deleted.

2) DELETE FROM . NOTE: Here the line in the database table that matching the primary key with specified work area () will be deleted.

3) DELETE FROM TABLE . Here all the lines in the database table that matching the primary keys in the specified internal table will be deleted.

DELETE STATEMENT Delete lines from the internal table. 1) DELETE TABLE FROM . Here the line in the internal table that matching the primary key with the specified work area will be deleted.2) DELETE TABLE WITH TABLE KEY = = .Here the lines in the table with the specified table keys will be deleted.3) DELETE WHERE . Here the lines in the table that matching the specified conditions will be deleted. 4) DELETE ADJACENT DUPLICATE ENTRIES FROM [COMPARING... ]. Deletes adjacent duplicate entries, either by comparing the key fields or the comparison fields specified explicitly in the COMPARING addition.

DELETE STATEMENT Example: TABLES SBOOK. DELETE FROM SBOOK WHERE CARRID = 'LH' AND CONNID = '0400 AND FLDATE = '19950228'.