Native and Open SQL in ABAP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Native and Open SQL in ABAP

In ABAP/4 programming language, there are two types of SQL being used.
1.
2.

NATIVE SQL
OPEN SQL.

Open SQL allows you to access the database tables declared in the ABAP dictionary
regardless of the database platform that the R/3 system is using.
Native SQL allows you to use database-specific SQL statements in an ABAP/4
program. This means that you can use database tables that are not administered by
ABAP dictionary, and therefore integrate data that is not part of the R/3 system.
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 the database system in use. Open SQL thus provides a uniform syntax
and semantics for all of the database systems supported by SAP. ABAP programs that
only use Open SQL statements will work in any R/3 system, regardless of the
database system in use. Open SQL statements can only work with database tables that
have been been created in the ABAP dictionary.

Basic Open SQL Commands

SELECT

INSERT

UPDATE

MODIFY

DELETE

OPEN CURSOR,
FETCH, CLOSE CURSOR
Example

TABLES SBOOK.

DATA C TYPE CURSOR,

WA LIKE SBOOK.

OPEN CURSOR C FOR SELECT * FROM SBOOK WHERE CARRID = 'LH '

AND CONNID = '0400'

AND FLDATE = '19950228'

ORDER BY PRIMARY KEY.

8
9

DO.
FETCH NEXT CURSOR C INTO WA.
IF SY-SUBRC <> 0.

10
CLOSE CURSOR C.

11
12

EXIT.
ENDIF.

13

WRITE: / WA-BOOKID, WA-CUSTOMID, WA-CUSTTYPE,

14

WA-SMOKER, WA-LUGGWEIGHT, WA-WUNIT,

15

WA-INVOICE.

16

ENDDO.

Outputs the passenger list for the Lufthansa flight 0400 on 28-02.1995:

Open SQL Return Codes


All Open SQL statements fill the following two system fields with return codes.
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.
SY-DBCNT
After an Open SQL statement, the system field SY-DBCNT contains the number of
database lines processed.

Native SQL
As already mentioned, Native SQL allows you to use database-specific SQL
statements in an ABAP program.
To use Native SQL statement, you must precede it with the EXEC SQL statement, and
follow it with the ENDEXEC statement.
Syntax

EXEC SQL [PERFORMING <form>].

2
3

<Native SQL statement>

4
5

ENDEXEC.

There is no period after Native SQL statements. Furthermore, using inverted commas
(") or an asterisk (*) at the beginning of a line in a native SQL statement does not
introduce a comment as it would in normal ABAP syntax. You need to know whether
table and field names are case-sensitive in your chosen database.
In Native SQL statements, the data is transported between the database table and the
ABAP program using host variables. These are declared in the ABAP program, and
preceded in the Native SQL statement by a colon (:). You can use elementary
structures as host variables. Exceptionally, structures in an INTO clause are treated as
though all of their fields were listed individually.
As in Open SQL, after the ENDEXEC statement, SY-DBCNT contains the number of
lines processed. In nearly all cases, SY-SUBRC contains the value 0 after the
ENDEXEC statement.

Open SQL - Performance Rules


To improve the performance of the SQL and in turn of the ABAP program, one should
take care of the following rulesKeep the Result Set Small

Using the where clause

If only one record is required from the database, use SELECT SINGLE
whenever possible .
Minimize the Amount of Data Transferred

Restrict the number of lines

If only certain fields are required from a table, use the SELECT <field1>
<field2> INTO ... statement

Restrict no of columns

Use aggregate functions


Minimize the Number of Data Transfers

Avoid nested select loops

An alternative option is to use the SELECT .. FOR ALL ENTRIES statement.


This statement can often be a lotmore efficient than performing a large number of
SELECT or SELECT SINGLE statements during a LOOP of an internal table.

Use dictionary views

Use Joins in the FROM clause

Use subqueries in the where clause


Minimize the Search Overhead

Use index fields in the where clause

When accessing databases, always ensure that the correct index is being used .
Reduce the Database Load

Buffering

Logical databases

Avoid repeated database access


Using Internal Tables to Buffer Records

To avoid executing the same SELECT multiple times (and therefore have
duplicate selects), an internal table of type HASHED can be used to improve
performance.

SAP Internal Tables

Internal Tables . Difference between Internal Tables and Work Areas


Types of Internal Tables
Creating Internal Tables
Populating Internal Tables
Reading Internal Tables
Deleting from Internal table.

What is an Internal Table?


Internal tables are used to obtain data from a fixed structure for dynamic use
in ABAP. Each line in the internal table has the same field structure. The main use for
internal tables is for storing and formatting data from a database table within a
program.

What is a Work Area?


Work areas are single rows of data. They should have the same format as any of the
internal tables. It is used to process the data in an internal table one line at a time.

Difference between Internal Table and a


Work Area?

Types of Internal Tables


There are two types of internal tables.

1.
2.

Internal tables with HEADER line


Internal tables without HEADER line.

Internal Tables with Header Line

Here the system automatically creates the work area.

The work area has the same data type as internal table.

This work area is called the HEADER line.

It is here that all the changes or any of the action on the contents of the table
are done. As a result of this, records can be directly inserted into the table or
accessed from the internal table directly.
Internal Tables without Header Line :

Here there is no work area associated with the table.


Work area is to be explicitly specified when we need to access such tables.
Hence these tables cannot be accessed directly.

Creating Internal Tables


There are many ways to create an Internal Table. Lets look at them one by one1. By Using the Type Statement
Let us now create a Internal table itab using the TYPE statement.
The syntax is Types : begin of line,

column1 type I,

column2 type I,

end of line.

Example:

TYPES : begin of line,

2
3

empno

type I,

4
5

empname(20)

type c

6
7

end of line.

The TYPES statement creates a structure line as defined.


To actually create an Internal Table itab use the following command-

Data itab type line occurs 10.

An internal table itab is created with the structure of line.Besides declaring the
structure of an internal table, the OCCURS clause also defines how many table entries
are maintained in main storage(in this case 10). Extra records are written out to paging
area and can effect performance
2. By referring to another Table
You can create an internal table by referring to an existing table. The existing table
could be a standard SAP table, a Z table or another internal table.
Syntax-

Data <f> <type> [with header line].

Example-

DATA itab TYPE line OCCURS 10 with header line.

Here an internal table itab is created of the type line with a header line. Please note
"with header line" is optional
3. By referring to existing Structure
Syntax-

Data

<f> LIKE <struct> occurs n [with header line].

Example-

DATA itab LIKE sline OCCURS 10.

Here a table itab is created having a structure same as that of sline


4. By creating a new Structure
Let us now create an internal table with a structure of our own. Here the table is
created with an Header line, by default.
Syntax -

Data : Begin of <f> occurs <n>,

2
3

<component declaration>,

4
5

.................................,

6
7

End of <f>.

Example -

Data : Begin of itab occurs 10,

2
3

column1

type I,

4
5

column2(4)

type C,

6
7

column3

like

mara-ernam,

8
9

End of itab.

Internal table itab is created

Populating Internal Tables


Now that we have successfully created some internal tables, let us see how do we
populate them with some records. There are various methods available to populate
tables
1. Append Data line by line

The first method available is the use of the APPEND statement.


Using the APPEND statement we can either add one line from another work area to
the internal table or we can add one initial line to the internal table..
Syntax -

APPEND [<wa> TO / INITIAL LINE TO] <itable>.

Here work area <wa> or the Initial Line is appended to the internal table <itable>.
The system variable SY-TABIX contains the index of the appended line.
Example:

Data: Begin of itab occurs 10,

2
3

col1 type C,

4
5

col2 type I,

6
7

end of itab.

8
9

Append initial line to itab.

Results : ' ' '0'


Initial lines adds a line initialized with the correct value for its type to the table. Here ,
col1 is an integer and col2 is a character. Then APPEND initial line , adds
a line initialized with respect to the data type of the columns, i.e. 0 for Col1 and space
for Col2.

2. Using COLLECT statement

COLLECT is another form of statement used for populating the internal tables.
Generally COLLECT is used while inserting lines into an internal table with unique
standard key.
Syntax-

COLLECT [<wa> INTO] <itable>.

Incase of tables with Header line, INTO option is omitted. Suppose there is already an
entry having a key same as the one you are trying to append, then a new line is not
added to the table, but the numeric fields of both the entries are added and only one
entry corresponding to the key is present. Value of SY-TABIX is changed to the row
of the original entry. Else COLLECT acts similar to APPEND and SY-TABIX
contains the index of the processed line.
3. Using INSERT statement
INSERT statement adds a line/work area to the internal table. You can specify the
position at which the new lineis to be added by using the INDEX clause with the
INSERT statement.
Syntax
INSERT [<wa> INTO / INITIAL LINE INTO] <itable> [index <idx>].
Here, the work area <wa> or INITIAL LINE is inserted into internal table
<itable> at index <idx>.

Copying Internal Tables


The contents of one internal table can be copied to another by using the APPEND
LINES or INSERT LINES statement. A more simpler way is to use any of the
following syntax's.

MOVE

<itab1> To <itab2>.

2
3

OR

4
5

<itab1> = <itab2>.

These copy the contents of ITAB1 to ITAB2. Incase of internal tables with
header line we have to use [] inorder to distinguish from work area. So, to copy
contents of internal tables with header line the syntax becomes,

itab1[] = itab2[].

Reading Internal Tables


We are now familiar with the creation of internal tables and populating them
with data. We will now see how do we actually use the data or retrieve the data from
the internal tables.
1. Using Loop -Endloop
One of the ways of accessing or reading the internal table is by using LOOPENDLOOP.
Syntax

LOOP AT <itable> [INTO <wa>]

2
3

...................................

4
5

ENDLOOP.

Here when you say LOOP AT ITABLE, then the internal table ITABLE is
read line by line. You can access the values of the columns for that line during any
part of the LOOP-ENDLOOP structure. The value of the SY-SUBRCis set to 0, even if
only one record is read.
2. Using READ
The other method of reading the internal table is by using the READ statement.
Syntax-

READ TABLE <itable> [INTO <wa>] INDEX <idx>.

This statement reads the current line or line as specified by index <idx>. The value
of SY-TABIX is the index of the line read. If an entry with the specified index is found,
then SY-SUBRC is set to 0. If the specified index is less than 0, then run-time error
occurs. If the specified index exceeds table size then SY-SUBRC is set to 4.

Deleting Internal Tables


There are many ways for deleting lines from an internal table.
1. Deleting lines in a loop.
This is the simplest way for deleting lines.
Sytax

DELETE <ITABLE>.

This statement works only within a loop. It deletes the current line. You can delete the
lines in a loop conditionally by adding the WHERE clause.
2. Deleting lines using the index.

This is used to delete a line from internal table at any know index.
Syntax

DELETE <ITABLE> INDEX <IDX>.

The line with the index <IDX> is deleted. The index of the following line is
decremented by 1.

Table Controls
Table controls and step loops are objects for screen table display that you add to a
screen in the Screen Painter.
From a programming standpoint, table controls and step loops are almost exactly the
same. Table controls are simply improved step loops that display data with the look
and feel associated with tables in desktop applications.
With table controls, the user can:

Scroll through the table vertically and horizontally

Re-size the width of a column

Scroll within a field (when field contents are wider than the field)

Select table rows or columns

Re-order the sequence of columns

Save the current display settings for future use


Table controls also offer special formatting features (some automatic, some optional)
that make tables easier to look at and use. Table Control provides

automatic table resizing (vertical and horizontal) when the user resizes the
window

separator lines between rows and between columns (vertical and horizontal)

column header fields for all columns


One feature of step loops is that their table rows can span more than one line on the
screen. A row of a table control, on the other hand, must always be contained in a
single line (although scrolling is possible).
In general, many of the features provided by the table control are handled locally by

your system's SAPgui frontend, so you do not need to program them yourself. The
only notable exception to this is vertical scrolling.
Example (Transaction TZ60)

Syntax
To handle table controls in ABAP programs, you must declare a control in the
declaration part of the program for each table control using the following statement:

CONTROLS &lt;ctrl&gt; TYPE TABLEVIEW USING SCREEN &lt;scr&gt;

where <ctrl> is the name of the table control on a screen in the ABAP program. The
control allows the ABAP program to read the attributes of the table control and to
influence the control .Here, <scr> is the screen number where the initial values of
the table are loaded.
Cursor Position for a table control can be set in following ways:
At PBO you can set the cursor on a specific field of a specific row of a table control.
1

SET CURSOR FIELD <f> LINE <lin> [OFFSET <off>]

Using the optional addition OFFSET, you can enter the offset of the cursor in the field
as described under Setting the Cursor Position.
At PAI you can read the current cursor position.
GET CURSOR FIELD <f> LINE <lin> ...

In addition to the information given under Finding Out the Cursor Position,
field <lin> contains information on which row of the table control the cursor is
currently on. You can also use
1

GET CURSOR LINE <lin>.

to determine the row of the table control. SY-SUBRC allows you to check if the cursor
is placed in a row of a table control.
For getting the corresponding line of the internal table :
1
2
3
4
5

GET CURSOR line <lin>.


ind = <table_control>-top_line + <lin> - 1.
Read table <itab> index ind.

The system variable stepl - contains the current table line index in a loop ...
endloop. Loopc - contains number of lines visible in the table
To create a table control
1.Add a table control element to your screen
2.Give a name to the table control. In the ABAP program declare a structure with the
same ( CONTROLS <tcl> type TABLEVIEW USING SCREEN <scrn >)
3.To create fields go to the Dict./Program fields function.

Enter the name of the structure whose fields you want. (If you want it to pick it
from dictionary of your program click the relevant puhbutton).

In the field list choose the fields you want and choose ok.

Click in the table control area


If you want a selection column , check the appropriate check box in the attributes and
give it a name. Create the field in the ABAP program.
In the PBO you should have the statement

1
2
3

LOOP at <itab> USING CONTROL <cntrl_name>.


ENDLOOP.

In the PAI you should have.


1
2
3

LOOP at <itab>.
ENDLOOP.

It is within the loops that data transfer happens between the screen and the
internal table.When you populate the internal table use DESCRIBE TABLE <itab>
LINES <cntrl_name>-lines, to store the total number of lines in the control.The
FIELD statement can be used to control when the data transfer happens
To change the attributes of individual cells temporarily change the SCREEN table in
the PBO. You can change the attributes of the structure created by the CONTROLS
statement
1
2
3
4
5

<cntrl>-fixed_cols etc are the attributes of the control


<cntrl>-cols-index etc are the attributes of the columns.
<cntrl>-cols-screen-invisible etc are the screen attributes of each column.

You might also like