Sunteți pe pagina 1din 39

SAP HANA

SQL Script
Development Artefacts on HANA

■ All development artefacts on HANA get stored in one


single repository called the HANA Repository.

■ It will contain table definitions, SQL code used to create


DB objects,

■ The advantages are object management, versioning and


transports.
SQL Script

HANA database has its own scripting language named SQL


Script
SQL Script is a collection of EXTENSIONS to Structured Query
Language (SQL).

It is used to push down data intensive logic into the database.


SQL: Extensions
SQL Script is a collection of extensions to the Structured Query
Language (SQL). The extensions include:

■ Data extension, which allows the definition of table types without


corresponding tables

■ Functional extension, which allows the definition of (side-effect


free) functions which can be used to express and encapsulate
complex data flows

■ Procedural extension, which provides imperative constructs


executed in the context of the database process.
Why use SQL Script?
SQL Script is an interface for applications to access SAP
HANA Extension of ANSI Standard SQL

Language for creating stored procedures in HANA


– Declarative logic, including SELECT queries and built-in
calculation engine functions
– Orchestration logic, including Data Definition Language
(DDL), Data Manipulation Language (DML), assignment,
and imperative logic
Benefits of SQL Script?
The main goal of SQL Script is to allow the execution of Data-intensive calculations
inside SAP HANA database.

There are two reasons why this is required to achieve the best performance:
– Eliminates the need to transfer large amounts of data from the database to
the application
– Calculations need to be executed in the database layer to get the maximum
benefit from SAP HANA features such as fast column operations, query
optimization, and parallel execution. If applications fetch data as sets of rows
for processing on application level, they will not benefit from these features.
Benefits of SQL Script?
Compared to plain SQL queries, SQL Script has the following advantages:

– Functions can return multiple result sets, while an SQL query returns only one
result set

– Complex functions can be broken down into smaller functions enabling modular
programming, reuse, and better understand ability. For structuring complex
queries, standard SQL only allows the definition of SQL views. However, SQL views
have no parameters.

– SQL Script supports local variables for intermediate results with implicitly defined
types. With standard SQL, you need to define globally visible views even for
intermediate steps

– SQL Script has control logic such as if/else that is not available in SQL
Performance Gains
Traditional vs HANA Code push down
model
SQL Script – Recap slide

HANA database has its own scripting language named SQL


Script
SQL Script is a collection of EXTENSIONS to Structured Query
Language (SQL).

It is used to push down data intensive logic into the database.


HANA Stored Procedures
Setting up HANA Dev Perspective
Logic Containers

In SQL Script there are two different logic containers, Procedure and User-Defined

Function. The User-Defined Function container is separated into Scalar User-Defined

Function and Table User-Defined Function.


SQL Script - Extensions
Logic Containers– Creating a
Procedure
A Procedures allows you to describe a sequence of data transformations on data passed as
input and database tables.

• A procedure is a unit/module that perform a specific task. This procedure can be combined
to form larger programs. This basically forms the 'Modular Design'. A procedure can be
invoked by another procedure which is called the calling program.
• Procedures are re-useable processing block with a specific sequence of data
transformation. The procedure can have multi-input/output parameters. The procedure can
be created as read-only or read-write.
• An SQL Procedure can be created at –
1. At Schema Level(Catalog Node)
2. At Package Level(Content Node)
SQL Scripts – Schema
A database schema is a way to logically group objects such as tables, views, stored procedures
etc. Think of a schema as a container of objects. 

There are 3 types of schemas:


• User Defined Schema – defined by the DBA
• System Defined Schema - These schemas are delivered with the SAP
HANA database and contains HANA system information. There are
system schemas like _SYS_BIC, _SYS_BI, _SYS_REPO, _SYS_STATISTICS
etc.
• SLT Derived Schema – SLT Driven schema when migrated
For now lets use our user
default schema….
Creating a Procedure using Select..

SELECT Column, Column, COUNT(*)


The SELECT row should contain FROM Table
the columns (fields) that you WHERE Condition
want to see in the result table.
GROUP BY Column, Column
The FROM conditions determine HAVING GROUP_Condition
the table from which the data ORDER BY Column ASC, Column DESC;
comes.
Creating a Procedure
Syntax:
CREATE PROCEDURE {schema.}name 
            {({IN|OUT|INOUT} 
                        param_name data_type {,...})} 
            {LANGUAGE <LANG>} {SQL SECURITY <MODE>} 
            {READS SQL DATA {WITH RESULT VIEW <view_name>}} AS 
BEGIN 
... 
END 

• In – Input parameters to the procedure


• OUT – Output parameters to the procedure
• INOUT – Changing parameters
• READS SQL DATA defines a procedure as read-only.
• Implementation LANGUAGE can be specified. Default is SQL Script. 
• WITH RESULT VIEW is used to create a column view for the output parameter of type table
Creating a Procedure - Example
CREATE PROCEDURE SCHEMA_NAME."PROCEDURE_SALES_REPORT"(
            IN DISCOUNT INTEGER,
            OUT OUTPUT_TABLE SCHEMA_NAME."TT_SALES" )
LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS
/*********BEGIN PROCEDURE SCRIPT ************/
BEGIN

• In – Input parameters to the procedure


• OUT – Output parameters to the procedure
• INOUT – Changing parameters
• READS SQL DATA defines a procedure as read-only.
• Implementation LANGUAGE can be specified. Default is SQLScript. 
• WITH RESULT VIEW is used to create a column view for the output parameter of type table
Data Type Extensions
Besides the built-in scalar SQL datatypes, SQL Script allows you to
use user-defined types for tabular values

The SQL Script type system is based on the SQL-92 type


Table Types (Creation and Drop)
A table type is :
• Similar to a database table but do not have an instance
• Used to define parameters for a procedure that represent tabular results.

In HANA, with the help of SQL Script, we can create a Table Type. These are used to get
back table outputs from a SQL Script. 

Syntax:
CREATE TYPE [schema.]name AS TABLE 
          (name1 type1 [, name2 type2,...]) 

DROP TYPE [schema.]name [CASCADE] CREATE TYPE SCHEMA_NAME.TT_SALES AS TABLE



           SALES_AMOUNT DECIMAL,
           NET_AMOUNT DECIMAL,
           PRODUCT_NAME NVARCHAR(20),
           REGION_NAME NVARCHAR(20),
           SUB_REGION_NAME NVARCHAR(20)
);
Table Types
Replace SCHEMA_NAME with your schema. 

Create Table Type

CREATE TYPE SCHEMA_NAME.TT_SALES AS TABLE



            SALES_AMOUNT DECIMAL,
            NET_AMOUNT DECIMAL,
            PRODUCT_NAME NVARCHAR(20),
            REGION_NAME NVARCHAR(20),
            SUB_REGION_NAME NVARCHAR(20)
);

Remove Table Type

Drop Type SCHEMA_NAME.TT_SALES AS TABLE;


Table Types – Example
After executing the statement you can go to the schema and find the table type under
Procedures 

Remember we cannot add record to table type. If you try to insert record, you will get
an error. (See error below in RED)

INSERT INTO SCHEMA_NAME.TT_SALES VALUES (100, 'PROD-1', 'ASIA', 'INDIA');


Create a Procedure
CREATE PROCEDURE get_bp_addresses_by_role_sql ( in partnerrole nvarchar(3),
out bp_addresses tt_bp_addresses)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER -- INVOKER OR DEFINER
DEFAULT SCHEMA JADHAVH
READS SQL DATA AS -- READ ONLY PROCEDURE
BEGIN
/*****************************
Write your procedure logic
Field names are case sensitive
*****************************/
bp_addresses =
select a."BP_ID", a."BP_ROLE", a."EMAIL_ADDRESS", a."COMPANY_NAME",
a."ADDRESS_GUID",
b."CITY", b."POSTAL_CODE", b."STREET"
from "SAPDB1"."SNWD_BPA" AS a INNER JOIN "SAPDB1"."SNWD_AD" AS b
on a.ADDRESS_GUID = b."NODE_KEY"
where a."BP_ROLE" = :partnerrole;
END;
Execute the Procedure

call "_SYS_BIC"."HJ_XS_Project.00.models/get_bp_addresses_by_role_sql"(partnerrole =>


'01', bp_addresses => ? );
SQL Script Procedure - Expressions
SQL Expressions is a clause that can be used for return values. There are 4 types of SQL 

Expressions-

• Case Expressions – In this expression the user can use IF – THEN – ELSE logic without

write procedure.

• Function Expressions – SQL built-in-functions can be used as Expressions.

• Aggregate Expressions – In This Expression aggregate functions is used to calculate a

single value from the values of multiple rows for a column.

• Subqueries in Expression – A subquery is a select statement enclosed in parentheses


Examples : Table Type as an export
• How to use table type inside procedure to send output data.

• In this example we are going to use 2 tables PRODUCTS and SALES. The procedure will join
these 2 tables to get PRODUCT_NAME and SALES_AMOUNT. The output will be sent in output
using a table type.

• Example : SALES_REPORT_TT
Examples : Use Local Scalar Variable

• Local variables are declared using DECLARE keyword and they can optionally be initialized
with their declaration. By default scalar variables are initialized with NULL.

• A scalar variable var can be referenced the same way as described above using :var or


without the :
Assignment (in contrast to binding table variables) is possible multiple times overwriting the
previous value stored in the scalar variable. Assignment is performed using the operator
“=”(SAP recommendation although := is avlb)

• Eg. In this example we are going to use 2 tables PRODUCTS and SALES. The procedure will
join these 2 tables to get PRODUCT_NAME and SALES_AMOUNT. The output will be sent in
output using a table type.
Examples : Variable Scope Nesting in
Procedure
• SQLScript supports local variable declaration in a nested block. Local variables are only
visible in the scope of the block in which they are defined. It is also possible to define local
variables inside LOOP / WHILE /FOR / IF-ELSE control structures.

• Eg. From this result you can see that the inner most nested block value of 3 has not been
passed to the val variable.
Examples : IF-ELSE Logic in Procedure
• 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.

• Eg. In this example we will pass product id, product name and category as input. If the
product already exist, we will update the record. If it does not exist, we will create a new
record. 
Examples : For Loop in Procedure
• The For loop iterates a range of numeric values.
BREAK:
Specifies that a loop should stop being processed.
CONTINUE:
Specifies that a loop should stop processing the current iteration, and should immediately
start processing the next.

• Eg. In this example we will define a loop sequence. If the loop value :x is less than 3 the
iterations will be skipped. If :x is 5 then the loop will terminate.
Examples : Use of Array in Procedure
• The For loop iterates a range of numeric values.
BREAK:
Specifies that a loop should stop being processed.
CONTINUE:
Specifies that a loop should stop processing the current iteration, and should immediately
start processing the next.

• Eg. In this example we will define a loop sequence. If the loop value :x is less than 3 the
iterations will be skipped. If :x is 5 then the loop will terminate.
Code Sample - Parallelization
BEGIN
-- Query 1
product_ids = select "ProductId", "Category", "DescId"
from
"SAP_HANA_EPM_DEMO"."sap.hana.democontent.epm.data::products"
where "Category" = 'Notebooks'
or "Category" = 'PC';
-- Query 2
product_texts = select "ProductId", "Category", "DescId", "Text"
from :product_ids as prod_ids
inner join
"SAP_HANA_EPM_DEMO"."sap.hana.democontent.epm.data::texts"
as texts on prod_ids."DescId" = texts."TextId";

-- Query 3
out_notebook_count = select count(*) as cnt from
:product_texts where "Category" = 'Notebooks';
-- Query 4
out_pc_count = select count(*) as cnt from
:product_texts where "Category" = 'PC';
AMDP – ABAP managed Database
Procedures
• AMDP is a class based approach for managing and calling HANA procedures from ABAP. This

class is called a AMDP class. All classes inheriting from the standard interface

IF_AMDP_MARKER_HDB gets classified as a AMDP class.

• A global class is marked with a specific interface to enable the class to contain the HANA

procedure code

• The CTS transport moves just the Class to the subsequent environments and the HANA

Artefact which is the procedure will automatically get created when the class gets activated

in the respective environment


Restrictions in AMDP
ABAP for HANA - AMDP

• Calling a AMDP? – a Static method call

• How does the AMDP run in HANA? – Lazy loading, created on runtime. JIT pattern

• How to create a AMDP? - ADT for Eclipse, not editable in ABAP Workbench, compile time

validations only avlb for SQL Script for HANA currently


Cannot edit in ABAP Workbench

S-ar putea să vă placă și