Вы находитесь на странице: 1из 48

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 Codes
1) SY-SUBRC :
After every Open 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) An internal table is 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) The body holds 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) The header line is 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
7) To define an internal table body, use OCCURS N on the definition of any
field string except tables. occurs creates the body of the internal table.
The memory for the body is not allocated until the first row is added to it.
Without occurs, you only have a field string.
8) To define an internal table with a header line, you must include
either begin of or with header line in the definition. A header line is
automatically created if begin of appears in the definition.
9) If you use like instead of begin of, the internal table will not have a
header line unless you add with header line after the occurs clause.
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
the append statement.
b) Append copies 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 statement append initial line to it appends 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 it and append it.



Append Statement
After append, sy-tabix is set to the relative row number of the row just
appended. For example, after appending the first row, sy-tabix will be set
to 1. After appending the second row, sy-tabix will be 2, 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 statement append it to it appends the header line named it to
the body named it. The statement append it does the same thing, because
the default work area is the header line.





Using the occurs Addition

a) Occurs does not limit the number of rows that can be added to the
internal table.
For example, if you specify occurs 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 specify occurs 0. If you do this, the system
allocates 8KB pages of memory at a time.
c) For peak performance and minimum wasted memory, choose
an occurs value 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 the occurs value 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 table
Use loop at to read multiple rows from the internal table.
Use read table to read a single row.

To read some or all rows from an internal table, you can use the
loop at statement.
Loop at reads 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.

If from is not specified, the default is to begin reading from the first row.
If to is 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 following end loop.

2) Continue Goes immediately to the end loop statement, 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
following end loop.

3) Check exp If exp is true, processing continues as if this statement had
not been executed. If exp is false, its effect is the same as continue.



Internal Tables
Types of Internal Tables
Difference of Internal Tables
Reading Data
The Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
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_function can be a function such as SUM, COUNT, MIN,
or MAX.



Aggregate Functions


GROUP BY CLAUSE
Examples:
1) SELECT DEPT, AVG(SALARY) FROM EMPLOYEE GROUP BY DEPT ;
DEPT AVG(SALARY)
MKT 33500
MGT 45000
LIB 22000
RND 27500
FIN 42000
2) 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 25000
Having Clause
The having clause is used with the group by clause when comparisons
need to be made with those aggregate functions .
SYNTAX: SELECT lines s
1
[AS a
1
] s
2
[AS a
2
]...
agg s
m
[AS a
m
] agg s
n
[AS a
n
]
GROUP BY s
1
s
2
....
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 : ASC is used as the default.
Example:
SELECT * FROM `members` ORDER BY `gender`,`date_of_birth` DESC.


Different Types of SELECT Statements
The SELECT clause can be divided into two parts for lines and columns:

SELECT <lines> <cols> ...
a) <lines> specifies whether you want to read one or more lines.
b) <cols> defines the column selection.
1) Reading a Single Line :
SELECT SINGLE <cols> ... 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 STATEMENTS
2) 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 .
3) 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 STATEMENTS
4) 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( <COLUMNNAME> ) INTO (<VARIABLE>) FROM <TABLE>.
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 STATMENTS
Syntax: SELECT MIN( <column> ) INTO (<variable>) FROM <table>.
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 <TABLE> INTO TABLE <ITAB> UP TO
<NUMBEROFROWS> rows.
Example: data : it_mara type TABLE OF mara.
**Get 50 rows form starting
select * FROM mara INTO TABLE it_mara UP TO 50 rows.






SELECT STATEMENTS
7) 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 <COULMN> FROM <TABLE> INTO TABLE <ITAB>.

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 <TABLE> INTO TABLE <ITAB> ORDER BY <COLUMN>
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 <ITAB> 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 ENTRIES
9) Syntax
FOR ALL ENTRIES IN itab WHERE ... col operator itab-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 ENTRIES

PARAMETERS: 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 <database table> FROM <work area> .
2) INSERT INTO <database table> VALUES <work area>.
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:
UPDATE <table name> SET <assignment list> ( <where clause> ) .

Example :

1) UPDATE PA0003 SET UNAME = SY-UNAME.

2) UPDATE employees
SET employee_name = 'Mary Jones'
WHERE employee_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 f
1
f
2
...].

data: idx type sy-tabix.
data: itab type standard table of t508a.
data: wa_tab type t508a.

select * from t508a into table itab
where 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:
1) DELETE FROM <dbtab> WHERE <cond>.
NOTE: Here all the lines matching the condition (<cond>) in the database table
(<dbtab>) will be deleted.

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

3) DELETE <dbtab> FROM TABLE <itab>.
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 <itab> FROM <wa>.
Here the line in the internal table that matching the primary key with the
specified work area will be deleted.
2) DELETE TABLE <itab> WITH TABLE KEY <k1> = <f 1> <k n> = <f n>.
Here the lines in the table with the specified table keys will be deleted.
3) DELETE <itab> WHERE <cond>.
Here the lines in the table that matching the specified conditions
will be deleted.
4) DELETE ADJACENT DUPLICATE ENTRIES FROM <itab> [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'.

Вам также может понравиться