0% found this document useful (0 votes)
344 views130 pages

Abap On Hana

Uploaded by

Alexandra Olariu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
344 views130 pages

Abap On Hana

Uploaded by

Alexandra Olariu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

ABAP on HANA Workshop

SAP Active Global Support


ABAP Database Connectivity -
ADBC
Learning Objectives: ADBC

After completing this unit you will be able to:

• Use ADBC to access database tables

© 2011 SAP AG. All rights reserved. RKT 3


Introduction of the ADBC

• ADBC is an API (application programming interface) for the


Native SQL interface of the AS ABAP that is based on ABAP
Objects.
• The methods of ADBC make it possible to :
 Send database specific SQL commands to a database system and
process the result.
 Establish secondary database connections.
 Access the views and tables in any database (including HANA)
directly.

© 2011 SAP AG. All rights reserved. RKT 4


Why do we need ADBC in 7.40?

• In SAP_BASIS 7.40 (Suite on HANA), all the views and procedures


created in HANA can be exposed to ABAP DDIC and used directly (using
OPEN SQL) in the ABAP code.
• In case of side-by-side scenario (HANA accelerators), ADBC is used to
access views, procedures and tables on HANA.
• In Suite on HANA, we may still use ADBC to access analytical views with
currency conversion functions* or generating DB procedure with an
ABAP code.

Note – More details in DEMO.

© 2011 SAP AG. All rights reserved. RKT 5


Difference to Open SQL and ADBC ( Native SQL )

Advantage of Open SQL: Advantage of ADBC (Native SQL) :


• Simple and High Readability, • Specific SQL Statements for HANA
can be executed
• Syntax Check on SQL Statements,
• Ability to Access All the Views and
• Easily Performance Trace, Tables in HANA Directly,
• Database Independent.

© 2011 SAP AG. All rights reserved. RKT 6


Classes in ADBC

The following four ADBC classes are the most important classes.
• CL_SQL_STATEMENT – Execution of SQL Statements

• CL_SQL_RESULT_SET – Result of the Execution

• CL_SQL_CONNECTION – Administration of Database Connections

• CL_SQL_EXCEPTION – Exception Handling

• Note - We would take up first 2 classes in the Course. For the details on the others, please
refer to appendix or http://help.sap.com/abapdocu_702/de/abenadbc.htm
© 2011 SAP AG. All rights reserved. RKT 7
CL_SQL_STATEMENT

• CL_SQL_STATEMENT is used to set and execute SQL statements.


• The instances of CL_SQL_STATEMENT can be created by
‘CREATE OBJECT’ statement.

• The default database where the SQL statements execute is the central
database of the AS ABAP. The methods to execute SQL statements on
another (secondary) databases* are out of scope for this training.

*Refer to http://help.sap.com/abapdocu_702/de/abencl_sql_connection.htm

© 2011 SAP AG. All rights reserved. RKT 8


CL_SQL_STATEMENT

• There are three methods to execute SQL statements. These methods


have an obligatory input parameter STATEMENT of type string, to which
syntactically correct SQL statement must be passed.

 EXECUTE_QUERY – For Queries (SELECT statements)

 EXECUTE_DDL – For DDL (CREATE, DROP, or ALTER)

 EXECUTE_UPDATE – For DML (INSERT, UPDATE, or DELETE)

© 2011 SAP AG. All rights reserved. RKT 9


CL_SQL_STATEMENT

• EXECUTE_QUERY – This method is used to execute queries


(SELECT statements). It returns an instance of CL_SQL_RESULT_SET
as the result of the query.

• EXECUTE_DDL - This method is used to execute Data Definition


Language statements such as CREATE, DROP, or ALTER. It doesn‟t
have a RETURNING parameter.

• EXECUTE_UPDATE – This method is used to execute Data


Manipulation Language ( DML ) statements such as INSERT, UPDATE,
or DELETE and it returns the number of table rows processed in
ROWS_PROCESSED.

© 2011 SAP AG. All rights reserved. RKT 10


Example Code
DDL & DML & Query Commands

DATA: lo_sql TYPE REF TO cl_sql_statement .


CREATE OBJECT lo_sql .
* Execute DDL statement
lo_sql->execute_ddl(
`CREATE TABLE dbtable` &&
`(val1 char(10) NOT NULL,` &&
` val2 char(10) NOT NULL,` &&
` PRIMARY KEY (val1) )`).
* Execute DML statement
lo_sql->execute_update(
`INSERT INTO dbtable VALUES('10', '10')`).
* Execute Query ( Describe in detail in following slides )
lo_result = lo_sql->execute_query(
'SELECT val1, val2 FROM dbtable' ).

© 2011 SAP AG. All rights reserved. RKT 11


CL_SQL_STATEMENT

• There is another method SET_TABLE_NAME_FOR_TRACE in the


CL_SQL_STATEMENT class. It can pass the views‟ name to the SQL
trace tools, such as SM50, STAD and ST05.
• You should execute this method just before that you want to execute
SQL statement. Then it will be directly shown in the trace result list and
tell others which views are being operated now.
• The method increases understandability by setting names where
appropriate. This will ease troubleshooting and performance analysis.
Please invoke this method every time you execute the SQL statement
via ADBC.

© 2011 SAP AG. All rights reserved. RKT 12


Example Code
SET_TABLE_NAME_FOR_TRACE

DATA: lo_sql TYPE REF TO cl_sql_statement,


lo_result TYPE REF TO cl_sql_result_set,
dref TYPE REF TO data,
val1 TYPE snwd_bpa-bp_id, val2 TYPE snwd_bpa-company_name,
val3 type snwd_so_i-gross_amount, tname TYPE tabname.
CREATE OBJECT lo_sql .
tname = 'AN_OPEN_ITEMS'.
lo_sql->set_table_name_for_trace( tname ).
lo_result = lo_sql->execute_query(
'SELECT bp_id, company_name,
SUM( gross_amount_converted ) AS sum_amount
FROM "_SYS_BIC"."test.oia.300.316/AN_OPEN_ITEMS"
GROUP BY bp_id, company_name ').
GET REFERENCE OF val1 INTO dref. lo_result->set_param( dref ).
GET REFERENCE OF val2 INTO dref. lo_result->set_param( dref ).
GET REFERENCE OF val3 INTO dref. lo_result->set_param( dref ).
lo_result->next( ). lo_result->close( ).
WRITE: / val1, val2, val3.
© 2011 SAP AG. All rights reserved. RKT 13
Example Code
SET_TABLE_NAME_FOR_TRACE

• SM50:

• ST05:

© 2011 SAP AG. All rights reserved. RKT 14


Example Code
SET_TABLE_NAME_FOR_TRACE

• STAD:

© 2011 SAP AG. All rights reserved. RKT 15


CL_SQL_RESULT_SET

• After the execution of a query, an instance of CL_SQL_RESULT_SET is


created and it stores the result data of the query.
• There are three methods of class CL_SQL_RESULT_SET to assign the
result to an object, a structure, or an internal table.

 SET_PARAM , NEXT , and CLOSE - Assign compatible ABAP data objects


to the columns of the result set
Like : ' SELECT SINGLE val1 val2 FROM dbtable INTO (wa1, wa2) ‘

 SET_PARAM_STRUCT , NEXT , and CLOSE - Assign compatible ABAP


structure to the row of the result set
Like : ' SELECT SINGLE val1 val2 FROM dbtable INTO ls_result '
© 2011 SAP AG. All rights reserved. RKT 16
CL_SQL_RESULT_SET

 SET_PARAM_TABLE , NEXT_PACKAGE , and CLOSE - Assign compatibly


structured internal table to the rows of the result set
Like : ' SELECT val1 val2 FROM dbtable INTO TABLE lt_result '

© 2011 SAP AG. All rights reserved. RKT 17


CL_SQL_RESULT_SET

SET_PARAM, NEXT, and CLOSE :

• These methods are used to assign several compatible ABAP data


objects to the columns of the result set from left to right.
lo_result = sql->execute_query('SELECT val1, val2 FROM dbtable').

GET REFERENCE OF wa1 INTO dref. lo_result->set_param( dref ).

GET REFERENCE OF wa2 INTO dref. lo_result->set_param( dref ).

lo_result->next( ).
wa1 wa2
val 0 val 1 val 2 val 3
SELECT val1, val2
XX XX XX XX …… FROM dbtable
val 1 val 2
Result
XX XX XX XX …… XX XX
…… …… …… …… …… XX XX Set
Database Table …… ……
© 2011 SAP AG. All rights reserved. RKT 18
CL_SQL_RESULT_SET

SET_PARAM, NEXT, and CLOSE :

• With the call of NEXT, one row in the result set of the query will be
addressed and the value of the columns in that row will be assigned to
those objects which are defined by SET_PARAM.

• The method NEXT will return value 1 if the row can be addressed and 0 if
it cannot be.
IF rc > 0.
... “Handling the result
ELSE.
WRITE 'No entry found.'.
ENDIF.

© 2011 SAP AG. All rights reserved. RKT 19


CL_SQL_RESULT_SET

SET_PARAM_STRUCT, NEXT, and CLOSE

• These methods are used to assign a completely compatible ABAP


structure to the rows of the result set.
lo_result = sql->execute_query('SELECT val1, val2 FROM dbtable').

GET REFERENCE OF ls_result INTO dref.

lo_result->set_param_struct( dref ).
ls_result
lo_result->next( ). wa1 wa2

val 0 val 1 val 2 val 3


SELECT val1, val2
XX XX XX XX …… FROM dbtable
val 1 val 2
Result
XX XX XX XX …… XX XX
…… …… …… …… …… XX XX Set
Database Table …… ……
© 2011 SAP AG. All rights reserved. RKT 20
CL_SQL_RESULT_SET

SET_PARAM_STRUCT, NEXT, and CLOSE

• With the call of NEXT, one row of result of the query will be addressed
and the value of that row will be assigned to the structure which is defined
by SET_PARAM_STRUCT.

• The method NEXT will return value 1 if the row can be addressed and 0 if
it cannot be.
IF rc > 0.
... “Handling the result
ELSE.
WRITE 'No entry found.'.
ENDIF.

© 2011 SAP AG. All rights reserved. RKT 21


CL_SQL_RESULT_SET

SET_PARAM_TABLE, NEXT_PACKAGE, and CLOSE

• These methods are used to assign a completely compatibly structured


internal table to the rows of the result set.
lo_result = sql->execute_query('SELECT val1, val2 FROM dbtable').
lt_result
GET REFERENCE OF lt_result INTO dref.
…… ……
lo_result->set_param_table( dref ).
XX XX
lo_result->next_package( ).
XX XX
APPEND
val 0 val 1 val 2 val 3
SELECT val1, val2
XX XX XX XX …… FROM dbtable
val 1 val 2
Result
XX XX XX XX …… XX XX
…… …… …… …… …… XX XX Set
Database Table …… ……
© 2011 SAP AG. All rights reserved. RKT 22
CL_SQL_RESULT_SET

SET_PARAM_TABLE, NEXT_PACKAGE, and CLOSE

• At each call of NEXT_PACKAGE, it reads out at most the number of rows


that are passed to the input parameter UPTO and append them to the
target internal table without deleting the previous contents. If no value is
passed to UPTO, all the rows are read out.

• In the method NEXT_PACKAGE, the number of rows read is returned in


the return value ROWS_RET.
rc = lo_result->next_package( ).

• With all series of methods, reading out is completed using CLOSE.


lo_result->close( ).

© 2011 SAP AG. All rights reserved. RKT 23


CL_SQL_RESULT_SET

• If you need to select one entry (row) and assign several values
(columns) in it to local variables instead of one structure, you can use
SET_PARAM to define those variables as target variables one by one.

• If you only want to get a whole entry (row), you can assign the target
structure to the row by SET_PARAM_STRUCT.

• If you want to assign rows of the result to the internal table, you need
SET_PARAM_TABLE.

© 2011 SAP AG. All rights reserved. RKT 24


DAY 2
Summary: ADBC

You should now be able to:

• Use ADBC to access database tables

© 2011 SAP AG. All rights reserved. RKT 25


Demo – Introduction of the ADBC

DEMO:

• Access database‟s table via ADBC in ABAP

© 2011 SAP AG. All rights reserved. RKT 26


HANA Specific solutions :
Code Pushdown
DAY 2
Learning Objectives: HANA Specific solutions – Code
pushdown

After completing this unit you will be able to:

• Understand the basics of Modeling Views in HANA.


• Attribute View, Analytical view, Calculation view.
• Understand and use External views and DB procedure Proxies.
• Understand and write simple DB procedures
• Use ABAP to access views and DB procedures in HANA.

© 2011 SAP AG. All rights reserved. RKT 28


HANA Specific Solutions

• HANA specific solutions help us move the application logic to HANA. It is


called as „code pushdown‟ or „code to data‟.
 The data transferred between AS and DB is minimized
 Number of round trips are reduced significantly.

© 2011 SAP AG. All rights reserved. RKT 29


Modeling Views in a Nutshell
Modeling with SAP HANA Studio

• Attribute View

• Analytic View

• Calculation View

© 2011 SAP AG. All rights reserved. RKT 30


Modeling Views
Calculation Column
Calculation View Tables
Engine

Attribute View
OLAP Analytic View Join
Engine Engine

Legend:
:can use

© 2011 SAP AG. All rights reserved. RKT 31


Decide on where to Build Content?

Analyze Query
Logic

yes no
Information
in existing
tables

Access Base
Tables no
yes Only Joins &
calculated
expressions

Use Attribute
yes Star Schema no
Views
or
Aggregation

Use Analytic
yes no
Views
Calculation
View

Use Graphical or Use DB


Scripted Calc Procedures with
Views SQLScript

© 2011 SAP AG. All rights reserved. RKT 32


Attribute View

© 2011 SAP AG. All rights reserved. RKT 33


Modeling Views
Attribute View

• Attribute View:
 It is mostly processed in JOIN Engine

 Master data modeling: used to join master data tables e.g. “Plant/Location” 
“Material”, “Business Partner”  “Business Partner Address”

 can be used to join two or more tables and also have calculated columns

© 2011 SAP AG. All rights reserved. RKT 34


Creating Attribute Views

• Right-click your Package in HANA Studio and select


New  Attribute View.
• Enter name, description, select the View Type 
Attribute View -> press Finish.

© 2011 SAP AG. All rights reserved. RKT 35


Creating Attribute Views
Select tables and attributes

• Now drag & drop master data table(s) into the Data Foundation section.
• Then at the Data Foundation section, right-click on the attributes -> Add to
Output.

© 2011 SAP AG. All rights reserved. RKT 36


Creating Attribute Views
Key Attribute

• At the Semantics section, define your Key Attribute(s).

 The key attribute is synonymous to the primary keys of a table but it is


not checked for uniqueness.

© 2011 SAP AG. All rights reserved. RKT 37


Creating Attribute Views
Join tables

• If more than 1 table was chosen, define the joins in the Data Foundation
section.

• Then Save, validate and activate.


 A runtime object will be created in the Catalog Schema _SYS_BIC.

© 2011 SAP AG. All rights reserved. RKT 38


Creating Attribute Views
Data Preview

• After creating an Attribute View you can preview it‟s data in table or
graphical form.

© 2011 SAP AG. All rights reserved. RKT 39


Calculated Columns

© 2011 SAP AG. All rights reserved. RKT 40


Calculated Columns

• Calculated Columns can be


created for Attribute Views, Analytic
Views, Calculation Views and is
calculated on-the-fly.

• Calculated Column = Calculated


Attribute or Calculated Measure

 For a Calculated Column, on


one or more existing attributes,
measures, other Calculated
Columns or constants can be
used.

 Calculations: string operations, If


/ Case / In / isnull operations,
mathematical functions, date
functions, conversion functions.

© 2011 SAP AG. All rights reserved. RKT 41


Calculated Columns
Risks

• Calculated Columns are intermediate results that need to be written into buffer
and take additional time.

 Calculated Columns can impact the performance, especially when complex


calculations need to be done.

• When a Calculated Column is defined for an Analytic View :

 the Analytic View is processed as Calculation View (Calc Engine), not


anymore as OLAP View ( OLAP engine), see Explain Plan 
Performance impact.

© 2011 SAP AG. All rights reserved. RKT 42


Calculated Columns
Risks
• Avoid Calculated Columns in the Where-clause of the SQL statement reading
data from the Attribute / Analytic / Calculation View

 the Where-clause is not pushed down to the bottom view/table

 Risk of high amount of data being processed  performance impact

• Avoid Filters on Calculated Columns

 The calculation first needs to be done for all selected records before the data
is filtered.

 Workaround:
Instead of a Calculated Column, it might be better (depending on the scenario) to
add a new fix table column and do the calculation during the time of inserting a new
data set into the table, e.g. via SLT.
Or do the calculation into a fix column via procedures scheduled periodically.
© 2011 SAP AG. All rights reserved. RKT 43
External Views

© 2011 SAP AG. All rights reserved. RKT 44


External Views

• External views are needed to access the HANA views/models using


OPEN SQL.
• External views are the ABAP repository object corresponding to a HANA
model/view.
• External views are stored and managed in the ABAP Dictionary - similar
to the regular Dictionary views .
• The external view only represents the HANA view. HANA view is the
leading object i.e. changes made to the fields in the HANA view imply
changes for the external view (in ABAP Dictionary).

© 2011 SAP AG. All rights reserved. RKT 45


External Views

• When an external view is created, the names and data types of the
fields from the HANA view/model are mapped onto compatible DDIC
names and DDIC data types (default mapping).
HANA Data Type Description ABAP Dictionary Type

SMALLINT 2-Byte integer INT2

INTEGER 4-Byte integer INT4

DECIMAL Packed number DEC

SMALLDECIMAL Packed number DEC

FLOAT Binary floating point number FLTP

VARCHAR Character string CHAR

© 2011 SAP AG. All rights reserved. RKT 46


External Views

HANA Data Type Description ABAP Dictionary Type

NVARCHAR Unicode character string CHAR

VARBINARY Byte string RAW

BLOB Byte string RAWSTRING

CLOB Character string STRING

NCLOB Unicode character string STRING

• HANA names that are compatible with DDIC naming rules (for
example, they do not contain more than 30 characters) are
mapped onto DDIC fields with the same name.

© 2011 SAP AG. All rights reserved. RKT 47


External Views

• Since the creation of a external view, the implementation of the related


HANA view may change. Thus it is occasionally necessary to perform
sync function. This gets the ABAP Dictionary object in sync with the
latest definitions in the corresponding HANA view.

• For creating an External view:


 Open the context menu of your package and choose New  Other ABAP
Repository Object  Dictionary  Dictionary View .

© 2011 SAP AG. All rights reserved. RKT 48


External Views

 Enter a Name* and a Description for the view to be created.

 Select the option External View.


 Enter the name of the appropriate HANA View that has already been
created and activated in the HANA Repository. (use Ctrl + Space for F4
help)
 This creates an inactive version of a Dictionary view for the corresponding
HANA view. The view definition will include default mappings of field names
and data types.
 Activate the external view.
*NOTE: Maximum length for names of external views is limited to 16 characters.
© 2011 SAP AG. All rights reserved. RKT 49
Analytic View

© 2011 SAP AG. All rights reserved. RKT 50


Modeling Views
Analytic View

• Analytic View: Mostly processed in OLAP Engine


 represents an OLAP view with a Star Schema including measures and attributes.

 Optimized for mass data processing and aggregations. Used for “Currency
Conversions” and “Unit conversions” functionalities

 Attribute View(s) (master data) are joined to the Fact Table (Data foundation) as
dimensions to give context to key figures (measures)

 Data is not stored but read at run time from the joined database tables.

© 2011 SAP AG. All rights reserved. RKT 51


Analytic View
OLAP Star Schema - Example

Data
Foundation
Delivery
Attribute Header
Delivery ID
View Delivery Date
Ship-to Party
Sold-to Party
Material Sales Org
Material ID 1
Material Class


Delivery
Item
Delivery ID
Item ID
Fact table
N
Material
Measure

• The Data Foundation can have multiple tables, but only one Fact table
can contain measures.
© 2011 SAP AG. All rights reserved. RKT 52
Creating Analytic Views

• In HANA Studio, right-click on your Package and choose New -> Analytic
View
• Enter Name and Description and click on Finish.

© 2011 SAP AG. All rights reserved. RKT 53


Creating Analytic Views

• Now drag & drop a Fact table into the Data Foundation section.
• In the same way drag & drop Attribute Views into the Logical Join section.

© 2011 SAP AG. All rights reserved. RKT 54


Creating Analytic Views
Select output, define Joins

• At the Data Foundation section, right-click on the desired Attributes or


Measures and click on „Add to Output.

• At the Logical Join section, build the Joins between Fact table / Data
Foundation and Attribute Views. Specify the Join type and Cardinality.

© 2011 SAP AG. All rights reserved. RKT 55


Creating Analytic Views
Define attributes and measures

• At the Semantics section, tab Local, define which output columns are
attributes and which are measures.
• For measures, define the aggregation type ( sum, max, min, count).

aggregation type
attribute

measure

• Then Save, validate and activate.


 A runtime object will be created in the Catalog Schema _SYS_BIC.
© 2011 SAP AG. All rights reserved. RKT 56
Creating Analytic Views
Data Preview

• You can see the result by pressing Data Preview and by executing
queries in SQL Editor.

• Remember that in the SQL statement you have to write the full view name:
Select * from “_SYS_BIC”.“<package_name>/<view_name>”

© 2011 SAP AG. All rights reserved. RKT 57


Defining Join Types

• Left (Right) Outer Join


 Returns all rows from the left (right) table, even if there are no

matches in the right (left) table. left right

 If records match, they are combined, otherwise the columns are empty.

 The Join and constraints (filters) will be executed only if fields from the joined table are
requested.

• Inner Join
 Returns rows when there is at least one match in both tables. left right

 Combines records from the left and right table exactly when the specified criteria are met.

 If the criteria are not met, no record is created in the result set.

 Is normally slower than Left Outer Join, as the join operation is always executed, no matter
which fields are requested. Should be used if constraints on the joined table have to be
always applied.
© 2011 SAP AG. All rights reserved. RKT 58
Defining Join Types

• Referential Join
 Default Join Type. left right left right

 Semantically an Inner Join that assumes that referential integrity

is given (e.g. ERP tables) and matching data exists in the joined tables.

 Referential Join (Inner Join) is only executed if fields from both joined tables are selected.

 If not, it works like a Left or Right Outer Join depending on the selected fields.

© 2011 SAP AG. All rights reserved. RKT 59


Results depending on Join Types
Example
Fact table – Data Foundation Dimension table – Attribute View
SALE_ID COST ITEM_ID ITEM_ID ITEM_DESCR
sale 1 20000 hnd JOIN on ITEM_ID hnd Hyundai
sale 2 25000 tyo tyo Toyota
sale 3 30000 bmw frd Ford
sale 4 35000 mrd mrd Mercedes
sale 5 20000 bmw
SALE_ID COST ITEM_ID ITEM_DESCR
• Left Outer Join returns all the rows from sale 1 20000 hnd Hyundai
left table and corresponding rows from sale 2 25000 tyo Toyota
sale 3 30000 bmw ?
right table if they exist. sale 4 35000 mrd Mercedes
sale 5 20000 bmw ?
• Inner Join returns only rows with
SALE_ID COST ITEM_ID ITEM_DESCR
ITEM_IDs that exist in both tables. sale 1 20000 hnd Hyundai
sale 2 25000 tyo Toyota
• Referential Join in that situation sale 4 35000 mrd Mercedes

returns different amount of rows SALE_ID COST ITEM_ID ITEM_DESCR SALE_ID COST
depending on the Select sale 1 20000 hnd Hyundai sale 1 20000
sale 2 25000 tyo Toyota sale 2 25000
statement because referential sale 4 35000 mrd Mercedes sale 3 30000
integrity is broken here („bmw‟ is sale 4 35000
BUT sale 5 20000
absent in Items table).
© 2011 SAP AG. All rights reserved. RKT 60
Calculation View

© 2011 SAP AG. All rights reserved. RKT 61


Modeling Views
Calculation View

• Calculation View:
 is mostly processed in Calculation Engine.

 Use Calculation Views when the application logic can‟t be modeled with an
Analytic/Attribute View.

 It is defined as graphical or scripted Calculation View (SQL Script).

© 2011 SAP AG. All rights reserved. RKT 62


Types of Calculation Views

• Graphical Calculation View


• Scripted Calculation View (=SQL Script based Calculation View)

Graphical Calculation SQL Script based Calculation View


View (here with CE functions)

Union Analytic View


Projection

Column
View
Projection structure

Analytic View

Union
© 2011 SAP AG. All rights reserved. RKT 63
Graphical Calculation View

© 2011 SAP AG. All rights reserved. RKT 64


Graphical Calculation View

Graphical Calculation View


 Only graphical elements are used, no SQL Script coding needed.

 Union, Join, Projection and Aggregation nodes are available.

 Analytic Views, Attribute Views, tables and other Calculation Views – all can be
used in a Calculation view
Attribute View
or Column
Store table

Analytic View

Calculation View

© 2011 SAP AG. All rights reserved. RKT 65


Create Graphical Calculation View

• Right-click your Package and select New


 Calculation View

• Choose „Graphical‟ View Type.

• Click Next to select needed Tables or


Attribute/Analytic/Calculation Views.

© 2011 SAP AG. All rights reserved. RKT 66


Create Graphical Calculation View
Join, Union, Projection or Aggregation nodes

• Connect tables and views as sources via Join, Union, Projection or


Aggregation nodes with the Output node:
 Join is used to connect fields of 2 different sources with Join. In the Join node,
specify the joined fields.

 Union is used to combine fields of multiple different sources. Combined fields


need to have the same data type.

© 2011 SAP AG. All rights reserved. RKT 67


Create Graphical Calculation View
Join, Union, Projection or Aggregation nodes

• Connect tables and views as sources via Join, Union, Projection or


Aggregation nodes with the Output node:
 Projection is used to select only the needed columns from the source,to add
calculated columns.

 Aggregation is used to aggregate data on specified fields, for example from


raw tables. For each aggregated measure you can choose the aggregation
type (sum, max, min).

© 2011 SAP AG. All rights reserved. RKT 68


Create Graphical Calculation View
Specify Attributes and Measures, Activate

• As next step you have to specify Attributes and Measures for the
Output node.

• Finally you can save, validate and activate the Calculation View and do
a Data Preview of the result.
© 2011 SAP AG. All rights reserved. RKT 69
Scripted Calculation View

© 2011 SAP AG. All rights reserved. RKT 70


Scripted Calculation View

• Scripted Calculation Views are created using SQL Script:


 SQL Script can query existing Attribute , Analytic Views , tables , Calculation
views.

 SQL Script can be used to create complex calculation functions.

• Scripted Calculation views provide more flexibility in implementing business


logic as compared to Graphical calculation view.

© 2011 SAP AG. All rights reserved. RKT 71


Scripted Calculation View
Example, SQL Script

Column View

• Scripted Calculation Views are created using SQL Script or CE functions.


• When activated, a Column View is created for the Output variable VAR_OUT
• VAR_OUT is the only output variable (table type) of Scripted calculation view.

© 2011 SAP AG. All rights reserved. RKT 72


Scripted Calculation View
Example, CE functions

• This Scripted Calculation View in this example uses CE functions.

Analytic View 1

Analytic View 2

Projection = Filtering or adding calculated columns

Union of both Analytic Views

© 2011 SAP AG. All rights reserved. RKT 73


Create Scripted Calculation View

• Right-click your Package


and select New 
Calculation View.

• To create a Scripted
Calculation View choose
„SQL Script‟ as View Type.

© 2011 SAP AG. All rights reserved. RKT 74


Create Scripted Calculation View

• Specify the fields for the Output Parameter var_out as result.


• Enter the SQL Script.

• Select Attributes and


Measures for the Output node.
• Finally activate it.

© 2011 SAP AG. All rights reserved. RKT 75


CE Functions
• Inside the SQL Script, SQL language and also highly optimized Calculation
Engine functions (CE Functions) can be used.
• Execution of CE Functions can benefit from internal parallelization.

• CE Functions should not be mixed with standard SQL statements because


different optimizer engines are used.
SQL

• But: Higher development

and maintenance efforts for CE functions


CE Functions, limited list

of available functions.

© 2011 SAP AG. All rights reserved. RKT 76


CE Functions

• CE_COLUMN_TABLE - get the contents of a table


• CE_JOIN_VIEW - get attribute view contents
• CE_OLAP_VIEW - procedure to get analytical view contents
• CE_CALC_VIEW - get calculation view contents
• CE_JOIN - inner join of two tables
• CE_LEFT_OUTER_JOIN - left outer join
• CE_RIGHT_OUTER_JOIN - right outer join
• CE_UNION_ALL - union for two tables, identical tuples won‟t be dropped
• CE_PROJECTION - apply a filter, compute expressions, rename column.
• CE_CALC - calculate an expression into a new column
• CE_AGGREGATION - aggregation of the data to a group of attributes
Supported aggregation functions: count, sum, min, max, average = sum/count
• CE_VERTICAL_UNION - concatenation of columns of two input tables,
no counterpart in SQL
• CE_CONVERSION - unit conversion of input table, no counterpart in SQL
© 2011 SAP AG. All rights reserved. RKT 77
SQL vs. CE Functions
Examples 1

SQL CE-Build In Function


SELECT on Column table SELECT CE_COLUMN_TABLE("COLUMN_TABLE", [A, B, C])
A, B, C
from
"COLUMN_TABLE"
SELECT on Attribute view SELECT CE_JOIN_VIEW("ATTRIBUTE_VIEW", [A, B, C])
A, B, C
from
"ATTRIBUTE_VIEW"
SELECT on Analytical view SELECT CE_OLAP_VIEW("ANALYTIC_VIEW", [A, B, C, D]);
A, B, C, SUM(D)
from
"ANALYTIC_VIEW"
GROUP BY
A, B, C
SELECT on Calculation View SELECT CE_CALC_VIEW("ANALYTIC_VIEW", [A, B, C, D]);
A, B, C, SUM(D)
from
“CALC_VIEW"
GROUP BY
A, B, C

© 2011 SAP AG. All rights reserved. RKT 78


SQL vs. CE Functions
Examples 2

SQL CE-Build In Function


WHERE clause SELECT var_tab =
A, B, C, SUM(D) CE_COLUMN_TABLE("COLUMN_TABLE");
from var_proj =
"ANALYTIC_VIEW" CE_PROJECTION(:var_tab, [A, B, C], ' "B" = ''value'' AND
WHERE "C" = ''value'' ');
B = 'value' AND C = 'value'
GROUP BY SELECT var_tab =
A, B, C, SUM(D) CE_COLUMN_TABLE("COLUMN_TABLE");
FROM var_agg =
"COLUMN_TABLE" CE_AGGREGATION(:var_tab, [SUM(D)], [A, B, C]);
GROUP BY
A, B, C
INNER JOIN SELECT A, B, Y, SUM(D) CE_JOIN("COLTAB1","COLTAB2", [KEY1, KEY2], [A, B, Y,
from "COLTAB1" INNER JOIN "COLTAB2" D])
ON
"COLTAB1"."KEY1" = "COLTAB2"."KEY1" AND
"COLTAB1"."KEY2" = "COLTAB2"."KEY2"
LEFT OUTER SELECT A, B, Y, SUM(D) CE_LEFT_OUTER_JOIN("COLTAB1","COLTAB2", [KEY1,
JOIN from "COLTAB1" LEFT OUTER JOIN "COLTAB2" KEY2], [A, B, Y, D])
ON
"COLTAB1"."KEY1" = "COLTAB2"."KEY1" AND
"COLTAB1"."KEY2" = "COLTAB2"."KEY2"

© 2011 SAP AG. All rights reserved. RKT 79


SQL vs. CE Functions
Examples 3

SQL CE-Build In Function


UNION ALL var_tab1 = SELECT A, B, C, D FROM var_tab1 =
"COLUMN_TABLE1"; CE_COLUMN_TABLE("COLUMN_TABLE1",[A,B,C,D]);
var_tab2 = SELECT A, B, C, D FROM var_tab2 =
"COLUMN_TABLE2";
CE_COLUMN_TABLE("COLUMN_TABLE2",[A,B,C,D]);
SELECT * FROM :var_tab1 UNION ALL var_out = CE_UNION_ALL(:var_tab1,:var_tab2);
SELECT * FROM :var_tab2;
UNION var_tab1 = SELECT A, B, C, D FROM n/a
"COLUMN_TABLE1";
var_tab2 = SELECT A, B, C, D FROM use CE_UNION_ALL
"COLUMN_TABLE2";

SELECT * FROM :var_tab1 UNION


SELECT * FROM :var_tab2;
SQL SELECT A, B, C, SUBSTRING(D,2,5) var_tab =
Expressions FROM "COLUMN_TABLE" CE_COLUMN_TABLE("COLUMN_TABLE");
var_proj =
CE_PROJECTION( :var_tab, ["A", "B", "C",
CE_CALC('midstr("D",2,5)', string) ]);
Right OUTER SELECT A, B, Y, SUM(D) CE_RIGHT_OUTER_JOIN("COLTAB1","COLTAB2", [KEY1,
JOIN from "COLTAB1" LEFT OUTER JOIN "COLTAB2" KEY2], [A, B, Y, D])
ON
"COLTAB1"."KEY1" = "COLTAB2"."KEY1" AND
"COLTAB1"."KEY2" = "COLTAB2"."KEY2"

© 2011 SAP AG. All rights reserved. RKT 80


HANA Views:
Which to use when

© 2011 SAP AG. All rights reserved. RKT 81


Modeling Views
Calculation Column
Calculation View Tables
Engine

Attribute View
OLAP Analytic View Join
Engine Engine

Legend:
:can use

© 2011 SAP AG. All rights reserved. RKT 82


SQL Script for Procedures-
Introduction

© 2011 SAP AG. All rights reserved. RKT 83


SQL Script
Introduction

• SQL Script is a collection of extensions to Structured Query Language


(SQL) which allow developers to push data intensive logic into the HANA
Database. It is the key for avoiding expensive copying of huge amount of
data from DB to AS.
• SQL Script allows to use control structures (like IF..ELSE, FOR, WHILE,
CASE etc..) which is not possible in simple open SQL‟s.

 Compared to SQL, SQLScript is much more powerful in implementing


business logics.

© 2011 SAP AG. All rights reserved. RKT 84


SQL Script vs SQL Queries
Introduction

•SQL Script SQL Queries


SQL Script can be used to implement SQL Queries do not have features to
complex business logic. implement business logic.
It therefore allows complex business As a consequence a business logic
logic to be pushed to the database cannot be pushed down into the
level. database using SQL queries.

SQL script can return multiple result SQL query can only return one result
sets. at a time.
Therefore the computation of multiple For the computation of multiple result
result sets can be done in one access sets multiple Database accesses are
to the Database. necessary.
HANA database provides Database Procedures to push down business logic to
database. The logics are programmed in SQL Script language.
Note: For more details on how to write SQL script, refer to Appendix
© 2011 SAP AG. All rights reserved. RKT 85
HANA Database Procedures

© 2011 SAP AG. All rights reserved. RKT 86


Procedure
Introduction

• HANA provides Procedures to implement very complex application logic.


• Procedures provides much higher flexibility which HANA views might lack.
• Only input parameters and final result sets (more than one possible)
move between application and HANA when the procedure is executed.

© 2011 SAP AG. All rights reserved. RKT 87


Procedure
Creation

• To create a Procedure in HANA, use HANA Studio and create a new


Procedure for your package:

© 2011 SAP AG. All rights reserved. RKT 88


Procedure
Procedures with more than on result set

• Currently ADBC cannot be used to access Procedures that


return more than one result set.
• Such Procedures have to be accessed by exposing them to
ABAP DDIC *.

*More details during DEMO


© 2011 SAP AG. All rights reserved. RKT 89
Which HANA Artifact to use

© 2011 SAP AG. All rights reserved. RKT 90


Decide on where to Build Content?

Analyze Query
Logic

yes no
Information
in existing
tables

Access Base
Tables no
yes Only Joins &
calculated
expressions

Use Attribute
yes Star Schema no
Views
or
Aggregation

Use Analytic
yes no
Views
Calculation
View

Use Graphical or Use DB


Scripted Calc Procedures with
Views SQLScript

© 2011 SAP AG. All rights reserved. RKT 91


Pros and Cons of different
HANA Artifacts

© 2011 SAP AG. All rights reserved. RKT 92


Code Pushdown – Pros and Cons of different HANA
Artifacts
4: Scripted Calculation
3: Calculation View View (SQL
1: Attribute View 2: Analytic View 5: Database Procedures
(Graphical) script/CE
Functions)

Used for Used for Used for implementing Used for implementing
analytical implementing business logics that
Used for simple complex business logics
purposes where business logics that
applications involving can‟t be modeled using that can‟t be modeled using
Usage read operations can‟t be modeled
joins and calculated Attribute or Analytic Attribute or Analytic Views
on mass data and using only Attribute
expressions Views or graphical or CalcView (Graphical and
aggregations are or Analytic Views.
CalcView. scripted) .
required.

Very good User-friendly  No Gives highest flexibility for


Easy to model as Gives high flexibility as
performance SQL, SQL Script or implementing very complex
compared to other compared to other views
when dealing with CE functions logics. Multiple result-sets
Pros artifacts. Good to implement complex
huge amount of knowledge required. can move from HANA to
performance when business logic. Supports
data and Supports UNION. AS in one call to the
dealing with joins. UNION
aggregations. database.

Limitations in regards Performance depends on


to graphical how the logic is written (if
No support for Limitations in functions. Only High efforts for CE functions are used, if
complex calculation regards to UNION, development because the queries are dependent
Cons and logic e.g. functionalities AGGREGATION, have to write/code own on each other , if cursor is
currency conversion e.g. No UNION JOIN and logic. High in complexity used for single line
etc. supported. PROJECTION if CE functions are used. access). Performance is
supported not always optimal as
compared to other views.

© 2011 SAP AG. All rights reserved. RKT 93


Database Procedure Proxy

© 2011 SAP AG. All rights reserved. RKT 94


Database Procedure Proxy

• Database procedure proxies are ABAP repository objects that make it


possible to access HANA DB procedures ( HANA-based
application/business logic) in ABAP codes.
• Database procedure proxies are stored and managed in the ABAP
Dictionary.

• Database procedure proxies define mappings for the following:


 Names of the input and output parameters from the database procedure
and the parameter names to be used in ABAP
 Types that are defined for the parameters in the database procedure and
the ABAP data types.

© 2011 SAP AG. All rights reserved. RKT 95


Database Procedure Proxy

ABAP Interface that contains type Definition

Importing Parameter

Exporting Parameter

Table type Scalar type

• For each database procedure proxy, an ABAP interface is also


generated, where the appropriate ABAP data types are defined.

© 2011 SAP AG. All rights reserved. RKT 96


Database Procedure Proxy

• For each HANA database procedure only one database procedure


proxy should be created. Even though several proxies can be created
for one database procedure, this approach is not recommended.
• For creating DB procedure proxy:
 Open the context menu of your package and choose New  Other ABAP
Repository Object  Dictionary  Database Procedure Proxy.
 Enter the Name and Description for the proxy to be created. (use Ctrl +
Space for F4 help)

© 2011 SAP AG. All rights reserved. RKT 97


Database Procedure Proxy

 The wizard automatically proposes a name ZIF_<PROXY_NAME> for the


ABAP interface to be created. We can change the proposal if wanted.
 This creates an inactive version of a proxy for the corresponding HANA
database procedure. The proxy definition will include default mappings of
field names and data types.
 Activate the proxy.

© 2011 SAP AG. All rights reserved. RKT 98


Database Procedure Proxy

• When a database procedure proxy is created, the names and data


types of input and output parameters from the HANA DB procedure are
mapped onto compatible ABAP names and data types (default
mapping).
• Names of the components of table-type parameters can be changed .
This is particular need and useful during MOVE- CORRESPONDING ABAP
command.

• One HANA data type can be mapped onto several compatible ABAP
data types. All the options of compatible data types are available in the
drop down and can be chosen.
• With the DDIC Type Override function, we can use already existing
suitable data elements or structures in the ABAP Dictionary for the
data type mapping. ABAP data types are overridden then.
Note – With DDIC type override only data elements and flat structures from the ABAP Dictionary can be assigned to the
proxy parameters as data types. Use of deep structure types is not supported
© 2011 SAP AG. All rights reserved. RKT 99
Database Procedure Proxy

• Changing parameter names to be used in ABAP code:

• Changing data types to be used in ABAP code

© 2011 SAP AG. All rights reserved. RKT 100


Database Procedure Proxy

• Overriding data types with DDIC types :

© 2011 SAP AG. All rights reserved. RKT 101


Database Procedure Proxy

• Checking the consistency of the Proxy checks the below:


 The changed parameter names are valid ABAP names (whether they
contain valid characters).
 There is consistency between the HANA repository and the proxy definition
in the ABAP repository.

© 2011 SAP AG. All rights reserved. RKT 102


Database Procedure Proxy

• Since the creation of a proxy, the implementation of the related HANA


DB procedure may change. Thus it is occasionally necessary to
perform sync function. This gets the ABAP Dictionary object in sync
with the latest definitions in the corresponding HANA DB procedure.

© 2011 SAP AG. All rights reserved. RKT 103


Database Procedure Proxy

• Calling DB procedure proxy in ABAP:

© 2011 SAP AG. All rights reserved. RKT 104


DAY 2
Summary: HANA specific solution – Code pushdown

You should now be able to:

• Understand HANA views, SQL Script and DB procedures in HANA.


• Understand and create External views.
• Understand and create DB procedure proxy

© 2011 SAP AG. All rights reserved. RKT 105


Demo + Exercises – HANA Specific solutions – Code
pushdown
Lessons Topics
Demos + Exercise Modeling, ABAP: Creating a Attribute View to calculate the DAYS OPEN
(difference between todays’ date and date on which SO was created) for each
SO.

Accessing the attribute view with OPEN SQL.

Demos Performance: Open days in ABAP v/s Open days in HANA

Demos + Exercise Modeling , ABAP: Creating Analytical view to calculate gross amount per
business partner in USD.

Accessing the analytical view through ADBC.

Demos Performance: Currency conversion in ABAP v/s Currency conversion in HANA

Demos Modeling: Creating Calculation views to mark specific Business Partners as


SPECIAL based on predefined conditions (Scripted and Graphical)

© 2011 SAP AG. All rights reserved. RKT 106


Demo + Exercises – HANA Specific solutions – Code
pushdown
Lessons Topics
Demos + Exercise Code Push down: Writing DB procedure to find the Business partners with
highest 5 and bottom 5 Gross Revenue

Demos+ Exercise Code Push down, ABAP: Creating DB procedure Proxy and calling DB
procedures from ABAP code.

© 2011 SAP AG. All rights reserved. RKT 107


Relation between the tables used in Exercises and Demos

© 2011 SAP AG. All rights reserved. RKT 108


Appendix
ABAP Database Connectivity -
ADBC
CL_SQL_CONNECTION

• If you want to execute SQL statements on another database, an


instance of CL_SQL_CONNECTION should be created first to represent
one of the connections which registered in AS ABAP.
• The GET_CONNECTION method of this class can be passed a
connection name from the column DBCON (SAP T-code SM30). This
method attempts to open the corresponding connection and, if successful,
it creates an instance of CL_SQL_CONNECTION and returns the
corresponding reference.

DATA lo_con_ref TYPE REF TO cl_sql_connection.

Connected to ABC:

lo_con_ref = cl_sql_connection=>get_connection( ‘ABC’ ).

.
© 2011 SAP AG. All rights reserved. RKT 110
CL_SQL_CONNECTION

• Instances of CL_SQL_CONNECTION that are created with CREATE


OBJECT represent the standard connection to the central database.
Connected to Central DB:

CREATE OBJECT lo_con_ref.

© 2011 SAP AG. All rights reserved. RKT 111


CL_SQL_CONNECTION

• References to instances of CL_SQL_CONNECTION can be passed to


the CON_REF parameter of the instance constructor of
CL_SQL_STATEMENT. The instances created in this way execute their
SQL statements on the database whose connection is represented by
the instance of CL_SQL_CONNECTION.
CREATE OBJECT lo_sql EXPORTING con_ref = lo_con_ref.

• The database connection is closed by the instance method CLOSE of


CL_SQL_CONNECTION. This method has no effect in instances that
represent the standard connection.

© 2011 SAP AG. All rights reserved. RKT 112


Example Code
A Simple Statement to Secondary Database Connection

DATA: lo_sql TYPE REF TO cl_sql_statement,


lo_result TYPE REF TO cl_sql_result_set,
lr_flight TYPE REF TO DATA,
lt_flight TYPE TABLE OF sflight.

CREATE OBJECT lo_sql

EXPORTING con_ref = cl_sql_connection=>get_connection( 'HDB' ).

lo_result = lo_sql->execute_query(

'SELECT * FROM SFLIGHT WHERE ...' ).


GET REFERENCE OF lt_flight INTO lr_flight.
lo_result->set_param_table( lr_flight ).
lo_result->next_package( ).
lo_result->close( ).

© 2011 SAP AG. All rights reserved. RKT 113


CX_SQL_EXCEPTION

• The execution codes of SQL statements should be surrounded with


TRY – CATCH control structures in case errors of SQL statement or
database itself occur.
• When any error occurs in the execution of the SQL statement, it will be
caught and a instance of CL_SQL_EXCEPTION will be created. The
error can then be handles appropritalely.

© 2011 SAP AG. All rights reserved. RKT 114


CX_SQL_EXCEPTION

TRY .

lo_result = lo_sql->execute_query('...').

...
Attribute Meaning
CATCH cx_sql_exception DB_ERROR
"X", if an SQL statement was not
executed by DBMS.
"X", if you want to create a
INTO lo_err. DBOBJECT_EXISTS database object that already exists.

MESSAGE lo_err DBOBJECT_NOT_EXIST "X", if you want to access a


S database object that does not exist.
TYPE 'I' "X", if a DML statement would
DUPLICATE_KEY violate a unique table key.
DISPLAY LIKE 'E'.
INTERNAL_ERROR Internal error code from DBMS.
ENDTRY. "X", if you want to use an invalid or
INVALID_CURSOR closed database cursor.
Database-specific error code, if
SQL_CODE DB_ERROR is "X".
Database-specific error code, if
SQL_MESSAGE DB_ERROR is "X".

© 2011 SAP AG. All rights reserved. RKT 115


Appendix
SQL Scripts in HANA
SQL Script
Data Types

• SQL Script supports the below scalar data types.


Scalar Data types:
 Integer: TINYINT, SMALLINT, INTEGER, BIGINT
 Float: DECIMAL(p, s), REAL, FLOAT, DOUBLE
 Character: VARCHAR, NVARCHAR, CLOB, NCLOB
 Binary: VARBINARY, BLOB
 Time: DATE, TIME, TIMESTAMP

• But in addition, it also allows to use and define user-defined table types.

© 2011 SAP AG. All rights reserved. RKT 117


SQL Script
Data Types

Table Type Definition


• SQL Script allows you to define and use user-defined table types.
• These table types are used to define parameters for a procedure that
represent tabular results.
• They are also used to store the result set of SQL statement for further
data manipulation within the procedure.
Syntax:

CREATE TYPE {schema.}name AS TABLE (attribute1 type1 , attribute2


type2,...)

© 2011 SAP AG. All rights reserved. RKT 118


SQL Script
Table Types

• The table type is specified using a list of attribute names and primitive
data types. For each table type, attributes must have unique names.
• In order to create a table type in a different schema than the current
default schema, the schema has to be provided as a prefix.

• Table types do not have an instance that is created when the table type
is created. No DML is supported on the table types.

tt_publishers
publisher INTEGER
name VARCHAR(5
0)
price DECIMAL
cnt INTEGER
© 2011 SAP AG. All rights reserved. RKT 119
SQL Script
Table Types

• A table type can be dropped using the DROP TYPE statement.


 DROP TYPE {schema.}name {CASCADE};

• By default, the drop statement invalidates dependent objects. For


example, if a procedure uses the table type in its parameters, it will be
invalidated.

© 2011 SAP AG. All rights reserved. RKT 120


SQL Script
Writing simple procedure

• Procedures describe a sequence of data transformations on data


passed as input and database tables.
• Procedures can have multiple input and output parameters which can be
scalar types or table types.

• It is a callable statement, and so it can be called using a CALL


statement.
CREATE PROCEDURE testproc( IN cnt INTEGER, OUT result tt_result)

LANGUAGE SQLSCRIPT READS SQL DATA AS

BEGIN

RESULT = SELECT …… FROM dbtab WHERE count = :cnt;

End;

© 2011 SAP AG. All rights reserved. RKT 121


SQL Script
Writing simple procedure

CREATE PROCEDURE
• This SQLScript defines a read-only testproc( IN cnt
procedure which has 1 scalar input INTEGER, OUT result
parameters and 1 output parameters of type tt_result)
table. LANGUAGE SQLSCRIPT
• As different languages are supported in the READS SQL DATA AS
body of the procedure, the implementation
language is defined to be SQLScript.
BEGIN
• The implementation language is by default
SQLSCRIPT. It is good practice to define RESULT = SELECT …… FROM
the language in all procedure definitions. dbtab WHERE count =
:cnt;

END;

© 2011 SAP AG. All rights reserved. RKT 122


SQL Script
Writing simple procedure

• Procedure is tagged as read only procedure CREATE PROCEDURE


testproc( IN cnt
using READS SQL DATA. INTEGER, OUT result
tt_result)
• Notice that it is a read-only procedure. It can
only be called by other read-only LANGUAGE SQLSCRIPT
procedures.
READS SQL DATA AS
• One factor to be considered is that neither
DDL (create, alter, drop) nor DML (insert,
update, delete) statements are allowed in its BEGIN
body. RESULT = SELECT …… FROM
dbtab WHERE count =
• The advantage to this definition is that :cnt;
certain optimizations are only available for
END;
read-only procedures.

© 2011 SAP AG. All rights reserved. RKT 123


SQL Script
Writing Simple procedures

• The below command Drops a procedure created by CREATE


PROCEDURE from the database catalog.

DROP PROCEDURE {schema.}name {CASCADE}

• If a cascading drop is defined, dependent objects will also be dropped. If


a cascading drop is not defined, dependent objects will be invalidated.

© 2011 SAP AG. All rights reserved. RKT 124


SQL Script
Writing Simple procedures

• The below command is used to CALL a procedure


CALL {schema.}name (param1 {, ...})
E.g. call testproc (10,lt_result);

© 2011 SAP AG. All rights reserved. RKT 125


SQL Script
Example of a Procedure

CREATE PROCEDURE getOutput( IN cnt INTEGER, IN currency VARCHAR(3),


OUT output_pubs tt_publishers, OUT output_year tt_years) LANGUAGE
SQLSCRIPT READS SQL DATA AS

BEGIN

big_pub_ids = SELECT publisher AS pid FROM books -- Query Q1


GROUP BY publisher HAVING COUNT(isbn) > :cnt;

big_pub_books = SELECT title, name, publisher, -- Query Q2 year,


price FROM :big_pub_ids, publishers, books WHERE pub_id = pid AND
pub_id = publisher AND crcy = :currency;

output_pubs = SELECT publisher, name, -- Query Q3


SUM(price) AS price, COUNT(title) AS cnt FROM :big_pub_books
GROUP BY publisher, name;

output_year = SELECT year, SUM(price) AS price, -- Query Q4


COUNT(title) AS cnt FROM :big_pub_books GROUP BY year;

END;

© 2011 SAP AG. All rights reserved. RKT 126


SQL Script
Writing simple procedures

• In some cases, applications have to update the database content.


• We can have scalar variables as defined as local variables in the
procedure. Local variables can optionally be initialized with their
declaration. NULL is the default value for local variables
• Here is a simple example:;
lv_bp_id varchar(10):= ‘0100000001';

SELECT bp_id, company_name, phone_number

INTO lv_bp_id, lv_company_name, lv_phone_number

FROM SAPNVM.SNWD_BPA WHERE bp_id = :lv_bp_id;

‘:’ before variable means getting value of the variable.

‘:=’ is the assignment operator which assign the value on the left side to the variable on the right side.

© 2011 SAP AG. All rights reserved. RKT 127


SQL Script
Control Structures (IF structure)

• IF <bool-expr1> THEN
{then-stmts1}
{ELSEIF <bool-expr2> THEN {then-stmts2}}
{ELSE {else-stmts3}}
END IF

• The IF statement consists of a boolean expression – bool-expr1. If this


expression evaluates to true then the statements – then-stmts1 – in the
mandatory THEN block are executed. The IF statement ends with END IF. The
remaining parts are optional.

© 2011 SAP AG. All rights reserved. RKT 128


SQL Script
Control Structures (WHILE and FOR)

• While loop structure:


WHILE <bool-stmt> DO

{statements}

END WHILE;

• For loop structure:


FOR <loop-var> IN {REVERSE} <start> .. <end> DO

{statements}

END FOR;

• Break command ( BREAK;) and Continue command ( CONTINUE;) -


You can use break to immediately leave the loop and continue to
immediately resume with the next iteration.
© 2011 SAP AG. All rights reserved. RKT 129
SQL Script
Interesting Example

• There are many useful expression available in SQL in HANA. Here is a


interesting one.

Note: Please find a complete reference of SAP HANA database SQL in SAP HANA Database - SQL
Reference Manual.
© 2011 SAP AG. All rights reserved. RKT 130

You might also like