Select Statements in Abap
Select Statements in Abap
Data
DB
Slide 1
Slide 2
Open SQL
Open SQL
Set of ABAP statements that perform operations on the central database in the R/3 System. Provides a uniform syntax and semantics for all of the database systems supported by SAP. Views are handled in exactly the same way as database tables.
Slide 4
Database Access I
Physical Database
Logical Database
REPORT: ZRACER01. TABLES: LFA1, LFB1, LFC3. GET LFA1. GET LFB1.
Authorisation Checking
No Authorisation Checking
GET LFB3.
Keywords
SELECT INSERT MODIFY DELETE Reads data from database tables Adds lines to database tables
UPDATE Changes the contents of lines of database tables Inserts lines into database tables or changes existing lines Deletes lines from database tables
OPEN CURSOR, FETCH, CLOSE CURSOR Reads lines of database tables using the cursor
Slide 6
Client Handling
Open SQL statements use automatic client handling by using the data from the current client of client dependent tables . Data from other clients cannot be fetched by specifying client code in WHERE clause . For that the addition... CLIENT SPECIFIED .is used directly after the name of the database table. This addition disables the automatic client handling and you can use the field MANDT both in the WHERE clause and in a table work area.
Slide 7
Slide 8
Basic Significance
SELECT statement specifies columns and rows to be selected . It can also select values for all columns using SELECT * FROM .. And can also retrieve all information in a table omitting the WHERE clause. It can select single/few rows/all rows from database table depending on the SEARCH criteria , WHERE . The result of the selection is either an elementary field or a flat structure or an internal table or table work area, depending on the number of columns you specified in <cols> and number of records fetched.
Slide 9
Slide 10
Eliminating Inconsistency
SELECT [SINGLE [FOR UPDATE] .
FOR UPDATE protects the selected entry against simultaneous updates until next commit, have to specify the primary key or returns empty with a sy-subrc = 8
DISTINCT would automatically delete duplicate entries The columns of the result set will have exactly the same sequence, names as the fields of the database table
Slide 11
tables : mara .
SELECT SINGLE * FROM MARA WHERE MATNR = 'TRNG'. IF sy-subrc eq 0. write:/5 mara-matnr. ENDIF.
Slide 12
The result of the selection is a table. The target area of the INTO clause can be an internal table with a line type appropriate for <cols>. If the target area is not an internal table, but a flat structure, an ENDSELECT statement must be included after the SELECT statement.
(SELECTENDSELECT statements can be nested , but is not recommendable for performance reasons .)
Slide 13
System Variables for SELECT Statement SELECT is an OPEN SQL statement. Result table contains at least 1 record: Sy-Subrc = 0 Result table is empty: Sy-Subrc = 4 Exception - Select count(*) Fromstatement If no records found, Result table contains 1 line with the result 0 Sy-Subrc = 4, Sy-Dbcnt = 0 The system field SY-DBCNT contains the number of lines read by SELECT
Slide 14
Example : SELECT---ENDSELECT
REPORT . YSUBDEL0
tables : mara . SELECT * FROM MARA WHERE MTART = 'ROH'. IF sy-subrc eq 0. write:/5 mara-matnr. ENDIF.
ENDSELECT.
skip 4. write:/5 sy-dbcnt , 'Records Selected'.
Slide 15
Copyright IBM Corporation 2003
tables : mara . SELECT * FROM MARA CLIENT SPECIFIED WHERE MTART = 'ROH' AND MANDT = '777'. IF sy-subrc eq 0. write:/5 mara-matnr. ENDIF. ENDSELECT. skip 4. write:/5 sy-dbcnt , 'Records Selected'.
Slide 16
Specifying Columns
To read from specific columns from the database table, use the following:
SELECT <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
OR ,
SELECT <col1> <col2> into (a1,a2)
Slide 17
tables : mara .
IF sy-subrc eq 0.
write:/5 mara-matnr, mara-meins. ENDIF. ENDSELECT.
Slide 18
tables : mara .
SELECT MATNR as MATERIAL MEINS as UNIT FROM MARA INTO (MARA-MATNR,MARA-MEINS) WHERE MTART = 'ROH' AND NOT MEINS EQ SPACE. IF sy-subrc eq 0. write:/5 mara-matnr, mara-meins. ENDIF. ENDSELECT.
Slide 19
Copyright IBM Corporation 2003
Slide 20
INTO Clause
... INTO CORRESPONDING FIELDS OF wa Each field of the result set is transported to the field of the same name in wa. If no such field exists, this is ignored, and NO runtime error occurs ... INTO (f1, ..., fn) Places the result set in the target area (f1, ..., fn) from left to right is allowed only if a list of elements is specified in the Select clause For runtime-critical applications use this option as compared to INTO CORRESPONDING FIELDS
Slide 21
matnr
meins
like mara-matnr ,
like mara-meins ,
end of x_mat . SELECT matnr meins FROM mara INTO CORRESPONDING FIELDS OF x_mat WHERE mtart = 'ROH'. IF sy-subrc eq 0. WRITE:/5 x_mat-matnr , x_mat-meins. ENDIF. ENDSELECT.
Slide 22
Copyright IBM Corporation 2003
Appending the Selected Records with Pre Existing Contents of an Internal table :
SELECT <col1> <col2> . APPENDING CORRESPONDING FIELDS OF TABLE <INTTABLE> .
Table addition is mandatory to specify selection into internal table .Otherwise , internal table header line will be used .
SELECT.ENDSELECT block is not required if record is selected into internal table body (I.e., TABLE clause is used ) .
Slide 23
Slide 24
Slide 25
INTO Clause
Performance If selected data to be evaluated only once, use wa. Reading internal tables would incur additional costs and would use more memory space Read the data into an internal table in a single operation than to read it line by line in a SELECT loop and then use APPEND to append the data to a internal table INTO CORRESPONDING FIELDshould only be used when retrieving large volumes of data otherwise the time required to compare the field names would be too high.
Slide 26
Slide 27
Used in a SELECT command, it allows you to use a logical condition for the groups in a GROUP BY clause.
SELECT carrid connid COUNT( *) SUM( luggweight ) INTO (carrid, connid, count, sum_weight) FROM sbook WHERE carrid = 'LH' GROUP BY carrid connid HAVING SUM( luggweight ) > 25. WRITE:/ carrid, connid, count, sum_weight. ENDSELECT.
Slide 28
Copyright IBM Corporation 2003
The parentheses must include the name of an internal table <itab> that is either empty or contains <s 1 > <s 2 > ... to specify the columns or aggregate expressions to be read. For this purpose, the line type of <itab> must be a type C field with a maximum length of 72. If the internal table is empty, the system reads all columns.
Slide 29
Slide 30
can only specify the database table name at runtime if you specify an INTO clause at the same time.
Name
Slide 31
Slide 32
Slide 33
If ORDER BY clause is used, the system reads all lines belonging to the selection, sorts them, and then places the first <n> lines in the selection set.
Slide 34
Slide 35
=
< > , >< >= <= > <
EQ
NE GE LE GT LT
Equals to
Not equal To Greater than or equal to Lesser than or equal to Greater Than Lesser than
Slide 36
SELECT ... WHERE <s> [NOT ] BETWEEN <f 1> AND <f 2> ...
Comparing Strings
To find out whether the value of a column matches a pattern:-
SELECT ... WHERE <s> [NOT ] LIKE <f> [ESCAPE <h>] ...
Following wildcard characters in <f> can be used : % for a sequence of any characters (including spaces).
Slide 38
The condition is true if the value of column <s> is [not] in the list <f1> ... <f n>.
Slide 39
Negative Conditions
To negate the result of a condition, use: SELECT ... WHERE NOT <cond> ... Checking Subqueries To find out whether the value of a column is contained in a scalar subquery : SELECT ... WHERE <s> [NOT ] IN <subquery>
Slide 41
where <itab> is an internal table with line type C and maximum length 72 characters. All of the conditions listed above except for selection tables, can be written into the lines of <itab>.
Slide 42
The parameters entered make up the contents of the WHERE clause. The user has the option of changing the conditions and dynamically effecting which way the program will execute.
WHERE_ITAB-TEXT = WHERECL1. APPEND WHERE_ITAB. WHERE_ITAB-TEXT = WHERECL2. APPEND WHERE_ITAB. WHERE_ITAB-TEXT = WHERECL3. APPEND WHERE_ITAB. SELECT * FROM TABNA WHERE (WHERE_ITAB). WRITE: / TABNA-COUNTRY, TABNA-ID. ENDSELECT.
Slide 43
An internal table is created which holds the WHERE clause until it is used in the SELECT statement.
INTO SEPARATED BY
operators like BETWEEN, LIKE, or IN expression cannot be used in the WHERE clause
Order
Slide 45
WARNING #2: Beware if you have a large table, or a large range, the resulting SQL statement can be extremely large, and take the database server a long time to build. If the ABAP program causes the build of a larger-than-allowed SQL statement , it may crash
Slide 46
WARNING #4: Database Hint should be used for SELECT statements having FOR ALL ENTRIES, if the proper index is not being used. (This is applicable if the Database is Oracle 8).
Slide 47
Slide 48
Sorting records
Sorting By Primary Key : To sort the selection set in ascending order by the primary key, use the following: SELECT <lines> * ... ORDER BY PRIMARY KEY. This sorting method is only possible if asterisk (*) in the SELECT clause is used to select all columns. Sorting By Any Number of Columns SELECT ... ... ORDER BY <s1> [ASCENDING|DESCENDING] <s2> [ASCENDING|DESCENDING] ...
Slide 49
Slide 50
ORDER BY clause
Performance Unless a Primary or Secondary index exists for the field list specified, ORDER BY f1.fn should not be used to sort the data on Database Server, but data should rather be sorted on the Application Server
Slide 51
Subquery
SCARR SFLIGHT
Slide 52
Subquery Syntax/Example
SELECT * FROM scarr WHERE NOT carrid IN ( SELECT carrid FROM sflight ). WRITE:/ scarr-carrid, scarr-carrname. ENDSELECT.
Slide 53
Joins are more efficient than logical databases and nested selects. They access multiple tables with one select statement.
Slide 54
Inner Joins
SCARR SFLIGHT
Slide 55
The The
database system creates a temporary table containing the lines that meet the ON condition. The WHERE condition is then applied to the temporary table
Slide 56
Copyright IBM Corporation 2003
SELECT scarr~carrname sflight~carrid sflight~connid sflight~fldate INTO (carrid, connid, date, carrname) FROM scarr INNER JOIN sflight ON scarr~carrid = sflight~carrid. WRITE: / carrid, connid, date, carrname. ENDSELECT.
Slide 57
the
database system creates a temporary table containing the lines that meet the ON condition. The remaining rows from the left hand table are then added to this table and their corresponding fields from the right hand table are filled with NULL values.
Slide 58
Copyright IBM Corporation 2003
Slide 59
The syntax for joins have been given certain restrictions in order to insure that they produce the same results for all SAP supported databases.
Slide 60
Redundancy
LFA1
BSIK
Slide 61
CURSOR Processing
Slide 62
The FETCH statement retrieves the rows from the CURSOR one by one until there are no more rows left.
DO. FETCH NEXT CURSOR TABCUR INTO TABNA_WA. IF SY-SUBRC <> 0. After the FETCH is executed, the SY-SUBRC is CLOSE CURSOR TABCUR. tested. Zero indicates a successful retrieval; EXIT. Four indicates there are no more rows. ELSE. WRITE: / TABNA_WA-COUNTRY, TABNA-NAME1. ENDIF. ENDDO.
Slide 64
Copyright IBM Corporation 2003
DO. FETCH NEXT CURSOR TABCUR INTO TABNA_WA. IF SY-SUBRC <> 0. CLOSE CURSOR TABCUR. EXIT. ELSE. WRITE: / TABNA_WA-COUNTRY, TABNA-NAME1. ENDIF. ENDDO.
Slide 65
When CURSOR processing is completed, the CURSOR should be closed with the CLOSE CURSOR statement.
Inserting Records
Slide 66
Slide 68
UPDATING RECORDS
Slide 69
Updating Records
Slide 70
Updating Several Lines From Internal Table UPDATE <target> FROM TABLE <itab> . Overwrites the line of the database tables with corresponding lines in internal table <itab> .
Slide 71
DELETE
Slide 72
Deleting Recordscontinued
Deleting By search Criteria
Deleting Individual Lines From a Work Area To delete a single line in a database table from the contents of a work area : DELETE <target> FROM <wa> .
Slide 73
Deleting Several Lines From Internal Table Delete <target> FROM TABLE <itab> . Deletes the line of the database tables with corresponding lines in internal table <itab> .
Slide 74
MODIFY <target> <lines>. If the database table contains no line with the same primary key as the line to be inserted, MODIFY works like INSERT, that is, the line is added. If the database already contains a line with the same primary key as the line to be inserted, MODIFY works like UPDATE, that is, the line is changed. The syntaxes of the modify statement are similar to the insert statement .
Slide 75
Commit/Rollback
Open SQL contains the statements COMMIT WORK. and ROLLBACK WORK. for confirming or undoing database updates. COMMIT WORK always concludes a database LUW and starts a new one. ROLLBACK WORK always undoes all changes back to the start of the database LUW.
Slide 76
The newly created database table is populated using an SQL INSERT statement.
Slide 77
A Host Variable is any data item that is defined by the ABAP program and used inside an ABAP Native SQL Statement. They must be preceded by a colon.
Slide 78
Copyright IBM Corporation 2003
The PERFORMING <form> option creates a looping structure that for every row retrieved, the subroutine is called.
Slide 79
Copyright IBM Corporation 2003