Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Reading Sample Sap Press Sqlscript For Sap Hana

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

First-hand knowledge.

Browse the Book


This sample chapter demonstrates the techniques for using SQLScript
procedures for ABAP programs. It starts with the most important concept,
AMDP, followed by the other development objects of the AMDP frame-
work. The end of this chapter briefly shows you an alternative to AMPD
and give some basic recommendations for using database procedures
in ABAP programs.

“SQLScript in ABAP Programs”

Contents

Index

The Author

Jörg Brandeis

SQLScript for SAP HANA


387 pages, 2nd, updated and revised edition 2021, $79.95
ISBN978-1-4932-2139-4

www.sap-press.com/5336
Chapter 8
SQLScript in ABAP Programs
To enable the use of SQLScript from within ABAP programs, various
options are available, for example, the ABAP-managed database proce-
dures (AMDP) framework or table functions. In this chapter, we’ll provide
you an overview of these techniques.

In previous chapters, you learned how to write effective SQLScript source


code. You can use various options to call this source code from within the
SAP NetWeaver ABAP platform. From the ABAP perspective, SQLScript basi-
cally is Native SQL, which is how all database-specific SQL dialects are
described. The opposite of Native SQL is Open SQL, which is part of the ABAP
programming language. Open SQL is database-independent and is trans-
lated into the corresponding Native SQL at runtime.

Consider Other Database Systems


If you use Native SQL in ABAP, the corresponding programs and classes are
restricted for use in a particular database system. To be compatible for
multiple database systems, you must develop along several tracks. Accord-
ingly, you should create different implementations for the various SQL
variants. In this chapter, we’ll focus on following a two-track approach in
our examples, using both techniques:
쐍 SQLScript for SAP HANA databases
쐍 Open SQL for all other databases

In the following section, you will learn the techniques for using SQLScript
procedures for ABAP programs. We’ll start with the most important con-
cept, AMDP, followed by the other development objects of the AMDP
framework. And at the end of this chapter, we will briefly show you an alter-
native to AMPD and give some basic recommendations for using database
procedures in ABAP programs.

8.1 AMDP Procedures


From the point of view of an ABAP developer, an AMDP procedure is a
method of an ABAP class, which is implemented in the SQLScript

283
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

programming language. Being a method solves several problems, such as


AMDP Procedure CDS Table Function AMDP Function
the following:
Call from Like an ABAP In a SELECT state- Not possible
쐍 The SQL procedure is called as a method call of an ABAP class. As a result,
ABAP method ment
the procedure call is perfectly integrated in ABAP.
Implementa- In a static or In PUBLIC, static In a static or
쐍 The transport of the database procedure is performed using the ABAP
tion instance method method of a static instance method
class rather than requiring several transport mechanisms that must be
class
kept in sync.
Two-track Inheritable Possible by case Not relevant, since
쐍 At the time of development, the developer does not need direct access to
development distinction only callable from
the SAP HANA database with the appropriate authorizations. Working 8
other AMDP meth-
with the usual ABAP developer authorizations with the ABAP develop- ods
ment tools is sufficient.
Type of data Read and write Read-only Read-only
In the following sections, the terms AMDP and AMDP procedure are used access
interchangeably. If not explicitly mentioned, the information doesn’t refer
Where are the When you define When you define When you define
to AMDP functions.
parameters the method the CDS object the method
Before we jump into using AMDP, however, we’ll first provide you with an defined?
initial introduction to some of the concepts of AMDP.
Type of Any IMPORTING, Any scalar IMPORT- Any scalar IMPORT-
parameters EXPORT, and ING and exactly ING and exactly
CHANGE one table-like one table-like
8.1.1 Introduction to AMDP
RETURNING param- RETURNING param-
AMDP The term ABAP-managed database procedure (AMDP) stands for the frame- eter eter
work recommended by SAP for using SQLScript code in ABAP programs.
This concept serves as the basis for creating, managing, and calling data- Table 8.1 Comparison of the Three AMDP Objects
base procedures and functions. The basic idea behind AMDP is that the
source code of SAP HANA database objects can be wrapped in an imple-
AMDP Framework
mentation of methods of an ABAP class. The corresponding SAP HANA
database object is then generated from this implementation when With the release of SAP NetWeaver 7.4 Support Package Stack (SPS) 05,
required. AMDPs were introduced as a framework for managing and calling data-
base procedures in the SAP HANA database.
Three different objects can be created with the AMDP framework:
With the release of SAP NetWeaver 7.5, AMDP functions have been added
쐍 AMDP procedures can be called like methods of an ABAP class. These pro- to this concept. Although these functions are technically not procedures,
cedures are implemented in SQLScript. The caller of the method doesn’t but functions, the name AMDP is also used for them.
know that the procedure is actually a database procedure.
AMDP classes are classes that implement the interface IF_AMDP_MARKER_
쐍 Core data services (CDS) table functions are AMDP functions that are HDB and that contain at least one AMDP method.
encapsulated by a CDS object and can therefore be called from ABAP or
AMDP methods can be either AMDP procedures or AMDP functions. AMDP
Open SQL like a normal database view via a SELECT query. functions either implement a CDS table function, or AMDP functions are
쐍 AMDP functions for AMDP methods can’t be called directly from ABAP or available internally for other AMDP methods.
Open SQL. However, these functions can be used when implementing
other AMDP objects in SQLScript source code. The AMDP framework provides ABAP developers with extensive options Tools

Table 8.1 compares the most important properties of the three objects. for implementation according to the code-to-data paradigm. Direct access
to the SAP HANA database is not absolutely necessary since all develop-

284 285
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

ment objects can be implemented via the ABAP development tools in the able in Open SQL, or if the transport of large amounts of data between the
Eclipse development environment. You can also use a debugger for the database server and SAP NetWeaver Application Server (AS) must be
SQLScript code in the AMDP methods. This AMDB debugger is described in avoided.
more detail in Chapter 11, Section 11.2.3.
If SAP HANA data models such as calculation views are modeled or if proce- SPACE and the Empty Character String
dures and functions are developed outside the AMDP framework, direct In ABAP, a global constant SPACE, of length 1, contains exactly one blank
database access with corresponding authorizations will be necessary. The character. This constant is often used for selecting data, for example, in
Eclipse plug-ins from SAP HANA Studio must also be installed. the following WHERE clause:
Benefits of AMDP When does using SQLScript in an ABAP program make sense? No general WHERE recordmode = SPACE 8
answer exists for this question. Basically, the use of AMDPs makes sense
In fact, however, the database doesn’t store the space character, but an
above all when significant performance improvements can be achieved,
empty string of length 0. ABAP therefore does not distinguish between an
which is particularly the case in the following scenarios:
empty string and a single space character.
쐍 If using SQLScript prevents the transport of large amounts of data However, SQLScript does distinguish between these two strings. For use in
between the database and SAP NetWeaver Application Server (AS). an ABAP system, SAP has introduced the ABAPVARCHAR mode. This mode
쐍 If the SQLScript procedure is programmed declaratively and can there- converts all string literals with exactly one blank character into an empty
fore be easily parallelized and optimized by the SAP HANA database. string in SQLScript as well, as in the following query:
쐍 If transformations with routines are to be executed directly in the SAP SELECT session_context( 'ABAPVARCHARMODE' ) FROM DUMMY
HANA database in SAP Business Warehouse (SAP BW). Data transfer pro- Furthermore, you can test whether this mode is switched on. Since this
cesses will be accelerated considerably, regardless of whether the previ- mode is controlled by the session variable ABAPVARCHAR, you can also turn
ous ABAP code worked with database access or not. this mod on and off in the code, as shown in Listing 8.1.
Disadvantages But the use of AMDPs also has a few disadvantages. You must always con- DO BEGIN
sider whether you want to accept these disadvantages for the expected per- SET 'ABAPVARCHARMODE' = 'true';
formance improvements. The following reasons, among others, speak SELECT length(' '),
against the use of AMDPs: '->' || ' ' || '<-' FROM dummy;

쐍 The application developer must be proficient in several programming


SET 'ABAPVARCHARMODE' = 'false';
languages. Sometimes, a well-implemented ABAP method is better than
SELECT length(' '),
a poorly implemented AMDP.
'->' || ' ' || '<-' FROM dummy;
쐍 SAP GUI is not suitable for developing AMDPs. END;
쐍 The application logic is distributed between the database server and SAP Listing 8.1 Testing the ABAP VARCHAR mode
NetWeaver Application Server (AS).
The result depends on the mode set. If you really need exactly one space as
쐍 Performance is not improved in all cases.
a string in SQLScript, use the expression CHAR(32).
쐍 AMDP developments can’t be used in other database systems. For a suit-
able procedure for parallel development, still leveraging the advantages
of SAP HANA with AMDPs, Section 8.1.5.
8.1.2 Creating AMDP Procedures
Alternatives You should always evaluate the alternatives before using AMDPs, includ- You can create an AMDP method only in a global class, which implements IF_AMDP_MARKER_
ing, for example, CDS views and the extended features of Open SQL of the the marker interface IF_AMDP_MARKER_HDB. The interface itself has no meth- HDB
latest SAP NetWeaver releases. According to the SAP documentation (http:// ods; it serves exclusively to mark AMDP classes.
s-prs.co/v533626), AMDPs should only be used if database-specific functions,
such as the SQL function for currency conversion, is required but not avail-

286 287
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

An AMDP class can include both normal ABAP methods and AMDP meth- with regard to parameters than ABAP methods. Accordingly, the following
ods. Whether a method is implemented as AMDP is not specified in the restrictions must of course also apply to AMDP methods:
method declaration. Listing 8.2 shows an example. 쐍 First, all parameters must be completely typed. Generic data types such
CLASS zcl_amdp_demo DEFINITION as TYPE TABLE or REF TO DATA are not permitted.
PUBLIC 쐍 Since SQLScript doesn’t know any structures, only scalar data types and
CREATE PUBLIC . table types may be used as parameters. The table types can only use sca-
lar data types in their row structure.
PUBLIC SECTION. 쐍 All parameters must be transferred as value parameters (call by value);
INTERFACES if_amdp_marker_hdb.
you can’t use any reference parameters (call by reference). The reason for 8
TYPES gty_tt_countries TYPE TABLE OF t005t .
this restriction is obvious when you consider that the application server
METHODS get_countries
is running on a different system than the database. Accordingly, no
IMPORTING
shared memory area exists that both systems reference.
VALUE(iv_langu) TYPE langu
쐍 You can only use IMPORTING, EXPORTING, and CHANGING parameters with
EXPORTING
VALUE(et_country) TYPE gty_tt_countries AMDP procedures. The use of RETURNING parameters is not possible.
CHANGING 쐍 Only AMDP exception classes can be declared in the signature of the
VALUE(cv_subrc) TYPE sy-subrc. method. These exception classes are the subclasses of CX_AMDP_ERROR. If
ENDCLASS. these exception classes are declared, the caller of the AMDP method can
handle these exceptions. However, if not declared, these errors result in
CLASS zcl_amdp_demo IMPLEMENTATION. a dump.
METHOD get_countries
AMDP procedures are developed in the SQLScript language, which is indi- Implementing
BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT
cated to the system by the addition BY DATABASE PROCEDURE FOR HDB LANGUAGE an AMDP
USING t005t.
SQLSCRIPT.

et_country = select * If an AMDP implementation only reads data, you can optionally specify the
from t005t addition OPTIONS READ-ONLY.
where spras = :iv_langu; The optional addition USING enables you to tell an AMDP implementation USING
that you want to use the corresponding tables, views, AMDP functions, or
SELECT CASE AMDP procedures from the default database schema of the SAP NetWeaver
WHEN COUNT(*) > 0 system. Thus, you can use this name without having to explicitly specify
THEN 0
the relevant database schema in the SQLScript source code. The objects are
ELSE 4
only separated by whitespaces and listed after the keyword USING. Note that
END AS subrc
this code is still ABAP code. If, for example, you specify a table generated by
INTO cv_subrc
SAP BW from the generation namespace, /BIC/ or /BI0/, you do not need to
FROM :et_country;
use any quotation marks, for example:
ENDMETHOD.
ENDCLASS. ...USING /BI0/PPLANT.

Listing 8.2 Example of a Simple AMDP Method If you access this table in SQLScript code, however, you must use special
notation, since the slash is not permitted in simple notation, as in the fol-
Restrictions on the An SQLScript procedure is generated at a later time from the source code of
lowing:
method signature an AMDP method. However, these database procedures are more restrictive
SELECT ... FROM "/BI0/PPLANT".

288 289
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

USING for The use of AMDP procedures and functions is declared in the USING clause
AMDP objects via the name of the associated ABAP method using the notation CLASS=
>METHOD. Listing 8.3 contains an example of the keywords in the METHOD
clause of the method implementation. Everything after the period in line 5
up to the keyword ENDMETHOD is interpreted as SQLScript.

1 METHOD get_countries
2 BY DATABASE PROCEDURE FOR HDB
3 LANGUAGE SQLSCRIPT
4 OPTIONS READ-ONLY
5 USING t005t. 8
6
7 <SQLScript-Code>
8 ENDMETHOD.

Listing 8.3 Keywords for Implementing an AMDP Method


Figure 8.1 Generated Objects of an AMDP Procedure

A General Concept for a Specific Database The Generated AMDP Procedure


Basically, all instructions and declarations in connection with AMDP are The procedure ZCL_AMDP_DEMO=>GET_COUNTRIES contains the actual SQLScript
designed in such a way that AMDPs can be implemented in different data- source code. However, the code has been slightly modified, as shown in
base systems and in different languages. Accordingly, the implementation Listing 8.4.
of AMDP methods also includes the mandatory entries FOR <databasesys-
tem> and LANGUAGE <querylanguage>. CREATE PROCEDURE
"ZCL_AMDP_DEMO=>GET_COUNTRIES"
However, to date (SAP NetWeaver 7.51), only implementations for the SAP
(
HANA database with the SQLScript language are possible. The language L
IN "IV_LANGU" NVARCHAR (000001),
may only be used within SAP.
OUT "EV_SUBRC" INTEGER,
The other database systems under SAP NetWeaver each have their own IN "CT_COUNTRY__IN__" "ZCL_AMDP_DEMO=>GET_COUNTRIES=>P00000#
programming languages, such as Oracle’s PL/SQL language. However, ttyp",
these languages can’t be used to implement AMDPs. OUT "CT_COUNTRY" "ZCL_AMDP_DEMO=>GET_COUNTRIES=>P00000#ttyp"
)
LANGUAGE sqlscript SQL SECURITY INVOKER
8.1.3 Generated Objects of an AMDP Method AS BEGIN
"CT_COUNTRY" = select * from :CT_COUNTRY__IN__ ;
An ABAP class serves as an envelope for the code of the AMDP procedure.
BEGIN
Some SAP HANA database objects are automatically generated from this
lt_countries = SELECT land1 FROM :CT_COUNTRY;
class. Figure 8.1 shows the objects generated by the procedure found in List-
et_country = SELECT t5.*
ing 8.2.
FROM "ZCL_AMDP_DEMO=>T005T#covw" AS t5
Note that a table type, two procedures, a database table, and a view have INNER JOIN :LT_COUNTRIES AS countries
been generated for an AMDP method. Each object has its own special tasks, ON t5.land1 = countries.land1
which we’ll explain next. WHERE t5.spras = :IV_LANGU;

SELECT CASE
WHEN COUNT(*) > 0

290 291
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

THEN 0 The source code shown in Listing 8.5 involves only two parameters: IV_
ELSE 4 LANGU and EV_SUBRC. The CHANGING table parameter CT_COUNTRIES is not part of
END AS subrc the parameter definition of the procedure.
INTO ev_subrc
The return of the table CT_COUNTRIES is not carried out via an explicitly Return of the table
FROM :CT_COUNTRY;
defined table parameter but via the result set of the procedure. After the call
END;
of the AMDP procedure, a SELECT query is executed to the table CT_COUN-
TRIES.
END;
CREATE PROCEDURE
Listing 8.4 Source Code of Procedure ZCL_AMDP_DEMO=>GET_COUNTRIES
"ZCL_AMDP_DEMO=>GET_COUNTRIES#stb2#20180301173139" 8
(
Parameter list The relevant passages in the source code are highlighted in bold type. First,
IN "IV_LANGU" NVARCHAR (000001),
you’ll see the parameter list. Notice that the CHANGING parameter CT_COUNTRY
OUT "EV_SUBRC" INTEGER
occurs twice. This repetition occurs because, in SQLScript, an INOUT parame-
)
ter must have a scalar type. Thus, in addition to the OUT parameter CT_COUN-
LANGUAGE sqlscript SQL SECURITY INVOKER AS BEGIN
TRY, the IN parameter CT_COUNTRY__IN__ is created. In the first line after AS
BEGIN, the parameter CT_COUNTRY is filled with the contents of CT_COUNTRY__
"CT_COUNTRY__IN__" = SELECT * FROM "ZCL_AMDP_DEMO=>GET_COUNTRIES=
IN__, which simulates the behavior of a CHANGING parameter. >P00000#tft#20180301173139" ;
CALL "ZCL_AMDP_DEMO=>GET_COUNTRIES" (
Table Types for the Table Parameters "CT_COUNTRY__IN__" => :CT_COUNTRY__IN__ ,
In the parameter interface of an SQLScript procedure, all parameters must "IV_LANGU" => :IV_LANGU ,
be typed. In the case of table parameters, corresponding table types are cre- "EV_SUBRC" => :EV_SUBRC ,
ated for AMDP procedures. In our example, CT_COUNTRY is typed using the "CT_COUNTRY" => :CT_COUNTRY
generated table type ZCL_AMDP_DEMO=>GET_COUNTRIES =>P00000#ttyp. );
SELECT * FROM :CT_COUNTRY;

USING Views
END;
Each access to a table declared via USING is encapsulated by a view. In our
example, this view is the database view ZCL_AMDP_DEMO =>T005T#covw, which Listing 8.5 Source Code of the Stub Procedure

replaces direct access to table T005T. The task of the view is to compensate
for any field sequences that differ between the ABAP Dictionary and the Input Tables as Global Temporary Tables
database object. The values of table parameters are transferred into the stub procedure via
generated, global temporary tables. Before the actual AMDP procedure is
Stub Procedure called, the table variables are initialized from the global temporary table. In
our example, CT_COUNTRIES is filled from the global temporary table in the
In addition to the actual AMDP procedure, a second procedure is generated,
following way:
which is named according to the name pattern <AMDPprocedure>#stb2#
<timestamp>. Accordingly, in our example, the procedure name is ZCL_AMDP_ "CT_COUNTRY__IN__" = SELECT * FROM "ZCL_AMDP_DEMO=>GET_COUNTRIES=>
DEMO=>GET_COUNTRIES#stb2#20180301173139. P00000#tft#20180301173139"
This procedure serves as a stub for the call from SAP NetWeaver. The time-
Here again, a timestamp is part of the name.
stamp (Section 8.1.4) is used for versioning purposes in case the object
changes.

292 293
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

8.1.4 Lifecycle of the Generated Objects both is not a problem, since whether a method is written in SQLScript or
ABAP is only determined when the method is implemented and doesn’t
The lifecycle of the AMDP classes and methods is not identical to the lifecy-
affect the definition of the method. In the following sections, we’ll look at a
cle of their corresponding SAP HANA objects. In the following sections,
few typical use cases where more than one implementation exists.
we’ll describe the effects of various actions carried out in the SAP
NetWeaver Application Server (AS) on the corresponding SAP HANA
objects: Clean Code: Separation of Concerns
Object lifecycles 쐍 Creating and activating an AMDP class The principle of the separation of concerns was formulated in 1974 by Eds-
Creating and activating an AMDP class with an AMDP method doesn’t ger W. Dijkstra. Under this principle, different tasks should also be per-
generate any database objects. Thus, you can transport AMDP classes to formed by different components in a system. In our case, separation of
8
SAP NetWeaver systems without an SAP HANA database. If an SAP HANA concerns means that database access should not be mixed with other
database is available as the central database system, the database objects application code. Instead, different classes should be created for each
are temporarily created and immediately deleted again for the syntax aspect.
check. If you adhere to this principle, two-track development of AMDP and ABAP
implementations is also relatively simple. Classes for database access can
쐍 Executing an AMDP method
be easily exchanged.
Database objects, introduced in the previous section, are generated
during the first execution of the AMDP method. The timestamp in the
object’s name refers to the activation time of the class.
Support of Different Database Systems
Even if a class contains several AMDP methods, only the objects for the
If the application needs to run on different database systems, you can have
executed methods are generated.
one implementation in Open SQL and one in AMDP. Of course, you can also
쐍 Repeated editing and activation of an AMDP class
create special implementations for each of the other databases.
The stub procedures for all AMDP procedures are deleted when the class
Switching between the various implementations should take place auto- Switching between
is reactivated. The same applies to all generated AMDP procedures that
matically at runtime. For this purpose, you can use the factory design pat- implementations
have changed. The generated global temporary table will remain for the
tern. As shown in Figure 8.2, we’ll use a static factory method, GET_INSTANCE,
time being.
to generate the instances. Based on the SY-DBSYS field, this method decides
The next time the program is executed, the objects are created again
which class implementation should be used.
with the new timestamp. Since global temporary tables are not deleted
immediately, some objects with different timestamps can still exist at
the same time. ZCL_READ_XYZ

쐍 Deleting an AMDP class + EXECUTE( ): Table of data


The generated objects on SAP HANA are deleted upon the deletion of the + GET_INSTANCE( ): ZCL_READ_XYZ
AMDP class.

The late generation of SAP HANA objects means that transporting AMDP
classes in a mixed system landscape can run smoothly. Versioning of Extends Extends
changes is carried out using timestamps to ensure that the correct version
of a procedure is always called. ZCL_READ_XYZ_AMDP ZCL_READ_XYZ_OSQL

+ EXECUTE( ): Table of data + EXECUTE( ): Table of data


8.1.5 Two-Track Development
There are different reasons why you would want both an ABAP and an AMDP Figure 8.2 UML Diagram for Two Implementations of Database Access with a
implementation of a method. From a technical point of view, developing Static Factor Method

294 295
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

Listing 8.6 shows a simple implementation of the method GET_INSTANCE. Of


course, other database systems could also be considered. MY_CLASS

METHOD get_instance. + METHOD_X( )

DATA lv_classname TYPE classname. # AMDP_SUITABLE_METHOD_X( )

CASE sy-dbsys.
MY_CLASS
WHEN 'HDB'.
Refactoring Extends
lv_classname = 'ZCL_READ_XYZ_AMDP'. + METHOD_X( )
WHEN OTHERS.
lv_classname = 'ZCL_READ_XYZ_OSQL'. MY_CLASS_AMDP
ENDCASE. 8
# AMDP_SUITABLE_METHOD_X( )

CREATE OBJECT ro_instance TYPE (lv_classname).


ENDMETHOD. Figure 8.3 Outsourcing the Logic to an AMDP-Compatible Method and
Redefinition
Listing 8.6 Static Factory Method GET_INSTANCE in ABAP
To switch between the two versions of the class, you can use a factory
Comparison between ABAP and AMDP method again.
If you want to test the differences between the implementations in ABAP
and AMDP in runtime and result, inheritance is rather useful concept as in, ABAP Unit Tests
for example, the previous section where we leveraged inheritance from a A mock object is often used to insert data into a class to be tested in a unit
shared superclass. However, you’ll need a suitable switch that allows you test. This object has the same external interface as a real object but provides
the flexibility to select the relevant implementation. You can create these predefined data that is independent of the database state. Classes that con-
switches, for example, by using entries in a Customizing table or by defin- tain an AMDP can, for example, be replaced for unit tests by a local subclass
ing user parameters. These switches can then be queried in a corresponding in which the AMDP method has been replaced by a corresponding ABAP
factory method. implementation. For such tests, you can use the dependency injection
design pattern.
Retroactive Implementation as AMDP Note that AMDP implementation is only possible in global classes. In local Only in global
Let’s say you implemented a method in ABAP and later discover perfor- classes, only an implementation in ABAP is allowed. classes
mance problems; you can implement the method as an AMDP. To preserve
the original implementation for performance and result comparisons, cre-
ating a subclass is a good idea. The corresponding method is then imple- 8.1.6 Using AMDP Procedures in Other AMDP Procedures
mented as an AMDP in this subclass. An AMDP method generates a corresponding database procedure the first
Refactoring Due to restrictions on AMDPs regarding access to instance attributes and time it is executed (see also Section 8.1.4). This database procedure can of
parameters, this procedure must be taken into account when creating your course also be called directly in any SQLScript code, especially in other
methods. Alternatively, you can carry out a refactoring, as shown in Figure AMDP procedures. Thus, a certain modularization of the programs is possi-
8.3, by following this approach: ble without direct development access to the database.

1. Outsource the logic into a new method that meets the requirements of Listing 8.7 shows a simple example of calling an AMDP procedure in Example

an AMDP: no access to class and instance data, no RETURNING parameters, another AMDP method. Note that a CHANGING parameter in the AMDP
no parameters with structures. method has the following two associated parameters in the corresponding
database table, as described in Section 8.1.3:
2. Create a subclass.
3. Redefine the corresponding method as an AMDP.

296 297
8 SQLScript in ABAP Programs 8.1 AMDP Procedures

쐍 CT_PRICE VALUE(iv_vat) TYPE int1


쐍 CT_PRICE__IN__ CHANGING
VALUE(ct_price) TYPE ty_t_price.
In this case, you must assign these parameters yourself in order to call the
procedure correctly. ENDCLASS.

Avoid CHANGING Table Parameters CLASS zcl_amdp_call IMPLEMENTATION.


METHOD calculate_gross_price BY DATABASE PROCEDURE
In the database procedure, the CHANGING table parameters are imple-
FOR HDB LANGUAGE SQLSCRIPT
mented in two parameters. As shown in Listing 8.7, the code needed for a
USING zcl_amdp_call=>calculate_vat. 8
direct call of this procedure can look confusing to untrained readers
CALL "ZCL_AMDP_CALL=>CALCULATE_VAT"(
because the CT_PRICES__IN__ parameter was not defined anywhere in the
iv_vat => :iv_vat,
ABAP class. If you use these two parameters instead, the code will be more
ct_price => :ct_price,
readable:
ct_price__in__ => :ct_price );
쐍 IT_PRICES for entering the table
쐍 ET_PRICES for the output of the table ct_price = SELECT item,
If the generated procedures are only called using ABAP methods, whether net_price,
or not you use CHANGING table parameters doesn’t matter. net_price + vat as gross_price,
vat,
CLASS zcl_amdp_call DEFINITION PUBLIC. curr,
FROM :ct_price;
PUBLIC SECTION. ENDMETHOD.
TYPES: BEGIN OF ty_s_price,
item TYPE numc4, METHOD calculate_vat BY DATABASE PROCEDURE
net_price TYPE wertv9, FOR HDB LANGUAGE SQLSCRIPT.
gross_price TYPE wertv9, ct_price = SELECT item,
vat TYPE wertv9, net_price,
curr TYPE waers, gross_price,
END OF ty_s_price. net_price * :iv_vat / 100 as vat,
curr,
TYPES ty_t_price TYPE STANDARD TABLE OF ty_s_price. FROM :ct_price;

INTERFACES if_amdp_marker_hdb. ENDMETHOD.

METHODS calculate_vat ENDCLASS.


IMPORTING Listing 8.7 Calling an AMDP Procedure from Another AMDP Method
VALUE(iv_vat) TYPE int1
CHANGING All AMDP procedures used must be declared in an AMDP method via USING, USING
VALUE(ct_price) TYPE ty_t_price. which ensures that the necessary database objects are generated as
required. Note that the class constructor of the AMDP classes used is called
METHODS calculate_gross_price before the method is executed.
IMPORTING

298 299
8 SQLScript in ABAP Programs 8.2 CDS Table Functions

8.2 CDS Table Functions


IMPLEMENTED BY …
A CDS table function is an AMDP function that provides table data and can
be consumed from ABAP in Open SQL, like a database view.
CDS Table Function AMDP Function
Implementation The implementation of a CDS table function is similar to an AMDP proce-
dure as a method of an ABAP class. A corresponding user-defined function
is then generated from this method in the SAP HANA database. Since user- FOR TABLE FUNCTION …
defined functions can’t be consumed directly in Open SQL, the AMDP func- SAP NetWeaver
tions are encapsulated by a CDS object. An AMDP function can therefore Application Server for ABAP
also be considered a programmed CDS view. The CDS object can then be 8
Generate
used normally, such as a database view, in Open SQL. SAP HANA

Core Data Services


The classic ABAP Dictionary manages database objects such as data types
User-Defined Fields
(data elements, structures, table types); database tables; and views. The USING Views
Function
definitions of these objects are stored and managed in a database-neutral
form in the associated database tables (DD*) at the ABAP application server
level. Depending on the database system used, the appropriate database Figure 8.4 Objects Involved in a CDS Table Function
objects are then generated from the stored definition. The classic ABAP
Dictionary, which can be called via Transaction SE11, only allows the limited CDS Table Function
use of the SQL options, especially for views.
You can use a wizard to create CDS table functions from the ABAP develop- CDS table functions
CDS are a common concept that exists both directly in the SAP HANA data- ment tools of the Eclipse development environment. Start by clicking New 폷 wizard
base and on the SAP NetWeaver AS ABAP. With CDS, database objects such Other ABAP Repository Object in the context menu of the development
as views or table functions can be defined with the help of their own lan-
package and then choose Core Data Services 폷 Data Definition in the follow-
guage, which is based on the data definition language (DDL) of SQL. These
ing dialog. Figure 8.5 shows the corresponding wizard. To create a CDS table
data models can be enriched with semantic information using annota-
function, you must select the Define Table Function with Parameters tem-
tions.
plate.
The wizard then generates a basic structure of the corresponding source
8.2.1 Creating a CDS Table Function code of the CDS table function, as shown in Listing 8.8.

To create a CDS table function, two related objects must be created: @EndUserText.label: 'Example for a table function'
쐍 The CDS table function is defined in a DDL source with the parameters define table function Z_CDS_TF
with parameters parameter_name : parameter_type
and the table type of the return table. This step implicitly defines the sig-
returns {
nature of the associated AMDP method.
client_element_name : abap.clnt;
쐍 The AMDP function is implemented in a method of a static ABAP class. element_name : element_type;
This step contains the SQLScript source code for the table function. }
Interaction Figure 8.4 shows the interaction between a CDS table function and an implemented by method class_name=>method_name;;
AMDP function. Listing 8.8 Basic Structure of the Definition of a CDS Table Function

300 301
8 SQLScript in ABAP Programs 8.2 CDS Table Functions

쐍 returns { <fieldlist> }
The field list defines the structure of the return table. If the CDS table
function is client-dependent, the first field must have the ABAP Dictio-
nary type CLNT. For example, you can use the data element MANDT.
쐍 implemented by method <classname>=><methodname>
This component tells the CDS table function by which AMDP method the
implementation is performed. The CDS entity can be activated if the
associated method doesn’t exist yet.

AMDP Function
8

The actual implementation of the CDS table function occurs an AMDP


method in a static, global ABAP class, which requires the implementation of
the marker interface IF_AMDP_MARKER_HDB. Unlike AMDP procedures, AMDP
functions for CDS table functions are static methods. The parameters are
not defined individually in the method definition. Instead, you’ll use the
addition FOR TABLE FUNCTION <CDS_table_function_name> to establish the ref-
erence to the associated CDS table function. The parameters defined in the
CDS entity are then available in the function implementation.
The method implementation must be structured as shown in Listing 8.9.
Figure 8.5 Wizard for Creating CDS Objects
METHOD <method_name> BY DATABASE FUNCTION
FOR HDB LANGUAGE SQLSCRIPT
In this section, we’ll describe only a rudimentary syntax for defining CDS
OPTIONS READ-ONLY
objects, which are not the focus of the book. For more information on CDS
[USING <usages>].
objects, we recommend the SAP document “SAP HANA Core Data Services
<SQLScript-Code>
(CDS) Reference,” at http://s-prs.co/v533627. ENDMETHOD.
Components The definition of the CDS table function consists of the following compo-
Listing 8.9 Structure of the Implementation of an AMDP Function for a CDS
nents:
Table Function
쐍 @EndUserText.label
This annotation contains the descriptive text for the CDS table function The additions in the METHOD statement are all mandatory except for the
previously specified in the wizard. USING specification. The use of USING in this context is similar as in AMDP
쐍 define table function <CDS_entity> procedures.
This component indicates the start of the definition of the CDS table
function. The name of the CDS entity is in the same namespace as the Example of a CDS Table Function
data types of the ABAP Dictionary. Therefore, a CDS entity must not have For a functioning CDS table function, the definition of the CDS entity and
the same name as, for example, a database table. the implementation of the AMDP function belong together.
쐍 with parameters <parameterlist> Listing 8.10 and Listing 8.11 contain some simple examples to show the Definition
If the CDS table function will have parameters, these parameters can be basics of CDS table functions using texts for countries read from table
defined in this component. The use of parameters is optional. The client T005T. In practice, your CDS table functions will be used for much more
is often specified as a parameter, which will allow you to select data by complex scenarios that utilize multiple features of the SAP HANA database
client in the function, as shown in Listing 8.10. and SQLScript.

302 303
8 SQLScript in ABAP Programs 8.2 CDS Table Functions

@EndUserText.label: 'Country texts' REPORT zjb_test .


define table function z_country_text
with parameters SELECT *
@Environment.systemField: #CLIENT mandt:mandt, FROM z_country_text
@Environment.systemField: #SYSTEM_LANGUAGE sy_langu:langu INTO TABLE @DATA(lt_country)
returns { ##db_feature_mode[amdp_table_function].
mandt:mandt;
country:land1; cl_demo_output=>display( lt_country ).
text:landx50;
Listing 8.12 ABAP Program for Testing the CDS Table Function from the Example
}
8
implemented by method zjb_cl_country=>get_country_text;
Notice that the CDS table function can be read with a SELECT query, much
Listing 8.10 Example of Defining a CDS Table Function like a database table or a view.

The client and language are taken from the system fields via the annotation
Two-Track Implementation
@Environment.systemField.
You cannot create alternative implementations in ABAP or Open SQL for
RETURN statement The implementation shown in Listing 8.11 consists of only a RETURN state-
CDS table functions. However, if your program needs to run on SAP HANA
ment, which returns the result of a SELECT query. as well as on other database systems, the caller of the CDS table function
CLASS zjb_cl_country DEFINITION PUBLIC. must take care of an alternative implementation. To query at runtime
PUBLIC SECTION. whether CDS table functions are available, you can use the CL_ABAP_
INTERFACES if_amdp_marker_hdb. DBFEATURES class. As shown in Listing 8.13, this class can be queried for the
CLASS-METHODS get_country_text existence of the used feature AMDP_TABLE_FUNCTION.
FOR TABLE FUNCTION z_country_text. IF cl_abap_dbfeatures=>use_features(
ENDCLASS. VALUE #( ( cl_abap_dbfeatures=>amdp_table_function ) ) ).
* Implementation with CDS table function
CLASS zjb_cl_country IMPLEMENTATION. ELSE.
METHOD get_country_text BY DATABASE FUNCTION * Alternative implementation without SAP HANA features
FOR HDB LANGUAGE SQLSCRIPT ENDIF.
OPTIONS READ-ONLY
Listing 8.13 Checking the Availability of CDS Table Functions
USING t005t.
RETURN SELECT mandt, The syntax check also indicates with a warning that database-dependent
land1 AS country, functions are used when querying CDS table functions. You can use the
landx50 AS text following pragma to disable the warning, as shown in Listing 8.12.
FROM t005t
##db_feature_mode[amdp_table_function]
WHERE spras = :sy_langu
AND mandt = :mandt; This pragma signals to the syntax check that the developer is aware that
ENDMETHOD. this query will lead to errors in other database systems.
ENDCLASS.

Listing 8.11 Example of Implementing a CDS Table Function


8.2.2 Generated Objects of a CDS Table Function
Testing You can test the CDS table function using a simple ABAP program, as shown As with AMDP procedures, database objects can also be generated in SAP User-defined
in Listing 8.12. HANA for CDS table functions. First, a user-defined function is assigned the function

304 305
8 SQLScript in ABAP Programs 8.3 AMDP Functions for AMDP Methods

same name as the associated static method of the AMDP function, as


shown in Listing 8.14. Note the Client in the Join Condition
As an ABAP developer, you may not be accustomed to taking the client into
create function
account since this task is usually undertaken by Open SQL. In SQLScript,
"ZJB_CL_COUNTRY=>GET_COUNTRY_TEXT"
however, the client is only an ordinary database field. Be sure you make
(
the correct selection yourself, in particular for join conditions. If you don’t
"MANDT" NVARCHAR (000003),
select the client in this situation, the cartesian product of the data is
"SY_LANGU" NVARCHAR (000001)
formed over all existing clients.
)
returns table
( If implicit client handling is not desired, you can disable it using the anno- Client independent 8
"MANDT" NVARCHAR (000003) , tation @ClientDependent: false. Nevertheless, you can still have the client as
"COUNTRY" NVARCHAR (000003) , a field in the return structure of the CDS table function and select it as for
"TEXT" NVARCHAR (000050) any other field.
)
language sqlscript sql security invoker as begin
Use Implicit Client Handling If Possible

RETURN SELECT mandt, Application and Customizing data are typically client specific. Thus, you
land1 AS country, should always use the implicit the client handling feature of the CDS table
landx50 AS text function.
FROM "ZJB_CL_COUNTRY=>T005T#covw"
WHERE spras = :SY_LANGU
AND mandt = :MANDT;
8.3 AMDP Functions for AMDP Methods
end; If AMDP functions are only to be used in SQLScript source code by other
Listing 8.14 Generated User-Defined Function for the AMDP Function AMDP methods, defining an associated CDS table function is not necessary.
The definition and implementation of an AMDP function for AMDP meth-
As with AMDP procedures, a view was also generated for the table specified ods differs in the following aspects:
via USING. 쐍 The AMDP method can be a static method or an instance method. There-
fore, the associated AMDP classes don’t have to be static.
쐍 The method can also be declared in the private or protected visibility
8.2.3 Implicit Client Handling of CDS Table Functions
area.
By default, the implicit client handling of CDS table functions is enabled.
쐍 The parameters of the method are defined when the method is defined.
Thus, the first field in the field list must be of dictionary type CLNT. Accord-
ingly, the developer must also ensure that this field is filled out correctly 쐍 The addition FOR TABLE FUNCTION in the method definition is omitted.
with the source client of the data. In a SELECT query to the CDS table func-
tion, all data with other clients are then implicitly filtered out. 8.3.1 AMDP Table Functions
To improve performance, you should filter out the data of other clients in AMDP table functions have been available in ABAP since SAP NetWeaver
the AMDP function. To create a filter, you’ll define an input parameter for 7.40. They are defined with a fully typed, table-like RETURNING parameter. In
the client, which is then automatically assigned the correct client via the the implementation, the result table must then be returned with the RETURN
annotation @Environment.systemField: #CLIENT. The examples shown in <table expression> statement.
Listing 8.10 and Listing 8.11 illustrate the correct client handling.

306 307
8 SQLScript in ABAP Programs 8.3 AMDP Functions for AMDP Methods

AMDP functions Listing 8.15 contains an example using an AMDP table function in a differ- RETURN SELECT mandt,
in different ent AMDP method. The direct call of the method GET_COUNTRY_TEXT in an land1 AS country,
AMDP methods
ABAP method of the class ZCL_AMDP_FUNC would not be possible. landx50 AS text
FROM t005t
CLASS zcl_amdp_func DEFINITION PUBLIC.
WHERE spras = :iv_langu
AND mandt = :iv_mandt;
PUBLIC SECTION.
ENDMETHOD.
TYPES: BEGIN OF ty_s_country,
mandt TYPE mandt,
ENDCLASS.
country TYPE land1,
text TYPE landx50, Listing 8.15 Example of Using an AMDP Table Function in a Different AMDP 8
END OF ty_s_country. Method
TYPES ty_t_country TYPE STANDARD TABLE OF ty_s_country
WITH DEFAULT KEY.
8.3.2 Scalar AMDP Functions
INTERFACES if_amdp_marker_hdb. With SAP_BASIS component release 753, scalar functions can also be imple-
METHODS test_amdp_table_function mented in the AMDP framework. In the definition, these functions differ
IMPORTING VALUE(iv_langu) TYPE langu only in the scalar return type of the function. In the implementation, the
VALUE(iv_mandt) TYPE mandt result is then not returned with the RETURN statement, but the return
EXPORTING VALUE(et_country) TYPE ty_t_country. parameter is simply assigned.
We explored the structure of an AMDP function in connection with CDS
PRIVATE SECTION.
table functions earlier in Listing 8.9. For scalar AMDP functions, you can
METHODS get_country_text
IMPORTING VALUE(iv_langu) TYPE langu also specify the DETERMINISTIC option after OPTIONS if the same output is
VALUE(iv_mandt) TYPE mandt always generated for the same input. This step allows the results of the sca-
RETURNING VALUE(rt_country) TYPE ty_t_country. lar function to be buffered from the database.
ENDCLASS. Listing 8.16 shows an example of a scalar function that cleans up values for
InfoObjects that are not allowed in an SAP BW system. Note that, although
CLASS zcl_amdp_func IMPLEMENTATION. this function finds and replaces most characters disallowed in SAP BW sys-
tems, other characters may cause problems.
METHOD test_amdp_table_function BY DATABASE PROCEDURE
FOR HDB LANGUAGE SQLSCRIPT CLASS zjb_bw_tools_amdp DEFINITION
OPTIONS READ-ONLY PUBLIC
USING zcl_amdp_func=>get_country_text. FINAL
et_country = select * CREATE PUBLIC .
from "ZCL_AMDP_FUNC=>GET_COUNTRY_TEXT"
( iv_langu => :iv_langu, PUBLIC SECTION.
iv_mandt => :iv_mandt); INTERFACES if_amdp_marker_hdb.
ENDMETHOD. METHODS replace_unallowed_characters
IMPORTING VALUE(iv_input) TYPE rschavl60
METHOD get_country_text BY DATABASE FUNCTION RETURNING VALUE(rv_output) TYPE rschavl60.
FOR HDB LANGUAGE SQLSCRIPT ENDCLASS.
OPTIONS READ-ONLY
USING t005t. CLASS zjb_bw_tools_amdp IMPLEMENTATION.

308 309
8 SQLScript in ABAP Programs 8.5 Recommendations

METHOD replace_unallowed_characters BY DATABASE FUNCTION 쐍 ABAP Database Connectivity (ADBC)


FOR HDB LANGUAGE SQLSCRIPT ADBC is a class-based framework for running Native SQL. Individual SQL
OPTIONS READ-ONLY. statements, database connections, and result sets are represented as
ABAP objects. ADBC can be regarded as a successor to the static embed-
rv_output = CASE WHEN LEFT( :iv_input, 1 ) = '!' ding of Native SQL using the EXEC SQL statement in ABAP code. In more
THEN replace( iv_input ,'!' , '$') than name only, the ADBC framework is reminiscent of the similarly
WHEN :iv_input = '#' structured Java Database Connectivity (JDBC) from the Java world.
THEN ''
쐍 EXEC SQL <Native SQL> ENDEXEC
ELSE :iv_input
This statement enables you to embed Native SQL statically into the ABAP
END;
source code. However, SAP no longer recommends this approach. 8
Instead, ADBC is referenced for the use of Native SQL.
rv_output = replace_regexpr( '[[:cntrl:]]'
IN :rv_output WITH '' ); 쐍 CALL DATABASE PROCEDURE
rv_output = replace( :rv_output, nchar( '0130'), ''); This ABAP statement allows you to call any database procedure on SAP
ENDMETHOD. HANA via an associated proxy object. However, SAP recommends using
ENDCLASS. AMDPs instead, as long as the procedure will be called via the primary
database connection.
Listing 8.16 Example of a Scalar AMDP Function

Performance of Scalar Functions


8.5 Recommendations
In general, scalar functions run the risk of having a negative impact on per- In this chapter, you learned some ways to directly access the objects of an
formance. With the function shown in Listing 8.16, you can easily clean up SAP HANA database in your programs. Even if trying out these new tech-
dozens of fields in a transformation routine in the SAP BW system. How- niques is tempting, let’s pause a moment to review some final consider-
ever, large amounts of data can quickly lead to performance problems. ations:
Before using any scalar function, therefore, you should test them with
쐍 If possible, you should continue to use Open SQL, as long as no signifi-
realistic data volumes to determine whether the scalar function is suffi-
cant performance improvements are foreseeable. The ABAP language
ciently fast.
has been extended in recent releases to include powerful functions, such
as the use of expressions and the option of combining multiple queries
via UNION. More complex queries can also be mapped using CDS views.
8.4 Alternatives to AMDP for Calling SQLScript Code from 쐍 However, if, for performance reasons or other considerations, executing
ABAP Programs SQLScript code directly from ABAP programs still seems necessary, the
techniques of the AMDP framework on the SAP HANA database are the
With the AMDP framework, calling SQLScript can be elegantly integrated weapon of choice for executing static SQLScript code.
into the ABAP language and Open SQL. A person reading an ABAP program
쐍 If you need dynamic SQLScript code, ADBC is the right technique. How-
may not initially recognize that AMDP objects are actually hidden behind a
ever, dynamic SQL code is always problematic. On one hand, error analy-
method call or a presumed table.
sis is often more difficult, and on the other hand, you must guard against
Alternative However, with alternative techniques, you can execute SQLScript state- security gaps and vulnerability to SQL injection attacks.
techniques ments from ABAP programs. These techniques may be necessary if second- 쐍 If you’re working with secondary database connections, you should con-
ary database connections will be used and can be helpful when executing sider using a CALL DATABASE PROCEDURE statement. Further, the autono-
dynamic SQL code. mous transactions we discussed in Chapter 6, Section 6.6.2, can also
However, you can call SQLScript code from ABAP without using AMDPs in solve some classic use cases for secondary database connections more
several alternative ways: elegantly.

310 311
8 SQLScript in ABAP Programs

Regardless of the technology used, the clean encapsulation of the database


access is always recommended in both AMDP and Open SQL. Only if you
bundle and encapsulate the database access in separate classes will you
have the necessary flexibility to carry out optimizations later without fear
of negative side effects.

8.6 Summary
Code execution on the SAP HANA database system can be extremely fast,
which you can effectively take advantage of with the concepts learned in
this chapter. With the AMDP framework, you have in your hands a tool that
allows you to easily create and call database procedures and functions. In
the next chapter, you’ll learn how this framework is used by SAP BW to
implement transformation routines in SQLScript.

312
Contents

Introduction .................................................................................................................... 15

1 SAP HANA 21

1.1 What Is SAP HANA? ...................................................................................... 22


1.1.1 SAP HANA: A Fast SQL Database ............................................... 22
1.1.2 SAP HANA: An Application Server ............................................. 26
1.1.3 SAP HANA: A Collection of Tools ............................................... 27
1.2 System Architecture ..................................................................................... 29
1.2.1 SAP HANA Server Components .................................................. 29
1.2.2 Databases and Tenants ................................................................ 30
1.3 Organizing Database Objects .................................................................. 32
1.3.1 Database Schemas ......................................................................... 32
1.3.2 Database Catalogs ......................................................................... 34
1.3.3 Content and Repositories ............................................................ 35
1.4 Development Environments .................................................................... 36
1.4.1 SAP HANA Studio ............................................................................ 37
1.4.2 SAP HANA Database Explorer .................................................... 40
1.5 The SQL Console ............................................................................................. 44

1.6 Summary ........................................................................................................... 47

2 Getting Started with SQLScript 49

2.1 SQL versus SQLScript .................................................................................... 49

2.2 Basic Language Elements ........................................................................... 53


2.2.1 Statements ....................................................................................... 53
2.2.2 Whitespace ....................................................................................... 54
2.2.3 Comments ........................................................................................ 54
2.2.4 Literals ................................................................................................ 56
2.2.5 Identifiers .......................................................................................... 58
2.2.6 Access to Local Variables and Parameters ............................. 59
2.2.7 System Variables ............................................................................ 60
2.2.8 Reserved Words .............................................................................. 61
2.2.9 Operators .......................................................................................... 61
2.2.10 Expressions ....................................................................................... 63

7
Contents Contents

2.2.11 Predicates .......................................................................................... 65 4 Data Types and Their Processing 153


2.2.12 Data Types ......................................................................................... 66
2.2.13 The NULL Value ................................................................................ 67
4.1 Character Strings ........................................................................................... 153
2.2.14 The DUMMY Table .......................................................................... 69
4.1.1 Data Types for Character Strings .............................................. 154
2.3 Modularization and Logical Containers ............................................... 70 4.1.2 Conversions ...................................................................................... 157
2.3.1 Blocks .................................................................................................. 72 4.1.3 Character String Functions ......................................................... 157
2.3.2 Procedures ......................................................................................... 75 4.1.4 SQLSCRIPT_STRING Library ......................................................... 171
2.3.3 User-Defined Functions ................................................................ 83
4.2 Date and Time ................................................................................................. 176
2.3.4 User-Defined Libraries ................................................................... 87
4.2.1 Date Information ............................................................................ 176
2.4 Sample Program ............................................................................................. 89 4.2.2 Time Information ........................................................................... 181
2.4.1 Requirements ................................................................................... 89 4.2.3 Combined Time and Date Information ................................... 182
2.4.2 Requirements Analysis .................................................................. 90 4.2.4 Processing Time and Date Values ............................................. 182
2.4.3 Implementation .............................................................................. 91 4.2.5 Examples of Processing Time Values ....................................... 187
2.4.4 Testing the Implementation ....................................................... 97
4.3 Numerical Data ............................................................................................... 189
2.5 Summary ............................................................................................................ 100 4.3.1 Basic Arithmetic Operations ....................................................... 191
4.3.2 Square Roots and Exponents ...................................................... 191
4.3.3 Logarithms ........................................................................................ 192
3 Declarative Programming in SQLScript 101 4.3.4 Rounding or Trimming ................................................................. 192
4.3.5 Trigonometry ................................................................................... 194
4.3.6 Random Numbers .......................................................................... 194
3.1 Table Variables ................................................................................................ 102
4.3.7 Sign ...................................................................................................... 194
3.1.1 Declaring Table Variables ............................................................. 102
4.3.8 Quantities and Amounts ............................................................. 195
3.1.2 Using Table Variables .................................................................... 103
4.4 Binary Data Types .......................................................................................... 200
3.2 SELECT Statements ........................................................................................ 104
4.4.1 Conversion between Binary Data, Hexadecimal Data,
3.2.1 SELECT Clauses ................................................................................. 105
and Character Strings ................................................................... 201
3.2.2 Field List of SELECT Clauses ......................................................... 105
4.4.2 Bits and Bytes .................................................................................. 202
3.2.3 FROM Clauses ................................................................................... 119
3.2.4 Joins ..................................................................................................... 122 4.5 Conversions between Data Types .......................................................... 204
3.2.5 WHERE Conditions ......................................................................... 130 4.6 Summary ........................................................................................................... 205
3.2.6 WITH Clauses ................................................................................... 137
3.2.7 GROUP BY Clauses .......................................................................... 139
3.2.8 HAVING Clauses .............................................................................. 141
3.2.9 ORDER BY Clauses ........................................................................... 142
5 Write Access to the Database 207

3.2.10 Set Theory .......................................................................................... 143


3.2.11 Subqueries ......................................................................................... 145 5.1 INSERT ................................................................................................................. 208
3.2.12 Alias Names ...................................................................................... 146 5.1.1 Individual Data Records ............................................................... 208
5.1.2 Inserting Multiple Records Simultaneously .......................... 209
3.3 Other Operators .............................................................................................. 148
3.3.1 Calculation Engine Plan Operators ........................................... 148 5.2 UPDATE .............................................................................................................. 211
3.3.2 MAP_MERGE Operator .................................................................. 149 5.2.1 Simple UPDATE Statement ......................................................... 211
3.3.3 MAP_REDUCE Operator ................................................................ 150 5.2.2 UPDATE Statement with Reference to Other Tables .......... 212

3.4 Summary ............................................................................................................ 151

8 9
Contents Contents

5.3 UPSERT or REPLACE ........................................................................................ 213 6.8 Error Handling ................................................................................................. 260
5.3.1 Inserting or Updating Individual Data Records .................... 213 6.8.1 What Are Exceptions? ................................................................... 261
5.3.2 Inserting or Updating Multiple Data Records ....................... 214 6.8.2 Triggering Exceptions ................................................................... 262
5.4 MERGE INTO ..................................................................................................... 214 6.8.3 Catching Exceptions ...................................................................... 262

5.5 DELETE ................................................................................................................. 217 6.9 Summary ........................................................................................................... 266

5.6 TRUNCATE TABLE ............................................................................................ 217

5.7 Summary ............................................................................................................ 217 7 Creating, Deleting, and Editing


Database Objects 267

6 Imperative Programming 219


7.1 Tables .................................................................................................................. 268
7.1.1 Creating Database Tables ............................................................ 268
6.1 Variables ............................................................................................................ 219 7.1.2 Changing Database Tables ......................................................... 272
6.1.1 Local Scalar Variables .................................................................... 219 7.1.3 Deleting Database Tables ............................................................ 273
6.1.2 Local Table Variables ..................................................................... 224
7.2 Table Types ....................................................................................................... 273
6.1.3 Session Variables ............................................................................ 234
6.1.4 Temporary Tables ........................................................................... 235 7.3 Views ................................................................................................................... 274

6.2 Flow Control Using IF and ELSE ................................................................ 236 7.4 Sequences ......................................................................................................... 276
7.4.1 Increment .......................................................................................... 277
6.3 Loops .................................................................................................................... 239
7.4.2 Limits .................................................................................................. 277
6.3.1 FOR Loop ............................................................................................ 239
7.4.3 Behavior When Reaching the Limit .......................................... 277
6.3.2 WHILE Loop ....................................................................................... 240
7.4.4 Resetting the Sequence ................................................................ 278
6.3.3 Controlling Loop Passes ................................................................ 241
7.4.5 Changing and Deleting a Sequence ......................................... 278
6.3.4 Exercise: Greatest Common Divisor ......................................... 242
7.5 Triggers .............................................................................................................. 278
6.4 Cursors ................................................................................................................ 243
7.5.1 Parameters ....................................................................................... 280
6.4.1 FOR Loop via a Cursor .................................................................... 243
7.5.2 Per Row or Per Statement ............................................................ 281
6.4.2 Open, Read, and Close Explicitly ................................................ 244
6.4.3 Updateable Cursors ........................................................................ 246 7.6 Summary ........................................................................................................... 281

6.5 Arrays ................................................................................................................... 246


6.5.1 Generating an Array ....................................................................... 247
6.5.2 Accessing the Array ........................................................................ 247 8 SQLScript in ABAP Programs 283
6.5.3 Arrays as Local Variables .............................................................. 248
6.5.4 Splitting and Concatenating Arrays ......................................... 249 8.1 AMDP Procedures .......................................................................................... 283
6.5.5 Arrays and Table Columns ........................................................... 250 8.1.1 Introduction to AMDP ................................................................... 284
6.5.6 Bubble Sort Exercise ....................................................................... 251 8.1.2 Creating AMDP Procedures ......................................................... 287
6.6 Transaction Control ....................................................................................... 253 8.1.3 Generated Objects of an AMDP Method ................................ 290
6.6.1 Transactions ..................................................................................... 253 8.1.4 Lifecycle of the Generated Objects ........................................... 294
6.6.2 Autonomous Transactions .......................................................... 254 8.1.5 Two-Track Development .............................................................. 294
8.1.6 Using AMDP Procedures in Other AMDP Procedures ......... 297
6.7 Executing Dynamic SQL ............................................................................... 255
6.7.1 Parameters of Dynamic SQL ........................................................ 257 8.2 CDS Table Functions ..................................................................................... 300
6.7.2 Input Parameters ............................................................................ 258 8.2.1 Creating a CDS Table Function .................................................. 300

10 11
Contents Contents

8.2.2 Generated Objects of a CDS Table Function .......................... 305 10 Clean SQLScript Code 339
8.2.3 Implicit Client Handling of CDS Table Functions ................. 306
8.3 AMDP Functions for AMDP Methods .................................................... 307 10.1 Code Readability ............................................................................................ 339
8.3.1 AMDP Table Functions .................................................................. 307 10.1.1 Formatting the Code ..................................................................... 340
8.3.2 Scalar AMDP Functions ................................................................. 309 10.1.2 Mnemonic Names .......................................................................... 341
8.4 Alternatives to AMDP for Calling SQLScript Code from 10.1.3 Granularity of Procedures and Functions ............................... 342
ABAP Programs ............................................................................................... 310 10.1.4 Comments ........................................................................................ 345
10.1.5 Decomposing Complex Queries ................................................ 347
8.5 Recommendations ......................................................................................... 311
10.1.6 Readable SQLScript Statements ................................................ 351
8.6 Summary ............................................................................................................ 312
10.2 Performance Recommendations ............................................................ 352
10.2.1 Reducing Data Volumes ............................................................... 353
10.2.2 Avoid Switching between Row and Column Engines ........ 353
9 SQLScript in SAP Business Warehouse 313 10.2.3 Declarative Queries ........................................................................ 353
10.2.4 Scalar Functions .............................................................................. 353
9.1 Executing the Data Transfer Process in ABAP vs. SAP HANA ..... 314 10.3 Summary ........................................................................................................... 354
9.2 Transformation Routines as AMDP ........................................................ 318
9.2.1 Creating Transformation Routines in Eclipse ........................ 318
9.2.2 Creating Transformation Routines in SAP GUI ..................... 319 11 Tests, Errors, and Performance Analysis 355
9.3 Successive Transformations and Mixed Execution ......................... 320

9.4 Generated AMDP Classes ........................................................................... 321 11.1 Testing SQLScript Code ............................................................................... 356
9.4.1 Signature of AMDP Methods ...................................................... 323 11.1.1 SQL Console ...................................................................................... 356
9.4.2 Assigning the Output Tables ...................................................... 325 11.1.2 Testing ABAP-Managed Database Procedure Methods .... 358
9.4.3 Access to Data from Other Data Models ................................ 325 11.1.3 SQLSCRIPT_LOGGING Library ..................................................... 359
11.1.4 End-User Test Framework in SQLScript ................................... 361
9.5 Individual Routines ....................................................................................... 328
9.5.1 Start Routines ................................................................................... 329 11.2 Debugger for SQLScript ............................................................................... 365
9.5.2 End Routines ..................................................................................... 329 11.2.1 SQLScript Debugger in SAP HANA Studio ............................... 366
9.5.3 Expert Routines ............................................................................... 330 11.2.2 ABAP-Managed Database Procedure Debugger in
9.5.4 Field Routines ................................................................................... 332 the ABAP Development Tools ..................................................... 369
11.2.3 Debugging in the SAP HANA Database Explorer ................. 372
9.6 Error Processing and Error Stack .............................................................. 333
9.6.1 Processing Flow in the Data Transfer Process ....................... 335 11.3 Performance Analysis .................................................................................. 374
9.6.2 Example: Recognizing Incorrect Data in Table OUTTAB .... 336 11.3.1 Runtime Measurement ................................................................ 374
9.6.3 Example: Finding Invalid Field Contents with Regular 11.3.2 Execution Plan ................................................................................. 375
Expressions ....................................................................................... 337 11.3.3 Plan Visualizer ................................................................................. 377
11.3.4 SQL Analyzer of the SAP HANA Database Explorer ............. 384
9.7 Summary ............................................................................................................ 337
11.3.5 SQLScript Code Analyzer .............................................................. 386
11.4 Summary ........................................................................................................... 390

12 13
Contents

Appendices 391

A Data Model for Task Management ........................................................ 393

B List of Abbreviations ..................................................................................... 397

C The Author ........................................................................................................ 399

Index ................................................................................................................................... 401

14
Index

A Anonymous blocks ........................... 70, 102


ANSI SQL standard ....................................... 50
ABAP ................................................................. 67 APPLY_FILTER ............................................. 259
date format ............................................ 180 Arithmetic operators .................................. 61
unit test .................................................... 297 Array ............................................................... 246
ABAP Database Connectivity access ........................................................ 247
(ABDC) ...................................................... 311 as local variable .................................... 248
ABAP development tools ................... 36, 38 concatenate and split ......................... 249
ABAP Dictionary ........................................ 300 generate ................................................... 247
ABAP_ALPHANUM() ................................ 157 table and .................................................. 250
ABAP_LOWER() .......................................... 159 ARRAY_AGG() ................................... 250–251
ABAP_UPPER() ........................................... 159 AS BEGIN ................................................... 80, 84
ABAP-managed database procedure ASCII ...................................................... 154, 170
(AMDP) ....................... 21, 55, 70, 284, 296 character set .............................................. 53
ABAP .......................................................... 296 ASIN() ............................................................. 194
classes ....................................................... 321 Assigning an output table ..................... 325
debugger ......................................... 369, 372 Asterisk .......................................................... 107
field routine ............................................ 332 ATAN() ........................................................... 194
framework .............................................. 285 ATAN2() ......................................................... 194
function ................................. 284, 300, 307 Authorization control ................................ 33
implementing a procedure ............... 289 Automatic number assignment ......... 270
in ABDP procedure .............................. 297 Autonomous transaction ...................... 254
method ............................................ 287, 297 AVG ................................................................. 113
objects ....................................................... 290
procedure ....................................... 283–284 B
PROCEDURE method .......................... 323
recommendations ............................... 311 Basic arithmetic operations .................. 191
retroactive implementation ............ 296 BEGIN
routines .................................................... 147 AUTONOMOUS TRANSACTION ...... 254
testing the method .............................. 358 block ............................................................. 72
tools ........................................................... 317 Best practices .............................................. 339
ABS() ............................................................... 194 BETWEEN ...................................................... 132
ACOS() ............................................................ 194 Binary data ................................................... 202
ADD_*() ......................................................... 183 Binary data type ......................................... 200
ADD_MONTHS_LAST() ........................... 184 Binary floating-point number ............. 190
ADD_MONTHS() ........................................ 184 BINTOHEX() ................................................. 201
ADD_WORKDAYS() .................................. 184 BINTONHEX() .............................................. 201
Advanced DataStore objects BINTOSTR() .................................................. 201
(aDSOs) ............................................ 313, 326 BITCOUNT() ................................................. 204
Aggregate expression .............................. 111 BITSET() ......................................................... 202
Aggregate functions ....................... 111, 113 BITUNSET() ................................................... 202
Alias ................................................................ 106 Blank characters ........................................... 54
Alias name .......................................... 146, 212 Blank line ...................................................... 340
Alignment .................................................... 341 BLOB ............................................................... 200
Alpha conversion ...................................... 157 Blocks ................................................................ 72
ALPHANUM ................................................ 155 anonymous ................................................ 74
ALTER TABLE ............................................... 272 comment ..................................................... 55
Amount ......................................................... 195 BREAK statement ...................................... 241

401
Index Index

Breakpoint ................................................... 370 CONCAT() ...................................................... 158 Data model Deviating fiscal year ................................. 187
Bring Your Own Language (BYOL) ......... 26 array .......................................................... 249 data ........................................................... 394 Dictionary compression ............................ 23
Bubble sort algorithm ............................. 251 Concatenation ............................................ 158 example ................................................... 393 DISTINCT ...................................................... 105
Constants ........................................................ 88 installation ............................................. 395 DO BEGIN ........................................................ 74
C Constraint ..................................................... 269 table ........................................................... 393 Don’t Repeat Yourself (DRY)
CONTAINS .................................................... 135 task management ................................ 393 principle ...................................................... 71
Calculation engine .................................... 376 Content folder .............................................. 35 Data preview ............................................... 358 DROP TABLE ................................................ 273
Calculation engine functions CONTINUE .................................................... 241 Data provisioning server .......................... 30 DUMMY table ................................................ 69
(CE functions) ................................ 148, 387 Control character ....................................... 337 Data transfer intermediate storage ... 333 Dynamic SQL ..................................... 255, 387
Calendar week ............................................ 186 Conversion Data transfer process ..................... 315, 320
CALL ................................................................... 81 data type .................................................. 204 execute ..................................................... 314 E
CALL DATABASE PROCEDURE ............. 311 explicit ....................................................... 204 processing flow ..................................... 335
CARDINALITY() ........................................... 246 implicit ...................................................... 204 Data types ............................................. 66, 153 Eclipse ............................................ 37, 318, 380
CASCADE ....................................................... 273 permissible .............................................. 204 composite ................................................... 66 debugger .................................................. 366
CASE expressions ...................................... 108 convert ............................................ 157, 204 installation ................................................. 38
CONVERT_CURRENCY() .......................... 198
searched ................................................... 109 primitive ..................................................... 66 Empty date ................................................... 177
CONVERT_UNIT() ...................................... 195
simple ........................................................ 108 scalar ............................................................ 66 EMPTY parameter ........................................ 78
Core data services (CDS) ........................... 21
CAST() ............................................................. 204 Data volume ............................................... 353 Empty result ................................................ 146
client .......................................................... 306
CEIL() .............................................................. 193 Database END .................................................................... 80
objects of a table function ................ 305
CHANGING table parameters ............... 298 catalog ............................................... 34, 273 anonymous block .................................... 74
table function ............ 284, 300–301, 303
CHAR() ........................................................... 170 different systems .................................. 295 block ............................................................. 72
view ............................................................ 300
Character string ......................................... 153 objects ................................................ 32, 267 functions ..................................................... 84
Correlation name ............................ 107, 352
data type .................................................. 154 schema ........................................................ 32 End routine .................................................. 329
COS() ............................................................... 194
function .................................................... 157 search ........................................................ 135 End-of-line comment ................................. 54
COSH() ............................................................ 194 status ........................................................ 253
literals .......................................................... 57 End-user test framework ........................ 361
Cosine ............................................................. 194 write access ............................................ 207
search within .......................................... 165 Engine ............................................................ 375
COT() ............................................................... 194 DATE ............................................................... 176
Client capability ............................................ 31 Equivalent join ........................................... 125
Client concept ............................................. 197 COUNT ................................................. 112–113 Date formats ............................................... 177 Error code ..................................................... 261
Client handling .......................................... 306 CPU load .......................................................... 24 DATS ............................................................... 180 Error handling ................................... 260, 262
CLOB ............................................................... 157 CREATE FUNCTION ..................................... 83 DATS fields .................................................. 180 Error processing ........................................ 333
COALESCE function ..................................... 69 CREATE TABLE ............................................ 268 DAYNAME() ................................................. 187 Error stack ........................................... 333, 335
Code Analyzer ............................................. 386 CREATE TABLE AS ...................................... 271 DAYOFYEAR() .............................................. 187 ERRORTAB .................................................... 325
Code Inspector ........................................... 389 CREATE TABLE LIKE .................................. 271 Deadlock ....................................................... 255 Error-tolerant search .................................. 28
Code optimization .................................... 354 Critical path ................................................. 380 Debug mode ................................................ 372 Escape expression ..................................... 131
Code pushdown ............................................ 52 Cross-join ...................................................... 123 Debugging ...................... 356, 365–366, 373 ESCAPE_DOUBLE_QUOTES ................... 259
Code-to-data paradigm .............................. 51 Currency conversion ................................ 198 data preview .......................................... 358 ESCAPE_SINGLE_QUOTES ..................... 259
Colon ................................................................. 60 CURRENT_DATE ......................................... 183 external .................................................... 368 Euclidean algorithm ................................ 242
Column alias ............................................... 147 CURRENT_LINE_NUMBER ....................... 61 in SAP HANA Studio ............................ 368 Evaluation sequence of operators ......... 62
Column definition .................................... 268 CURRENT_OBJECT_NAME ....................... 60 procedure ................................................ 367 EXCEPT .......................................................... 145
Column engine .......................................... 376 CURRENT_OBJECT_SCHEMA .................. 60 Decimal floating-point number ......... 190 Exceptions ................................................... 261
Column list .................................................. 352 CURRENT_TIME ......................................... 183 Declarative programming ..................... 101 forwarding .............................................. 265
Column list UPSERT ................................. 213 CURRENT_TIMESTAMP ........................... 183 DECLARE in procedures .......................................... 264
Column name ............................................. 106 CURRENT_UTCDATE ................................ 183 CONDITION ............................................ 261 trigger ....................................................... 262
Column sequence ........................... 208–209 CURRENT_UTCTIME ................................. 183 CURSOR .................................................... 243 EXEC ................................................................ 256
Column store ............................. 22, 270, 353 CURRENT_UTCTIMESTAMP .................. 183 Decomposition .......................................... 172 EXEC SQL ....................................................... 311
Column update .......................................... 215 CYCLE parameter ....................................... 277 DEFAULT DECLARE .................................. 220 EXECUTE IMMEDIATE ............................. 257
Column-based storage ............................... 23 DEFAULT parameter ................................... 77 Execution plan .............. 375, 378, 380, 386
Commented out ........................................ 242 DEFAULT SCHEMA ...................................... 80 EXISTS ............................................................ 133
D DELETE ................................................. 217, 229
Comments ............................................ 54, 345 EXISTS predicate ........................................ 236
Commercial rounding ............................. 192 Data control language (DCL) ................... 50 Delta merge operation ............................... 25 Expert routine ............................................ 330
COMMIT ........................................................ 253 Data definition language (DDL) .... 50, 267 Delta storage .................................................. 25 EXPLAIN PLAN ............................................ 376
CompositeProvider .................................. 313 Data flow graph .......................................... 101 DETERMINISTIC ............................................ 84 Explanatory comments .......................... 346
Compression .................................................. 23 Data manipulation language (DML) .... 50 Development environments ........... 36–37 Exponent ...................................................... 191

402 403
Index Index

Expressions .......................................... 63, 106 I LEAD ............................................................... 119 N


context ......................................................... 64 Left outer join ............................................. 126
Extended store server ................................ 30 Identifiers ....................................................... 58 LEFT() ............................................................. 160 Name server ................................................... 29
EXTRACT() .................................................... 185 IF ....................................................................... 236 LENGTH() ...................................................... 157 Naming .......................................................... 341
IF statement ................................................. 236 Lexical element ............................................ 49 Naming conventions ............................... 342
F IF_AMDP_MARKER_HDB ...................... 287 LIKE ................................................................. 131 Native SQL .................................................... 283
Imperative programming ...................... 219 LIKE_REGEXPR ........................................... 170 NCHAR() ........................................................ 170
FETCH INTO ................................................. 244 Imperative statements ............................ 219 LIMIT .............................................................. 105 NCLOB ............................................................ 157
Field list ............................................... 105–106 Implicit client handling .......................... 306 Limit ............................................................... 277 NDIV0() .......................................................... 191
Field routine ................................................ 332 Implicit date conversion ........................ 177 Line break .............................................. 54, 340 Nest expressions ....................................... 114
First in, first out (FIFO) ............................ 143 IN ...................................................................... 132 Linear dimension ......................................... 90 Nested CASE expressions .......................... 96
Fiscal year ..................................................... 187 Inbound projection .................................. 347 Linguistic search ................................ 28, 135 NEXT_DAY( \u003cdate\>) .................... 184
Fixed-point number ................................. 189 Inclusive time ............................................. 380 List of statements ........................................ 74 Node grouping ........................................... 379
Floating-point literal ................................... 57 Increment ..................................................... 277 Literals .................................................... 56, 352 Non-equivalent join ................................. 125
Floating-point number ........................... 190 Index server ................................................... 29 LN() ................................................................. 192 Non-permitted characters ..................... 337
FLOOR() ......................................................... 193 Index-based access ......................... 224–225 LOB ................................................................. 157 NOT EXISTS .................................................. 145
Flow control ................................................ 236 Infinite loop ................................................. 241 Local table variable ................................... 224 NOT NULL ..................................................... 269
FOR loop ............................................... 239, 243 Initial value, variable ................................ 220 Local temporary table ............................. 235 NOT NULL DECLARE ................................. 220
FORMAT function ..................................... 174 In-memory ..................................................... 23 Local variable ................................................. 59 NOTFOUND ................................................. 245
Formatting ................................................... 340 Inner join ................................... 114, 124, 144 LOCALTOUTC() ........................................... 187 NOW() ............................................................. 183
Formatting strings .................................... 173 Input parameter, dynamic SQL ............ 258 LOCATE_REGEXPR() ........................ 163, 165 NULL value ........................... 67–68, 269, 328
FROM clause ................................................ 119 Input parameters ....................................... 275 LOCATE() ....................................................... 165 in aggregate functions ....................... 114
UPDATE .................................................... 212 INSERT ........................................... 99, 208, 226 LOG() .............................................................. 192 NULLS FIRST ................................................ 142
Full outer join ............................................. 127 Insert-only approach ................................. 24 Logarithm .................................................... 192 NULLS LAST ................................................. 142
Function call in the field list ................. 111 Integer ............................................................ 189 Logging ......................................................... 254 Number of rows ......................................... 231
Functions ......................................................... 70 Integer expression .................................... 225 Logical container ....................................... 219 Numerical data ........................................... 189
Fuzzy search ................................................ 136 INTERSECT .................................................... 144 Logical operators .......................................... 62 Numerical literal .......................................... 56
Intersection .................................................. 144 Loop pass ...................................................... 241 NVARCHAR .................................................. 154
G Interval .......................................................... 132 Loops ..................................................... 233, 239
INTO clause .................................................. 220 LOWER() ........................................................ 159 O
Generation namespaces ............................ 59 INTO clause EXEC ...................................... 257 LPAD() ............................................................ 167
Generic programming ............................ 255 IS [NOT] NULL ............................................. 135 LTRIM() .......................................................... 168 OCCURRENCES_REGEXPR() ......... 163, 166
Geodata ............................................................ 27 IS_EMPTY ...................................................... 231 OData ................................................................ 27
Global temporary table (GTT) .............. 235 IS_SQL_INJECTION_SAVE ...................... 259 M OFFSET ........................................................... 105
Granularity .................................................. 342 ISCLOSED ...................................................... 245 OLAP engine ................................................ 376
Graph engine ................................................. 28 ISOWEEK() ..................................................... 186 Map merge ................................................... 149 ON .................................................................... 124
Graph processing ......................................... 28 MapReduce method ................................ 150 OPEN CURSOR ............................................ 244
Greatest common divisor ...................... 242 J Material number ....................................... 168 Open SQL ............................................... 67, 283
GROUP BY clause .............................. 112, 139 MAX ................................................................ 113 OpenUI5 ........................................................... 27
Grouping sets ............................................. 140 Join .................................................................. 122 MAXVALUE ................................................. 277 Operator ........................................................... 61
condition .................................................. 124 MEMBER OF ....................................... 134, 248 Operator expressions .............................. 108
H type ............................................................. 123 MEMBER_AT() ............................................ 248 Operator list ................................................ 382
Join engine ................................................... 376 MERGE INTO ............................................... 214 OPTIONS READ-ONLY ............................. 289
Hamming distance ................................... 169 MIN ................................................................. 113 ORDER BY ............................................ 117, 142
HAMMING_DISTANCE() ......................... 169 L MINVALUE ................................................... 277 ORDINALITY ................................................ 250
HAVING clause ........................................... 141 Mixed execution ....................................... 320 Orphaned AMDP Classes ........................ 319
Header comments .................................... 345 LAG .................................................................. 119 MOD() ............................................................ 191 Outsourcing complexity ........................ 343
Help procedures ........................................ 263 LANGUAGE ..................................................... 79 MONTHNAME() ......................................... 187 OUTTAB ................................................ 325, 336
Hexadecimal representation ............... 202 LANGUAGE SQLSCRIPT ............................. 84 Multicontainer database .......................... 31 Overlapping ................................................. 223
HEXTOBIN() ................................................. 201 LAST_DAY(\u003cdate\>) ...................... 184 Multitenant database containers
Hungarian notation ................................. 342 Lateral joins ................................................. 128 (MDCs) ......................................................... 31
LCASE() ........................................................... 159

404 405
Index Index

P Random numbers ..................................... 194 SAP Fiori apps ................................................ 27 Self-join ................................................ 116, 122
Readability ................................ 339, 343, 351 SAP HANA ....................................................... 21 Semantic search ............................................ 28
Parameterization ......................................... 90 READS SQL DATA ......................................... 80 database ..................................................... 22 Semicolon ....................................................... 53
Parameters ................................................... 120 RECORD ......................................................... 323 deployment infrastructure .................. 41 Separation of concerns ........................... 295
dynamic SQL .......................................... 257 RECORD_COUNT ....................................... 231 introduction .............................................. 22 Sequence .................................... 270, 276, 278
example ....................................................... 90 Recursive calls ............................................... 82 performance ........................................... 317 change ...................................................... 278
generic ......................................................... 78 Redundant comments ............................ 346 perspectives ............................................... 39 delete ......................................................... 278
named .......................................................... 81 Regular expressions ....................... 161, 337 server components ................................. 29 reset ........................................................... 278
trigger ....................................................... 280 groups ....................................................... 163 system architecture ................................ 29 Sequence of operators ................................ 62
view ............................................................ 275 Relational operators ................................... 62 system schema ......................................... 33 Sequences ..................................................... 267
Parentheses .......................................... 62, 351 REPLACE ........................................................ 213 SAP HANA automated predictive SERIES_GENERATE_DATE ...................... 150
PARTITION BY ............................................. 117 REPLACE_REGEXPR() ..................... 163, 166 library .......................................................... 28 Session variables ....................................... 234
Performance ................................................ 352 REPLACE() ..................................................... 166 SAP HANA database explorer ......... 36, 40, SET clause ..................................................... 211
Performance analysis ..................... 355, 374 Repository ...................................................... 35 384, 389 Set operations ............................................. 143
Performance trace .................................... 383 Request .......................................................... 315 debugger .................................................. 372
Requirements analysis .............................. 90 SHINE demo ................................................... 59
Personal schema ........................................... 33 user interface ............................................ 43
Reserved words ............................................ 61 SHORTTEXT ................................................. 156
Phonetic code ............................................. 169 SAP HANA deployment infrastructure
Placeholders ................................................ 131 RESIGNAL ...................................................... 265 Sign ................................................................. 194
(HDI)
Plan operator .............................................. 375 RESTART ........................................................ 278 SIGN() ............................................................. 194
container .................................................... 27
Plan Visualizer (PlanViz) ..... 350, 356, 377 RESTRICT ....................................................... 273 SIGNAL ........................................................... 262
server ............................................................ 29
call .............................................................. 377 Return values ................................................ 95 Simple notation ............................................ 58
SAP HANA smart data integration ........ 30
views .......................................................... 380 RETURNS ......................................................... 84 SIN() ................................................................ 194
SAP HANA Studio ................................. 36–37
POWER() ........................................................ 191 Reuse ................................................................ 71 Single container database ......................... 31
database connection ............................. 39
Pragmas ........................................................ 362 Right outer join .......................................... 126 SINH() ............................................................. 194
debugger .................................................. 366
Predicates .............................................. 65, 236 RIGHT() .......................................................... 160 Sinus ............................................................... 194
SAP HANA Web-Based Development
Predictive analytics ..................................... 28 ROLLBACK .......................................... 217, 253 Size category .................................................. 93
Workbench ................................................ 36
Pretty printer .............................................. 341 ROUND() ........................................................ 192 Sorted table variables .............................. 232
SAP HANA XS .......................................... 26, 29
PRIMARY KEY .............................................. 269 Rounding ...................................................... 192 SOUNDEX() .................................................. 169
SAP HANA XSA ....................................... 26, 29
Primary key .............................. 207, 214, 269 Row engine ................................................... 376 Source code ................................................. 389
SAP HANA, express edition ..................... 29
Procedures ............................................... 70, 75 Row store ..................................... 23, 270, 353 Special characters ......................................... 58
SAP HANA, streaming analytics
call ................................................................. 80 ROWCOUNT .......................................... 60, 245 Special notation ............................................ 58
option .......................................................... 30
create ............................................................ 75 ROWS clause ................................................ 118
SAP Landscape Transformation Splitting strings ......................................... 171
parameter list ........................................... 76 RPAD() ............................................................ 167
schema ........................................................ 34 SQL ..................................................................... 49
properties .................................................... 79 RTRIM() .......................................................... 168
SAP NetWeaver schema ............................ 33 security ........................................................ 80
Public schema ................................................ 33 Runtime measurement .......................... 374
SAP Web IDE ............................................ 36, 40 SQL Analyzer ............................................... 384
Public synonym ............................................ 35 Runtime platform ....................................... 26
SAPUI5 .............................................................. 27 SQL console ................................... 43–44, 356
Savepoint ........................................................ 23 getting started .......................................... 46
Q S Scalar AMDP ................................................ 309 user interface ............................................ 45
Scalar parameters ..................................... 324 SQL Editor ................................................. 45, 47
Quantity ........................................................ 195 Sample program .......................................... 89
SAP Adaptive Server Enterprise Scalar queries .......................................... 64, 66 SQL functions ............................................. 102
Quantity conversion ....................... 195, 197
(SAP ASE) .................................................... 50 Scalar session variables .......................... 234 SQL injection ............................................... 259
QUARTER() ................................................... 187
SAP Business Application Studio ... 36, 42 Scalar user-defined functions ................. 86 SQL__PROCEDURE__SOURCE__
Queries .......................................................... 104
SAP Business Technology Platform Search ............................................................... 28 RECORD .................................................... 324
insert from ............................................... 209
Query decomposition ................... 347–348 (SAP BTP) .................................................... 42 SEARCH operator ...................................... 232 SQL_ERROR_CODE ............................ 60, 262
Query result, dynamic SQL ................... 257 SAP Business Warehouse (SAP BW) ..... 59, SEARCH table operator ........................... 230 SQL_ERROR_MESSAGE .................... 60, 262
Question mark .............................................. 82 313, 347 SECONDDATE ............................................. 182 SQLSCRIPT_LOGGING library .............. 359
Quotation marks .......................................... 58 query .......................................................... 383 SECURITY MODE functions ..................... 84 SQLSCRIPT_STRING library ................... 171
transformation ...................................... 314 SELECT clause ............................................. 105 SQRT() ............................................................ 191
transformation routine ...................... 371 SELECT INTO ............................................... 221
R SELECT query .............................................. 104
Square root .................................................. 191
SAP BW modeling tools ............ 36, 38, 319 Start routine ................................................ 329
RAND_SECURE() ........................................ 194 SAP BW/4HANA ............................... 314, 321 SELECT statement ............................ 101, 104 Statement ........................................................ 53
RAND() ........................................................... 194 transformation ...................................... 317 UPSERT ..................................................... 214 Streaming cluster ......................................... 30

406 407
Index Index

String Test library ................................................... 364 User-defined functions ............ 43, 83, 344 VERTICAL_UNION .................................... 332
operators .................................................... 62 modularization ..................................... 363 call and use ................................................ 85 View ................................................................ 274
padding .................................................... 167 Test procedures .......................................... 363 create ........................................................... 83 Virtual tables ............................................... 274
replace variable ..................................... 166 Test-driven development ....................... 356 implementation ....................................... 91 Visibility ........................................................ 223
similarity .................................................. 169 Testing ................................... 94, 97, 355–356 properties ................................................... 83
trimming .................................................. 167 TEXT ................................................................ 157 sample application ................................. 89 W
STRING_AGG ............................................... 113 Text mining ................................................... 28 sample program flow ............................ 91
Structure comments ................................ 346 TIME ...................................................... 176, 181 scalar ......................................................... 111 Watchpoint .................................................. 373
Stub procedure ........................................... 292 Time information ...................................... 181 User-defined libraries ................................ 87 WEEK() ........................................................... 186
SUBARRAY() ................................................. 249 Time zone ..................................................... 187 User-defined table types ........................ 273 WEEKDAY() .................................................. 186
Timeline ........................................................ 382 USING ............................................................ 289 WHEN MATCHED ...................................... 216
Subquery ................................... 116, 145, 236
TIMESTAMP ................................................. 182 view ............................................................ 292 WHERE clause ............................................. 127
correlated ................................................ 115
TO_DATE() function ................................. 178 WADP routine ........................................ 325 DELETE ...................................................... 217
in field lists .............................................. 114
TO_NVARCHAR ................................ 157, 178 UTC ................................................................. 187 UPSERT ..................................................... 214
SUBSTR_AFTER() ........................................ 160
UTCTOLOCAL() ........................................... 187 WHERE condition ...................................... 130
SUBSTR_BEFORE() ..................................... 160 TO_TIME() ..................................................... 181
TO_VARCHAR ............................................. 178 comparison ............................................. 130
SUBSTR_REGEXPR() ......................... 161, 163
SUBSTRING() ............................................... 160 TO_VARCHAR() ................................ 157, 181 V with multiple values ............................ 130
WHILE Loop ................................................. 240
Subtracting sets ......................................... 145 TOP .................................................................. 105
Value Whitespace ..................................................... 54
Successive transformations .................. 320 Transaction context ................................. 217
constant ................................................... 111 Window functions ................. 115–116, 118
SUM ...................................................... 112–113 Transaction control .................................. 253
VARBINARY ................................................. 200 WITH clause ....................................... 137–138
System database ........................................... 31 Transaction log ............................................. 23
VARCHAR ..................................................... 154 WITH ENCRYPTION ..................................... 80
System variable ............................................. 60 Transaction RSA1 ...................................... 319
Variables ....................................................... 219 WITH ORDINALITY ................................... 250
Transformation .......................................... 314
local scalar .............................................. 219 WITH PRIMARY KEY ................................. 213
on SAP HANA ......................................... 316
T scalar ......................................................... 111
routine ............................................. 318–319
unnecessary ............................................ 387
Table ............................................................... 268 Transport ...................................................... 322
visibility .................................................... 223
alias ............................................................ 147 Triggers ................................................ 267, 278
change ...................................................... 272 limit reproduction ................................ 280
convert to string ................................... 174 per row ...................................................... 281
copy ............................................................ 271 per statement ......................................... 281
create with SQL ..................................... 271 Trigonometry .............................................. 194
definition ................................................. 268 TRIM_ARRAY() ............................................ 249
delete ......................................................... 273 TRIM() ............................................................. 168
expressions ............................................. 119 Troubleshooting ........................................ 355
global temporary .................................. 293 TRUNCATE TABLE ...................................... 217
local variable .......................................... 224
parameter ......................................... 66, 292 U
tables used .............................................. 383
temporary ............................................... 270 UCASE() .......................................................... 159
type ................................................... 269, 273 UDF_SORT_2 ............................................... 238
Table variables ........................... 66, 102, 210 UDF_SORT_3 ............................................... 238
declare ....................................................... 102 UMINUS() ...................................................... 194
use .............................................................. 103 Unicode ......................................................... 154
Tabs .................................................................... 54 UNICODE() .................................................... 170
Uniform terms ............................................ 342
TAN() ............................................................... 194
UNION ............................................................ 143
TANH() ........................................................... 194
UNIQUE ......................................................... 269
Task management .................................... 393
UNNEST() ...................................................... 250
Temporary table ........................................ 235
UPDATE ......................................................... 211
Tenant ............................................................... 30
reference to other tables .................... 212
Tenant database ............................................ 31
table operator ........................................ 228
Test cases ............................................... 98, 361
UPPER() .......................................................... 159
Test data ........................................................... 98
UPSERT .......................................................... 213

408 409
First-hand knowledge.

Jörg Brandeis is the managing director of Brandeis Consulting


GmbH in Mannheim, which offers training and consulting for
SAP BW/4HANA, SAP HANA and SQLScript. Until mid-2015, Mr.
Brandeis worked as head of development at zetVisions AG in
Heidelberg, where he was responsible for the development and
architecture of the SAP NetWeaver-based products zetVisions CIM and SPoT.
In this role, he worked extensively with agile development methods and clean
code.

Jörg Brandeis

SQLScript for SAP HANA


387 pages, 2nd, updated and revised edition 2021, $69.95
ISBN 978-1-4932-2139-4
We hope you have enjoyed this reading sample. You may recommend
or pass it on to others, but only in its entirety, including all pages. This
www.sap-press.com/5336
reading sample and all its parts are protected by copyright law. All usa-
ge and exploitation rights are reserved by the author and the publisher.

You might also like