SELECT SINGLE CARRID CONNID CITYFROM CITYTO INTO CORRESPONDING FIELDS OF WA The output is: SINGLE in the SELECT clause means that the statement reads a single entry fromthe database tabl
Trang 1Filling an Initial Screen using SPA/GPA Parameters
Filling an Initial Screen using SPA/GPA Parameters
To fill the input fields of a called transaction with data from the calling program, you can use theSPA/GPA technique SPA/GPA parameters are values that the system stores in the global, user-specific SAP memory SAP memory allows you to pass values between programs A user canaccess the values stored in the SAP memory during one terminal session for all parallel
sessions Each SPA/GPA parameter is identified by a 20-character code You can maintain them
in the Repository Browser in the ABAP Workbench The values in SPA/GPA parameters areuser-specific
ABAP programs can access the parameters using the SET PARAMETER and GET
PARAMETER statements
To fill one, use:
SET PARAMETER ID <pid> FIELD <f>
This statement saves the contents of field <f> under the ID <pid> in the SAP memory The code
<pid> can be up to 20 characters long If there was already a value stored under <pid>, thisstatement overwrites it If the ID <pid> does not exist, double-click <pid> in the ABAP Editor tocreate a new parameter object
To read an SPA/GPA parameter, use:
GET PARAMETER ID <pid> FIELD <f>
This statement fills the value stored under the ID <pid> into the variable <f> If the system doesnot find a value for <pid> in the SAP memory, it sets SY-SUBRC to 4, otherwise to 0
To fill the initial screen of a program using SPA/GPA parameters, you normally only need theSET PARAMETER statement
The relevant fields must each be linked to an SPA/GPA parameter
On a selection screen, you link fields to parameters using the MEMORY ID addition in the
PARAMETERS or SELECT-OPTIONS statement If you specify an SPA/GPA parameter ID whenyou declare a parameter or selection option, the corresponding input field is linked to that inputfield
On a screen, you link fields to parameters in the Screen Painter When you define the field
attributes of an input field, you can enter the name of an SPA/GPA parameter in the Parameter
ID field in the screen attributes The SET parameter and GET parameter checkboxes allow you
to specify whether the field should be filled from the corresponding SPA/GPA parameter in thePBO event, and whether the SPA/GPA parameter should be filled with the value from the screen
in the PAI event
When an input field is linked to an SPA/GPA parameter, it is initialized with the current value ofthe parameter each time the screen is displayed This is the reason why fields on screens in theR/3 System often already contain values when you call them more than once
When you call programs, you can use SPA/GPA parameters with no additional programmingoverhead if, for example, you need to fill obligatory fields on the initial screen of the called
program The system simply transfers the values from the parameters into the input fields of thecalled program
However, you can control the contents of the parameters from your program by using the SETPARAMETER statement before the actual program call This technique is particularly useful ifyou want to skip the initial screen of the called program and that screen contains obligatory fields
Trang 2If you want to set SPA/GPA parameters before a program call, you need to know which
parameters are linked to which fields on the initial screen A simple way of doing this is to startthe program that you want to call, place the cursor on the input fields, and choose F1 followed by
Technical info The Parameter ID field contains the name of the corresponding SPA/GPA
parameter Alternatively, you can look at the screen definition in the Screen Painter
The technical information for the first input field of the booking transaction TCG2looks like this:
Airline
Booking number
Flight numberFlight date
Technical info
Parameter ID CAR
The SPA/GPA parameter for the input field Company has the ID CAR Use this
method to find the IDs CON, DAY, and BOK for the other input fields
The following executable program is connected to the logical database F1S and calls
an update transaction:
REPORT BOOKINGS NO STANDARD PAGE HEADING
TABLES SBOOK
Trang 3Filling an Initial Screen using SPA/GPA Parameters
SET PARAMETER ID: 'CAR' FIELD SBOOK-CARRID,
'CON' FIELD SBOOK-CONNID,
'DAY' FIELD SBOOK-FLDATE,
'BOK' FIELD SBOOK-BOOKID
CALL TRANSACTION 'BOOK'
The basic list of the program shows fields from the database table SBOOK according
to the user entries on the selection screen These data are also stored in the HIDEareas of each line
If the user selects a line of booking data by double-clicking, the system triggers the
AT LINE-SELECTION event and takes the data stored in the HIDE area to fill theminto the SPA/GPA parameters of the initial screen of the transaction Then it calls thetransaction Since you do not suppress the initial screen using AND SKIP FIRSTSCREEN, the initial screen may appear as follows:
Trang 4Airline
Booking number
Flight numberFlight date
LH240201/20/199500010001
If you would use the AND SKIP FIRST SCREEN option with the CALL
TRANSACTION statement, the second screen would appear immediately, since allobligatory fields of the first screen are filled
Trang 5ABAP Database Access
ABAP Database Access
Trang 6Standard SQL
SQL (Structured Query Language) is a largely standardized language for accessing relationaldatabases It can be divided into three areas:
• Data Manipulation Language (DML)
Statements for reading and changing data in database tables
• Data Definition Language (DDL)
Statements for creating and administering database tables
• Data Control Language (DCL)
Statements for authorization and consistency checks
Each database has a programming interface that allows you to access the database tables usingSQL statements The SQL statements in these programming interfaces are not fully
standardized To access a specific database system, you must refer to the documentation of thatsystem for a list of the SQL statements available and their correct syntax
The Database Interface
To make the R/3 System independent of the database system with which you use it despite thedifferences in the SQL syntax between various databases, each work process on an applicationserver has a database interface The R/3 System communicates with the database by means ofthis interface The database interface converts all of the database requests from the R/3 Systeminto the correct Standard SQL statements for the database system To do this, it uses a
database-specific component that shields the differences between database systems from therest of the database interface You choose the appropriate layer when you install the R/3
System
Trang 7Accessing the Database in the R/3 System
Open SQL Modules(Table module, buffer management)
There are two ways of accessing the database from a program - with Open SQL or Native SQL
Open SQL
Open SQL statements are a subset of Standard SQL that is fully integrated in ABAP They allowyou to access data irrespective of the database system that the R/3 installation is using OpenSQL consists of the Data Manipulation Language (DML) part of Standard SQL; in other words, itallows you to read (SELECT) and change (INSERT, UPDATE, DELETE) data
Open SQL also goes beyond Standard SQL to provide statements that, in conjunction with otherABAP constructions, can simplify or speed up database access It also allows you to buffercertain tables on the application server, saving excessive database access In this case, thedatabase interface is responsible for comparing the buffer with the database Buffers are partlystored in the working memory of the current work process, and partly in the shared memory forall work processes on an application server Where an R/3 System is distributed across morethan one application server, the data in the various buffers is synchronized at set intervals by thebuffer management When buffering the database, you must remember that data in the buffer isnot always up to date For this reason, you should only use the buffer for data which does notoften change You specify whether a table can be buffered in its definition in the ABAP
Dictionary
Trang 8Native SQL
Native SQL is only loosely integrated into ABAP, and allows access to all of the functions
contained in the programming interface of the respective database system Unlike Open SQLstatements, Native SQL statements are not checked and converted, but instead are sent directly
to the database system When you use Native SQL, the function of the database-dependentlayer is minimal Programs that use Native SQL are specific to the database system for whichthey were written When writing R/3 applications, you should avoid using Native SQL whereverpossible It is used, however, in some parts of the R/3 Basis System - for example, for creating orchanging table definitions in the ABAP Dictionary
The ABAP Dictionary
The ABAP Dictionary, part of the ABAP Workbench, allows you to create and administer
database tables Open SQL contains no statements from the DDL part of Standard SQL Normalapplication programs should not create or change their own database tables
The ABAP Dictionary uses the DDL part of Open SQL to create and change database tables Italso administers the ABAP Dictionary in the database The ABAP Dictionary contains
metadescriptions of all database tables in the R/3 System Only database tables that you createusing the ABAP Dictionary appear in the Dictionary Open SQL statements can only accesstables that exist in the ABAP Dictionary
Authorization and Consistency Checks
The DCL part of Standard SQL is not used in R/3 programs The work processes within the R/3System are logged onto the database system as users with full rights The authorizations ofprograms or users to read or change database tables is administered within the R/3 Systemusing the R/3 authorization concept Equally, transactions must ensure their own data
consistency using the R/3 locking concept For more information, refer to Programming
Database Updates [Page 1312]
Trang 9Open SQL
Open SQL
Open SQL consists of a set of ABAP statements that perform operations on the central database
in the R/3 System The results of the operations and any error messages are independent of thedatabase system in use Open SQL thus provides a uniform syntax and semantics for all of thedatabase systems supported by SAP ABAP programs that only use Open SQL statements willwork in any R/3 System, regardless of the database system in use Open SQL statements canonly work with database tables that have been created in the ABAP Dictionary
In the ABAP Dictionary, you can combine columns of different database tables to a databaseview (or view for short) In Open SQL statements, views are handled in exactly the same way asdatabase tables Any references to database tables in the following sections can equally apply toviews
Overview
Open SQL contains the following keywords:
SELECT Reads data from database tables
INSERT Adds lines to database tables
UPDATE Changes the contents of lines of database tables
MODIFY Inserts lines into database tables or changes the contents of existing linesDELETE Deletes lines from database tables
By default, Open SQL statements use automatic client handling Statements that access
client-dependent application tables only use the data from the current client You cannot specify a
condition for the client field in the WHERE clause of an Open SQL statement If you do so, thesystem will either return an error during the syntax check or a runtime error will occur You
Trang 10cannot overwrite the MANDT field of a database using Open SQL statements If you specify adifferent client in a work area, the ABAP runtime environment automatically overwrites it with thecurrent one before processing the Open SQL statement further.
Should you need to specify the client specifically in an Open SQL statement, use the addition CLIENT SPECIFIED
directly after the name of the database table This addition disables the automatic client handlingand you can use the field MANDT both in the WHERE clause and in a table work area
Reading data [Page 1084]
Changing data [Page 1135]
Trang 12FROM clause WHERE clause
SELECT <result> [Page
1087] The SELECT clause defines the structure of the data you want toread, that is, whether one line or several, which columns you
want to read, and whether identical entries are acceptable or not.INTO <target> [Page 1094] The INTO clause determines the target area <target> into which
the selected data is to be read
FROM <source> [Page
1101] The FROM clause specifies the database table or view<source> from which the data is to be selected It can also be
placed before the INTO clause
WHERE <cond> [Page
1108]
The WHERE clause specifies which lines are to be read byspecifying conditions for the selection
GROUP BY <fields> [Page
1116] The GROUP-BY clause produces a single line of results fromgroups of several lines A group is a set of lines with identical
values for each column listed in <fields>
Trang 13Reading Data
HAVING <cond> [Page
1119] The HAVING clause sets logical conditions for the linescombined using GROUP BY
ORDER BY <cond> [Page
1121] The ORDER-BY clause defines a sequence <fields> for the linesresulting from the selection.The individual clauses and the ways in which they combine are all very important factors in theSELECT statement Although it is a single statement like any other, beginning with the SELECTkeyword and ending with a period, its division into clauses, and the ways in which they combine,make it more powerful than other statements A single SELECT statement can perform functionsranging from simply reading a single line to executing a very complicated database query
You can use SELECT statements in the WHERE and HAVING clauses These are called
subqueries [Page 1124]
You can decouple the INTO clause from the SELECT statement by reading from the databaseusing a cursor [Page 1128]
Trang 14The selection can be flat (one line) or tabular (several lines) You can specify whether to accept
or exclude duplicate entries The SELECT clause also specifies the names of the columns to beread You can replace the names of the database fields with alternative names Aggregatefunctions can be applied to individual columns
The SELECT clause can be divided into two parts for lines and columns:
SELECT <lines> <cols>
<lines> specifies whether you want to read one or more lines <cols> defines the column
selection
Reading a Single Line
To read a single entry from the database, use the following:
SELECT SINGLE <cols> WHERE
To ensure that the line can be uniquely identified, you must specify values for all of the fields ofthe primary key of the table in the WHERE clause If the WHERE clause does not contain all ofthe key fields, the syntax check produces a warning, and the SELECT statement reads the firstentry that it finds that matches the key fields that you have specified
The result of the selection is either an elementary field or a flat structure, depending on thenumber of columns you specified in <cols> The target area in the INTO clause must be
appropriately convertible
If the system finds a line with the corresponding key, SY-SUBRC is set to 0, otherwise to 4
Reading Several Lines
To read a several entries from the database, use the following:
SELECT [DISTINCT] <cols> WHERE
Trang 15structure, you must include an ENDSELECT statement after the SELECT statement:
SELECT [DISTINCT] <cols> WHERE
ENDSELECT
The lines are read in a loop [Page 246] one by one into the target area specified in the INTOclause You can work with the target area within the loop
If at least one line is read, SY-SUBRC is set to 0 after the statement (or loop) has been
processed If no lines are read, SY-SUBRC is set to 4 The number of lines read is placed in thesystem field SY-DBCNT Within the loop, SY-DBCNT already contains the number of lines thathave already been passed to the target area
Technically, it is possible to nest SELECT loops However, for performance reasons, you shouldavoid doing so If you want to read interdependent data from more than one database table, youcan use a join in the FROM clause or a subquery in the WHERE clause
Reading the Whole Line
To read all of the columns in the database table, use the following:
SELECT <lines> *
This reads all columns for the specified lines The data type of the selected lines is a structurewith exactly the same data type as the database table in the ABAP Dictionary The target area ofthe INTO clause should be compatible with, or at least convertible into this data type In the otherclauses, you can only address the columns under their names in the database table
Reading individual columns can be considerably more efficient than reading all of the columns in
a table You should therefore only read the columns that you need in your program
Reading Single Columns
To read single columns from the database table, use the following:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>]
where <si> are single columns There are different ways of addressing the columns, depending
on the form of your FROM clause:
• <si> specifies the component <ci> of the database table This is only possible if thecorresponding name is unique This is always the case if you only specify a singledatabase table in the FROM clause
• <si> specifies the full name of the required component in the form <dbtab>~<ci>, where
<dbtab> is the name of the database table This is always necessary if the componentname appears in more than one database table in the FROM clause, and is only possible
if the database table <dbtab> only appears once in the FROM clause
• <si> specifies the full name of the required component in the form <tabalias>~<ci>,where <tabalias> is an alias name for the database table This is always necessary if thetable from which you want to read occurs more than once in the FROM clause Youmust define the alias name <tabalias> in the FROM clause
Trang 16In the SELECT clause, you can use the AS addition to specify an alias name <ai> for eachcolumn <si> The alias column name is used instead of the real name in the INTO and ORDER
BY clauses This allows you for example, to read the contents of a column <si> into a
component <ai> of a structure when you use the INTO CORRESPONDING FIELDS OF addition.The data type of a column is the Dictionary type of the corresponding underlying domain in theABAP Dictionary You must choose the data types of the target fields in the INTO clause so thatthe Dictionary types can easily be converted For a table of Dictionary types and their
corresponding ABAP data types, refer to Data Types in the ABAP Dictionary [Page 105]
Reading Aggregate Data for Columns
To read aggregate data for a column in the database, use the following:
SELECT <lines> <agg>( [DISTINCT] <s1> ) [AS <a1>]
<agg>( [DISTINCT] <s2> ) [AS <a2>]
where <si> are the same field labels as above The expression <agg> represents one of thefollowing aggregate functions:
• MAX: returns the maximum value of the column <si>
• MIN: returns the minimum value of the column <si>
• AVG: returns the average value of the column <si>
• SUM: returns the sum value of the column <si>
• COUNT: counts values or lines as follows:
•••• COUNT( DISTINCT <si> ) returns the number of different values in the column
<si>
•••• COUNT( * ) returns the total number of lines in the selection
You can exclude duplicate values from the calculation using the DISTINCT option The spacesbetween the parentheses and the arguments of the aggregate expressions must not be left out.The arithmetic operators AVG and SUM only work with numeric fields
The data type of aggregate functions using MAX, MIN, or SUM is the Dictionary type of thecorresponding column Aggregate expressions with the function AVG have the Dictionary typeFLTP, and those with COUNT have the Dictionary type INT4 The target field should have thecorresponding type When you calculate average values, it is a good idea to use the ABAP type
F However, remember that the database system may use different approximations to ABAP.When you calculate a sum, ensure that the target field is large enough
Unlike ABAP, database systems recognize null values in database fields A null value meansthat a field has no contents, and it is not included in calculations The result of the calculation isonly null if all of the lines in the selection contain the null value in the corresponding field InABAP, the null value is interpreted as zero (depending on the data type of the field)
In the AS addition, you can define an alternative column name <ai> for each aggregate
expression The alias column name is used instead of the real name in the INTO and ORDER
BY clauses This is the only way of sorting by an aggregate expression in the ORDER BYclause
If the list in the SELECT clause (excepting aggregate expressions) contains one or more fieldnames, the field names must also be listed in the GROUP BY clause The aggregate functions
do not then apply to all of the selected lines, but to the individual groups of lines
Trang 17Defining Selections
Specifying Columns Dynamically
You can also specify <cols> dynamically as follows:
SELECT <lines> (<itab>)
The parentheses must include the name of an internal table <itab> that is either empty or
contains <s1> <s2> to specify the columns or aggregate expressions to be read For thispurpose, the line type of <itab> must be a type C field with a maximum length of 72 If the internaltable is empty, the system reads all columns
Examples
Reading certain columns of a single line:
DATA WA TYPE SPFLI.
SELECT SINGLE CARRID CONNID CITYFROM CITYTO
INTO CORRESPONDING FIELDS OF WA
The output is:
SINGLE in the SELECT clause means that the statement reads a single entry fromthe database table SPFLI where the primary key fields CARRID and CONNID havethe values specified in the WHERE clause The columns specified in the SELECTclause are transferred to the identically-named components of the structure WA
Reading particular columns of more than one line:
DATA: ITAB TYPE STANDARD TABLE OF SPFLI,
WA LIKE LINE OF ITAB.
SELECT CARRID CONNID CITYFROM CITYTO
INTO CORRESPONDING FIELDS OF TABLE ITAB
WHERE CARRID EQ 'LH'.
IF SY-SUBRC EQ 0.
LOOP AT ITAB INTO WA.
WRITE: / WA-CARRID, WA-CONNID, WA-CITYFROM, WA-CITYTO ENDLOOP.
ENDIF.
The output is:
Trang 18Since there are no lines specified in the SELECT clause, the statement reads all ofthe lines from the database table SPFLI that satisfy the condition in the WHEREclause The columns specified in the SELECT clause are transferred to the
identically-named components of the internal table ITAB
Reading all columns of more than one line:
DATA WA TYPE SPFLI.
The output is:
Since there are no lines specified in the SELECT clause, the statement reads all ofthe lines from the database table SPFLI that satisfy the condition in the WHEREclause All of the columns in the table are transferred to the identically-namedcomponents of the flat structure WA This is why you must conclude the SELECTloop with the ENDSELECT statement
Trang 19Defining Selections
The following coding demonstrates the aggregate functions:
DATA RESULT TYPE P DECIMALS 2
SELECT <agg>( [DISTINCT] COL_2 )
Specifying Columns Dynamically
DATA: ITAB TYPE STANDARD TABLE OF SPFLI,
WA LIKE LINE OF ITAB.
DATA: LINE(72) TYPE C,
LIST LIKE TABLE OF LINE(72).
LINE = ' CITYFROM CITYTO '.
APPEND LINE TO LIST.
SELECT DISTINCT (LIST)
INTO CORRESPONDING FIELDS OF TABLE ITAB FROM SPFLI.
IF SY-SUBRC EQ 0.
LOOP AT ITAB INTO WA.
WRITE: / WA-CITYFROM, WA-CITYTO.
ENDLOOP.
ENDIF.
The output is:
Trang 20The internal table ITAB contains the columns of the database table SPFLI to be read.The DISTINCT addition in the SELECT clause means that the statement only readsthose lines that have different contents in both of these columns The result is a list
of possible routes
Trang 21Specifying a Target Area
Specifying a Target Area
The INTO clause defines the target area into which the selection from the SELECT clause iswritten Suitable target areas are variables [Page 124] whose data type is compatible with orconvertible into that of the selection in the SELECT clause
The SELECT clause determines the data type of the target area as follows:
• The <lines> specification in the SELECT clause determines the depth of the target area,that is, whether it is a flat or a tabular structure
• The <cols> specification in the SELECT clause determines the structure (line type) of thetarget area
}
Target area Structure
Depth ABAP
Selection
If you select a single line, the target area must be flat If you select more than one line, the targetarea may be either tabular or flat If the target area is flat, you need to use a SELECT loop.When you select all of the columns, the target area must either be a structure or convertible intoone When you select individual columns, the target area can be a component of a structure or asingle field
The elementary data types in the selection in the SELECT clause are Dictionary types TheseDictionary types must be able to be converted into the ABAP data types of the correspondingelementary components of the target area For a table of data types, refer to Data Types in theABAP Dictionary [Page 105]
Trang 22Specifying a Flat Work Area
You can specify a flat work area regardless of whether you are reading from a single line or fromseveral To read data into one, use the following in the INTO clause:
SELECT INTO [CORRESPONDING FIELDS OF] <wa>
The target area must be at least as large as the line to be read into it However, this is the onlyrestriction on its data type You should base your choice of data type on the specifications in theSELECT clause such that the columns that you have read can be addressed in <wa>
If you specify an asterisk (*) in the SELECT clause (select all columns), the data is transferredinto the work area from left to right according to the structure of the database table The
structure of <wa> is irrelevant in this case In order to enable you to address the values in theindividual columns after the SELECT statement, the work area should have the same structure
as the database table
If you specified individual columns or aggregate expressions in the SELECT clause, the columnsare transferred into the work area from left to right according to the structure of the work area.When you read the data into <wa>, its previous contents are overwritten However, the
components of <wa> that are not affected by the SELECT statement retain their previous values
If the work area is structured, you can use the CORRESPONDING FIELDS addition Thistransfers only the contents of fields whose names are identical in the database table and thework area This includes any alias column names that you specified in the selection Workingwith the CORRESPONDING FIELDS option of the INTO clause does not limit the amount of dataread from the database, but only the amount of data that is read from the resulting set into theABAP program The only way of restricting the number of columns read is in the SELECT clause
If you use the asterisk (*) option to read all of the columns of a single database table <dbtab> inthe SELECT clause, the INTO clause may be empty The SELECT statement then writes thedata by default into the table work area with the same name <dbtab> as the database table itself
You must declare this table work area using the TABLES [Page 131] statement Before Release
4.0, this was necessary before you could read data from a database table at all, and was
frequently used as an implicit work area Nowadays, table work areas are still useful as interfacework areas, but should no longer be used as the work area in the SELECT statement Likeinternal tables without header lines, having different names for the source and target areasmakes programs clearer
Specifying Internal Tables
When you read several lines of a database table, you can place them in an internal table To dothis, use the following in the INTO clause:
SELECT INTO|APPENDING [CORRESPONDING FIELDS OF] TABLE <itab>
[PACKAGE SIZE <n>]
The same applies to the line type of <itab>, the way in which the data for a line of the databasetable are assigned to a table line, and the CORRESPONDING FIELDS addition as for flat workareas (see above)
The internal table is filled with all of the lines of the selection When you use INTO, all existinglines in the table are deleted When you use APPENDING; the new lines are added to the
existing internal table <itab> With APPENDING, the system adds the lines to the internal tableappropriately for the table type Fields in the internal table not affected by the selection are filledwith initial values
Trang 23Specifying a Target Area
If you use the PACKAGE SIZE addition, the lines of the selection are not written into the internaltable at once, but in packets You can define packets of <n> lines that are written one after theother into the internal table If you use INTO, each packet replaces the preceding one If you useAPPENDING, the packets are inserted one after the other This is only possible in a loop thatends with ENDSELECT Outside the SELECT loop, the contents of the internal table are
undetermined You must process the selected lines within the loop
Specifying Single Fields
If you specify single columns of the database table or aggregate expressions in the SELECTclause, you can read the data into single fields for a single entry or for multiple entries in a
SELECT loop To read data into single fields, use the following in the INTO clause:
SELECT INTO (<f1>, <f2>, )
You must specify as many individual fields <fi> as are specified in the field list of the SELECTclause The fields in the SELECT clause are assigned, from left to right, to the fields in the list inthe INTO clause
You do not have to use a field list in the INTO clause when you specify individual fields in theSELECT clause - you can also use the CORRESPONDING FIELDS addition to read the datainto a flat work area or an internal table instead In that case, the target area does not need tocontain the same number of elements as the list in the SELECT clause
Examples
Flat structure as target area
DATA WA TYPE SPFLI.
DATA SPFLI TYPE SPFLI.
Trang 24Internal table as target area
DATA: BEGIN OF WA,
CARRID TYPE SPFLI-CARRID, CONNID TYPE SPFLI-CONNID, CITYFROM TYPE SPFLI-CITYFROM, CITYTO TYPE SPFLI-CITYTO, END OF WA,
ITAB LIKE SORTED TABLE OF WA
WITH NON-UNIQUE KEY CITYFROM CITYTO.
SELECT CARRID CONNID CITYFROM CITYTO
INTO CORRESPONDING FIELDS OF TABLE ITAB
IF SY-SUBRC EQ 0.
WRITE: / SY-DBCNT, 'Connections'.
SKIP.
LOOP AT ITAB INTO WA.
WRITE: / WA-CARRID, WA-CONNID, WA-CITYFROM, WA-CITYTO ENDLOOP.
ENDIF.
The output is:
The target area is a sorted table ITAB containing four fields with the same namesand data types as the database table SPFLI The program uses the
CORRESPONDING FIELDS addition to place the columns from the SELECT clauseinto the corresponding fields of the internal table Because ITAB is a sorted table, thedata is inserted into the table sorted by the table key of ITAB
Reading packets into an internal table
DATA: WA TYPE SPFLI,
ITAB TYPE SORTED TABLE OF SPFLI
WITH UNIQUE KEY CARRID CONNID.
Trang 25Specifying a Target Area
SELECT CARRID CONNID
INTO CORRESPONDING FIELDS OF TABLE ITAB
PACKAGE SIZE 3.
LOOP AT ITAB INTO WA.
WRITE: / WA-CARRID, WA-CONNID.
ENDLOOP.
SKIP 1.
ENDSELECT.
The output is:
The example reads packets of three lines each into the sorted table ITAB In eachpass of the SELECT loop, the internal table has a different sorted content
If you were to use APPENDING instead of INTO, the list would look like this:
Trang 26In each loop pass, a new packet is sorted into the internal table.
Single fields as target area:
DATA: AVERAGE TYPE P DECIMALS 2,
SELECT AVG( LUGGWEIGHT ) SUM( LUGGWEIGHT )
INTO (AVERAGE, SUM)
Trang 27Specifying a Target Area
The SELECT clause contains two aggregate expressions for calculating the averageand sum of the field LUGGWEIGHT from database table SBOOK The target fieldsare called AVERAGE and SUM
Using aliases:
DATA: BEGIN OF LUGGAGE,
AVERAGE TYPE P DECIMALS 2,
The output is:
This example has the same effect as the previous one The only difference is that astructure is used as the target area instead of individual fields, and that the names ofthe structure components are used as aliases in the SELECT clause
Trang 28Specifying Database Tables
The FROM clause determines the database tables from which the data specified in the SELECTclause is read You can specify either a single table or more than one table, linked using inner orouter joins The names of database tables may be specified statically or dynamically, and youcan use alias names You can also use the FROM clause to bypass the SAP buffer and restrictthe number of lines to be read from the database
The FROM clause has two parts - one for specifying database tables, and one for other
additions:
SELECT FROM <tables> <options>
In <tables>, you specify the names of database tables and define joins <options> allows you tospecify further additions that control the database access
Specifying Database Tables Statically
To specify the name of a database table statically, use the following:
SELECT FROM <dbtab> [AS <alias>] <options>
The database table <dbtab> must exist in the ABAP Dictionary The AS addition allows you tospecify an alternative name <alias> that you can then use in the SELECT; FROM, WHERE, and
Trang 29Specifying Database Tables
GROUP BY clauses This can eliminate ambiguity when you use more than one database table,especially when you use a single database table more than once in a join Once you havedefined an alias, you may no longer use the real name of the database table
Specifying Database Tables Dynamically
To specify the name of a database table dynamically, use the following:
SELECT FROM (<name>) <options>
The field <name> must contain the name of a database table in the ABAP Dictionary The tablename must be written in uppercase When you specify the name of a database table dynamically,you cannot use an empty INTO clause to read all of the columns into the work area <dbtab> It isalso not possible to use alternative table names
Specifying Two or More Database Tables as an Inner Join
In a relational database, you normally need to read data simultaneously from more than onedatabase table into an application program You can read from more than one table in a singleSELECT statement, such that the data in the tables all has to meet the same conditions, usingthe following join expression:
A join expression links each line of <tab> with the lines in <dbtab> that meet the condition
<cond> This means that there is always one or more lines from the right-hand table that is linked
to each line from the left-hand table by the join If <dbtab> does not contain any lines that meetthe condition <cond>, the line from <tab> is not included in the selection
Trang 30SELECT
FROM ( ( ( DBTAB1 INNER JOIN DBTAB2 ON )
INNER JOIN DBTAB3 ON ) INNER JOIN DBTAB4 ON )
SELECT
FROM ( ( ( DBTAB1 INNER JOIN DBTAB2 ON )
INNER JOIN DBTAB3 ON ) INNER JOIN DBTAB4 ON )
DBTAB1 DBTAB2
DBTAB3
DBTAB4
The syntax of the <cond> condition is like that of the WHERE clause, although individual
comparisons can only be linked using AND Furthermore, each comparison must contain acolumn from the right-hand table <dbtab> It does not matter on which side of the comparison itoccurs For the column names in the comparison, you can use the same names that occur in theSELECT clause, to differentiate columns from different database tables that have the samenames
The comparisons in the condition <cond> can appear in the WHERE clause instead of the ONclause, since both clauses are applied equally to the temporary table containing all of the linesresulting from the join However, each join must contain at least one comparison in the condition
<cond>
Specifying Two or More Database Tables as a Left Outer Join
In an inner join, a line from the left-hand database table or join is only included in the selection ifthere is one or more lines in the right-hand database table that meet the ON condition <cond>.The left outer join, on the other hand, reads lines from the left-hand database table or join even ifthere is no corresponding line in the right-hand table
Trang 31Specifying Database Tables
In the left outer join, more restrictions apply to the condition <cond> than in the inner join Inaddition to the above restrictions:
• EQ or = is the only permitted relational operator
• There must be at least one comparison between columns from <tab> and <dbtab>
• The WHERE clause may not contain any comparisons with columns from <dbtab> Allcomparisons using columns from <dbtab> must appear in the condition <cond>
Client Handling
As already mentioned, you can switch off the automatic client handling in Open SQL statementsusing a special addition In the SELECT statement, the addition comes after the options in theFROM clause:
SELECT FROM <tables> CLIENT SPECIFIED
If you use this addition, you can then address the client fields in the individual clauses of theSELECT statement
Disabling Data Buffering
If buffering is allowed for a table in the ABAP Dictionary, the SELECT statement always readsthe data from the buffer in the database interface of the current application server To read datadirectly from the database table instead of from the buffer, use the following:
SELECT FROM <tables> BYPASSING BUFFER
This addition guarantees that the data you read is the most up to date However, as a rule, onlydata that does not change frequently should be buffered, and using the buffer where appropriateimproves performance You should therefore only use this option where really necessary
Restricting the Number of Lines
To restrict the absolute number of lines included in the selection, use the following:
SELECT FROM <tables> UP TO <n> ROWS
If <n> is a positive integer, the system reads a maximum of <n> lines If <n> is zero, the systemreads all lines that meet the selection criteria If you use the ORDER BY clause as well, thesystem reads all lines belonging to the selection, sorts them, and then places the first <n> lines inthe selection set
Examples
Specifying a database table statically:
DATA WA TYPE SCARR.
SELECT *
FROM SCARR UP TO 4 ROWS.
WRITE: / WA-CARRID, WA-CARRNAME.
ENDSELECT.
Trang 32The output is:
The system reads four lines from the database table SCARR
Specifying a database table dynamically:
DATA WA TYPE SCARR.
DATA NAME(10) VALUE 'SCARR'.
Inner join:
DATA: BEGIN OF WA,
CARRID TYPE SPFLI-CARRID, CONNID TYPE SPFLI-CONNID, FLDATE TYPE SFLIGHT-FLDATE, BOOKID TYPE SBOOK-BOOKID, END OF WA,
ITAB LIKE SORTED TABLE OF WA
WITH UNIQUE KEY CARRID CONNID FLDATE BOOKID SELECT P~CARRID P~CONNID F~FLDATE B~BOOKID
INTO CORRESPONDING FIELDS OF TABLE ITAB
FROM ( ( SPFLI AS P
INNER JOIN SFLIGHT AS F ON P~CARRID = F~CARRID AND
P~CONNID =
INNER JOIN SBOOK AS B ON B~CARRID = F~CARRID AND
B~CONNID = F~CONNID AND B~FLDATE =
WHERE P~CITYFROM = 'FRANKFURT' AND
P~CITYTO = 'NEW YORK' AND F~SEATSMAX > F~SEATSOCC.
Trang 33Specifying Database Tables
LOOP AT ITAB INTO WA.
assigned to each table
Left outer join:
DATA: BEGIN OF WA,
CARRID TYPE SCARR-CARRID, CARRNAME TYPE SCARR-CARRNAME, CONNID TYPE SPFLI-CONNID, END OF WA,
ITAB LIKE SORTED TABLE OF WA
WITH NON-UNIQUE KEY CARRID.
SELECT S~CARRID S~CARRNAME P~CONNID
INTO CORRESPONDING FIELDS OF TABLE ITAB
FROM SCARR AS S
LEFT OUTER JOIN SPFLI AS P ON S~CARRID = P~CARRID AND
P~CITYFROM = 'FRANKFURT' LOOP AT ITAB INTO WA.
WRITE: / WA-CARRID, WA-CARRNAME, WA-CONNID.
ENDLOOP.
The output might look like this:
Trang 34The example links the columns CARRID, CARRNAME, and CONNID of the tablesSCARR and SPFLI using the condition in the left outer join that the airline must flyfrom Frankfurt All other airlines have a null value in the CONNID column in theselection.
If the left outer join is replaced with an inner join, the list looks like this:
Only lines that fulfill the ON condition are included in the selection
Trang 35SELECT WHERE <cond>
The <cond> conditions in the WHERE clause can be comparisons or a series of other specialexpressions You can combine a series of conditions into a single condition Conditions mayalso be programmed dynamically
The conditions <cond> in the WHERE clause are often like logical expressions [Page 226], butnot identical, since the syntax and semantics follow that of Standard SQL In the conditions inthe WHERE clause, you name columns using a field name as in the SELECT clause In thefollowing descriptions, <s> always represents a column of one of the database tables named inthe FROM clause The result of a condition may be true, false, or unknown A line is only
selected if the condition is true for it A condition is unknown if one of the columns involvedcontains a null value
Comparisons for All Types
To compare the value of a column of any data type with another value, use the following:
SELECT WHERE <s> <operator> <f>
<f> can be another column in a database table from the FROM clause, a data object, or a scalarsubquery [Page 1124]
You can use the following expressions for the relational operator:
Trang 36LE less than or equal to
<= less than or equal to
> greater than
GE greater than or equal to
>= greater than or equal to
The values of the operands are converted if necessary The conversion may be dependent onthe platform and codepage
Values in Intervals
To find out whether the value of a column lies within a particular interval, use:
SELECT WHERE <s> [NOT] BETWEEN <f1> AND <f2>
The condition is true if the value of column <s> is [not] between the values of the data objects
<f1> and <f2> You cannot use BETWEEN in the ON condition of the FROM clause
Comparing Strings
To find out whether the value of a column matches a pattern, use:
SELECT WHERE <s> [NOT] LIKE <f> [ESCAPE <h>]
The condition is true if the value of the column <s> matches [does not match] the pattern in thedata object <f> You can only use this test for text fields The data type of the column must bealphanumeric <f> must have data type C
You can use the following wildcard characters in <f>:
• % for a sequence of any characters (including spaces)
• _ for a single character
For example, ABC_EFG% matches the strings ABCxEFGxyz and ABCxEFG, but not
ABCEFGxyz If you want to use the two wildcard characters explicitly in the comparison, use theESCAPE option ESCAPE <h> specifies an escape symbol <h> If preceded by <h>, the
wildcards and the escape symbol itself lose their usual function within the pattern <f> The use of_ and % corresponds to Standard SQL usage Logical expressions elsewhere in ABAP use otherwildcard characters (+ and *)
You cannot use LIKE in the ON condition of the FROM clause
Checking Lists of Values
To find out whether the value of a column is contained in a list of values, use:
SELECT WHERE <s> [NOT] IN (<f1>, , <fn>)
Trang 37To find out whether the selection of a subquery [Page 1124] contains lines at all, use:
SELECT WHERE [NOT] EXISTS <subquery>
This condition is true if the result set of the subquery <subquery> contains at least one [no] line.The subquery does not have to be scalar
You cannot check a subquery in the ON condition of the FROM clause
Checking Selection Tables
To find out whether the value of a column satisfies the conditions in a selection table [Page 719],use:
SELECT WHERE <s> [NOT] IN <seltab>
The condition is true if the value of <s> [does not] satisfy the conditions stored in <seltab>
<seltab> can be either a real selection table or a RANGES table You cannot check a selectiontable in the ON condition of the FROM clause
Checking for Null Values
To find out whether the value of a column is null, use:
SELECT WHERE <s> IS [NOT] NULL
The condition is true if the value of <s> is [not] null
Negating Conditions
To negate the result of a condition, use:
SELECT WHERE NOT <cond>
The condition is true if <cond> is false, and false if <cond> is true The result of an unknowncondition remains unknown when negated
Linking Conditions
You can combine two conditions into one using the AND and OR operators:
SELECT WHERE <cond1> AND <cond2>
This condition is true if <cond 1 > and <cond 2> are true
SELECT WHERE <cond1> OR <cond2>
This condition is true if one or both of <cond 1 > and <cond 2> are true
NOT takes priority over AND, and AND takes priority over OR However, you can also control theprocessing sequence using parentheses
Trang 38Dynamic Conditions
To specify a condition dynamically, use:
SELECT WHERE (<itab>)
where <itab> is an internal table with line type C and maximum length 72 characters All of theconditions listed above except for selection tables, can be written into the lines of <itab>
However, you may only use literals, and not the names of data objects The internal table canalso be left empty
If you only want to specify a part of the condition dynamically, use:
SELECT WHERE <cond> AND (<itab>)
You cannot link a static and a dynamic condition using OR
You may only use dynamic conditions in the WHERE clause of the SELECT statement
Tabular Conditions
The WHERE clause of the SELECT statement has a special variant that allows you to deriveconditions from the lines and columns of an internal table:
SELECT FOR ALL ENTRIES IN <itab> WHERE <cond>
<cond> may be formulated as described above If you specify a field of the internal table <itab>
as an operand in a condition, you address all lines of the internal table The comparison is thenperformed for each line of the internal table For each line, the system selects the lines from thedatabase table that satisfy the condition The result set of the SELECT statement is the union ofthe individual selections for each line of the internal table Duplicate lines are automaticallyeliminated from the result set If <itab> is empty, the addition FOR ALL ENTRIES is disregarded,and all entries are read
The internal table <itab> must have a structured line type, and each field that occurs in thecondition <cond> must be compatible with the column of the database with which it is compared
Do not use the operators LIKE, BETWEEN, and IN in comparisons using internal table fields.You may not use the ORDER BY clause in the same SELECT statement
You can use the option FOR ALL ENTRIES to replace nested select loops by operations oninternal tables This can significantly improve the performance for large sets of selected data
Examples
Conditions in the WHERE clause:
WHERE CARRID = 'UA'
This condition is true if the column CARRID has the contents UA
WHERE NUM GE 15
This condition is true if the column NUM contains numbers greater than or equal to15
WHERE CITYFROM NE 'FRANKFURT'
This condition is true if the column CITYFROM does not contain the string
FRANKFURT
Trang 39Selecting Lines
WHERE NUM BETWEEN 15 AND 45
This condition is true if the column NUM contains numbers between 15 and 45 WHERE NUM NOT BETWEEN 1 AND 99
This condition is true if the column NUM contains numbers not between 1 and 99 WHERE NAME NOT BETWEEN 'A' AND 'H'
This condition is true if the column NAME is one character long and its contents arenot between A and H
WHERE CITY LIKE '%town%'
This condition is true if the column CITY contains a string containing the pattern
‘town’
WHERE NAME NOT LIKE '_n%'
This condition is true if the column NAME contains a value whose second character
is not ‘n’
WHERE FUNCNAME LIKE 'EDIT#_%' ESCAPE '#'
This condition is true if the contents of the column FUNCNAME begin with EDIT_ WHERE CITY IN ('BERLIN', 'NEW YORK', 'LONDON')
This condition is true if the column CITY contains one of the values BERLIN, NEWYORK, or LONDON
WHERE CITY NOT IN ('FRANKFURT', 'ROME')
This condition is true if the column CITY does not contain the values FRANKFURT orROME
WHERE ( NUMBER = '0001' OR NUMBER = '0002' ) AND
NOT ( COUNTRY = 'F' OR COUNTRY = 'USA' )
This condition is true if the column NUMBER contains the value 0001 or 0002 andthe column COUNTRY contains neither F nor USA
Dynamic conditions
DATA: COND(72) TYPE C,
ITAB LIKE TABLE OF COND.
PARAMETERS: CITY1(10) TYPE C, CITY2(10) TYPE C.
DATA WA TYPE SPFLI-CITYFROM.
CONCATENATE 'CITYFROM = ''' CITY1 '''' INTO COND.
APPEND COND TO ITAB.
CONCATENATE 'OR CITYFROM = ''' CITY2 '''' INTO COND.
APPEND COND TO ITAB.
CONCATENATE 'OR CITYFROM = ''' 'BERLIN' '''' INTO COND.
APPEND COND TO ITAB.
LOOP AT ITAB INTO COND.
WRITE COND.
ENDLOOP.
Trang 40The first three lines show the contents of the internal table ITAB Exactly the
corresponding table lines are selected
Tabular conditions
DATA: BEGIN OF LINE,
CARRID TYPE SPFLI-CARRID, CONNID TYPE SPFLI-CONNID, CITYFROM TYPE SPFLI-CITYFROM, CITYTO TYPE SPFLI-CITYTO, END OF LINE,
ITAB LIKE TABLE OF LINE.
LINE-CITYFROM = 'FRANKFURT'.
LINE-CITYTO = 'BERLIN'.
APPEND LINE TO ITAB.
LINE-CITYFROM = 'NEW YORK'.
LINE-CITYTO = 'SAN FRANCISCO'.
APPEND LINE TO ITAB.
SELECT CARRID CONNID CITYFROM CITYTO
INTO CORRESPONDING FIELDS OF LINE
FOR ALL ENTRIES IN ITAB
WHERE CITYFROM = ITAB-CITYFROM AND CITYTO = ITAB-CITYTO.
WRITE: / CARRID, CONNID, CITYFROM,
LINE-CITYTO.
ENDSELECT.