ABAP On HANA

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 114

ABAP on HANA & S/4 HANA Training by Anubhav

http://www.onlinefioritranings.com
[email protected]

SAPGUI

OData

Application Layer – NW
Application Layer - NW NW7.4 SP02, SP05
NW7.5
CDS
ADBC
AMDP
DB inf.

Database - RDMS Database – SAP HANA


In-memory
Info. Modelling SQL Scripting
Will i get lifetime access of videos?

If i start teaching you VB, how many of you will join my course?
Outdated content <NOONE>

In 8 months if you cannot learn, you cannot learn.


6 mon.

Fiori 2.0
XML, Comp, Rou, RMH, ALP,

[email protected]
Database – used to store all the data. ERP – Software and hardware combination to manage your business end to end.
Wallmart – Over years lots of data will be created inside of server. Sometimes there is a need to analyze this massive data to
take informed future decision.

I want to know how many laptops were sold in the month of Christmas. Mumbai
How many smart phones i sold on thanks giving day.
Which company smart phones selling the most – Samsung, iPhone, Windows,.... ETL (Extraction,
Transformation and
Loading)
Miami Santa Clara

Report in
ABAP
NYC California

Result
SQL
replication BW
Database (OLTP) (OLAP)
MARA
35 year
RDBMS
CPU RAM
Relational DB
Registers
Management System

8084 IC
8 bit Database
16 Address Bus
HDD
2~16 Max size of memory
Mechanical
MOV A,B
IO processing
ADD A

Bottlenecks –
Storing data in HDD, Mechanical device needs IO processing.
CPU has limited power to process data
Cost of RAM was high
1010 00 01 SHIP1 SOLD1 MAT1 10 500 EA MAT2 20 600 EA

MAT1 10 500 EA
1010 00 01 SHIP1 SOLD1 MAT2 20 600 EA

101000 01 SHIP2 SOLD1


Secondary Secondary
Index Index

Secondary Secondary
Index Index

Row Data
1001 SHIP1 600 USD 1002 SHIP2 800 USD 1003 SHIP1 900 USD
Calculate total amount of sales?
100110021003 SHIP1SHIP2 600800900 USD
Column Store

SHIP1
1001 600
(1,3) USD
1002 800
SHIP2 (1,2,3)
1003 900
(2,3)

Total of sales? Core1 Core2 Core3


Aggregations can be created faster (SUM, AVG, MAX, MIN)
Amount of data which is unique is stored only once.
Both OLTP and OLAP can be done with a single system – Real Time, No replication require, no additional cost

Column store, Much read optimized but not write optimised

Insert only approach – SAP never deletes data, always insert data with new timestamp.

Select MATNR, MAKTL, MKART from dbTab;


MARA
SAP HANA – High Performance Analytical Appliance
Application – Combination of HW and SW
Core Core
HW Advancements:

 Reduction in memory price (keep in RAM) – HDD is only for Backup


 Multi Core CPU – Massive parallel processing Core Core
 64 bit OS
 In-memory

Software Advancement Core


Core
 Use column store – in compressed format in RAM
 Aggregates can be built at runtime – Real-time data = OLAP+OLTP
SAP known as Hybrid Database
 Insert only approach (P*time) Core Core
 Compression
 No need for extra indexes

Core Core

Core Core
Row Store Column Store
When you see unique values are continuously repeating. This
When majority of values are unique. Config, Org
gives chance to compress data better.
Usually All Org data and Config data
Usually All SAP Master and Transaction tables we use column
store.
No aggregation org, config, Customizing data.
Aggregations are required on massive data.
All records all time (Select * )

Guidelines to choose Row is store is less restrictive


Select selective columns from table, best performance.
SAP BW on HANA
Side Car
Presentation BW powered by HANA

Analytics Tools SAP BW (7.31)


Application

Database HANA HANA


Oracle Data provisioning
ETL – SLT,BODS, DXC

ABAP on HANA

SAP NW 7.4 HANA (SP06)


Flow of an ABAP Workflow
BOPF Presentation
•Initialization BRF
•Select data from DB Customizing
•Loop at item into wa. Smartforms
--manipulation SAP Script
•Endloop. BAPI, RFC
•Write back data Application Layer (Netweaver - ABAP)
•Save- Commit
•End print result
Processing
logic Result
Code-to-data
Code push-down
Fi
ni
sh
Everythin ed
g you to
process
Processin
DB g
SAP HANA DB (Max. Power)
What about system access?

1. Buy a server access from a vendor (2500 INR per month per user)
S/4HANA OP 1610 – SAP 7.52
> SAP ABAP system access from Local computer SAPGUI + ADT on Eclipse (CDS, AMDP, ADBC)
> Access to Odata and Fiori Launchpad from local computers
> S/4HANA VDM concepts can also be covered
> Unlimited access (no per hour charges)
> Remote server access to check SAP HANA DB + HANA Studio (Local access to HANA not possible)

2. Setup your own server using http://www.aws.amazon.com using SAP CAL


> This will cost 60 INR per hours (40 Hours a month = 40 * 60 = 2400 INR) = 9600 INR
> SAP ABAP NW 7.5 SAP HANA 1.0SP10 Developer
> Everything for local computer including SAP HANA DB from HANA Studio or eclipse
> No S/4 HANA Concepts – VDM, Analytical Fiori App on WebIDE
> Effort to configure SAP CC to connect using local WebIDE to the Amazon account
HANA Architecture
HANA Evolution – Release 1.0 – 2.0SP2
How to setup your development tool (ADT for eclipse)
How to connect to your server from local Eclipse (Local + AWS)

ABAP on HANA Code


New ABAP syntax
What is new in ABAP
What it means to migrate to SAP HANA
CI checks
SWLT
ADT in details

Real time OIA scenario


EPM
Code in ABAP as Bad ABAP programmer
Where to improve performance
New SQL syntax

SAP HANA
IM – Attr, Ana, Cal (2)
SQL Scripting
JSP – Java Server pages

Whenever we have a java program, we need to first compile java program.

.java (500) .class (executable)

01012018 02012018
5AM 11AM

.java (1)

02012018
10AM

browser
HANA Colgate
IBM

SAP
TCS HANA NASA
Product Company

Infy
HANA HANA Wallmart

Notes - patch
Note to fix the bug.

After 3 months – collects all those notes and


release a support pack + minor new features
FPS

Release – Collection of SP + Major features.

Evolution of SAP HANA


ABAP on HANA SAP Mobility Fiori Developer, UX Designer,
-Keep the important thing up and running -Apps which are native compatible to Fiori Consultant
-Consume SAP HANA IM in ABAP Devices. Camera, barcode, offline access -Create Fiori App from scratch using JS
iOS integration with fiori, SMP, IoT -Integrate the fiori app with FLP
-Create new dimension apps
-Improvement of performance -Fiori Security, Theme designer
-Design the UX
-Where to improve? Smartfilter OVP
UI
-What is impact of migration?
- leverage on existing asset.
- OData Service odata
HANA Modellers
Define the relationship Native HANA Developers
App - End to end UI5 apps on top of SAP HANA
between tables to extract - XS Classic and XSA
the data business needs - Java, XSJS, Node JS

BW, Analytics
Old Database Data provisioning HANA BOBJ, Crystal,
Excel

HANA DB Consultants HANA DB Administrator BW Developers


-Migration - Health of DB, User creation -BW reporting
-ETL - Authorization -Reporting tools (OLAP)
-Tools like BODS, SLT, DXC, Flat - Backup and recovery, monitoring
ABAP BW SoH UI5

SAP HANA Platform


Application Server (XS Engine – eXtended Application services) + Web server

XS Advance
SAP HANA Repository
XS Classic
Java, Node.js, HTML5

Index Server – Database related functions

Name Server – in case of distributed system architecture, it routes the requests to different server by balancing load

Script server – Manages AFL Application function library – R language


PAL EML APL

Doc Store sever


Integration LM Tools Tooling and provisioning support
Client Side tool (Eclipse, HANA Studio), Analytical Tools, Browser,
BOBJ, Migration tools, Application (BW, ABAP)

Authenticati Session pool


Connection and session manager
on Manager

Request processing and execution


control
SQL Store OLAP
MDX Planning Calculation
Processor procedure Engine Engine
Engine Engine
DML engine (analytical)

Row Store In-memory Store Column Store

Persistence layer
Page management Logger
Max DB
Evolution of SAP HANA
Release 1.0 SPS0 – beta Release
SPS01 – GA (General Availability)
SPS02 – You can use SAP HANA as Secondary DB (Side car scenario) – BODS, SLT
SPS03 – To be able to connect to SAP BW directly, BW 7.31 – BW powered by HANA – Project Orange
SPS04 – Flat file data provisioning
SPS05 – DXC – Direct eXtractor connection, SAP HANA XS (Native Application develop), PAL (R Logic)
SPS06 – If you are on SAP NW 7.4 or above you can now run SAP HANA as primary database on top of ABAP
CRM, Suite on HANA, Introduced web base tooling (lm)
SPS07 – Smart Data Access, AMDP, AFL, Job scheduling
SPS08 – Only HANA DB can be installed on SUSE linux, We can now install SAP HANA on RedHat linux
SPS09 – Multitenant database containers (MDC), WebIDE tools (calculation views), new DB interface, API – zip, virus scan,
SMTP
SPS10 – Hight availability and disaster recovery options
SPS11 – XSA (Java, node.js, HTML5), ML
SPS12 – Workload analysis, Zero downtime

Release 2.0
SP0 – Backup encryption, 3rd party tool support MDC, Recover from snapshot
SPS01 – Doc Store, dynamic cache
SPS02 – Integrate google’s tensser flow ML library
download 2500 INR per month per user
9000 INR – 2-3 hours a day
SAP GUI screenshot

Fiori Development SF4 ABAP


SAP WebIDE Personal Edition Application

SAP Fiori Launchpad host


Browser

One Single Access point


ABAP + HANA
ADT for Eclipse HANA

HANA Studio or Eclipse mstsc


Eclipse: just a development environment. It is just like SE38 or SE80.
Rich IDE which is used by developers across the world for wide verity of developments Java, Android, iOS, ABAP, WebSite etc.
It free and open source.
There are multiple versions of eclipse, Juno, Kepler, Mars, Neon, Oxygen
Toolkit which when installed in Eclipse, we can start developing ABAP applications. – ADT on eclipse
SAP HANA arrive, they were also in need for a tool to connect to HANA system. Downloaded Eclipse source code and changed
it completely to be able to support HANA development. - HANA Studio (modified version of eclipse built by SAP).
SAP started developing only toolkits to connect to ABAP, HANA etc.

Step 1: go to https://tools.hana.ondemand.com/
Step 2: Download eclipse from ABAP section by choosing Eclipse Oxygen based on OS type
Step 3: After download extract to your system e.g. D:\Eclipse
Step 4: Run Eclipse.exe
Step 5: Eclipse will ask you workspace – it is a folder in your local computer where eclipse will store file. E.g. D:\anubhav
Note: Make sure your SAP GUI is already installed.
Step 6: Help -> Install new software...
Step 7: Enter url http://tools.hana.ondemand.com/oxygen and hit Enter key
Step 8: Choose ADT and HANA tools, complete the installation – Eclipse will restart
Now you can click on open perspective button, and will be able to see ABAP perspective.
Benefits:
 You can work with multiple systems like Dev, Q, Prod
 It seamlessly integrated with SAPGUI, whenever there is no support from ADT, a SAPGUI window will open
 Multiple systems, multiple landscapes, Different system (Java, UI5, HANA, Native, ABAP)
 No context switching hence increased developer efficiency
 Flexible and customizable
 Fast search and navigation capabilities
 Supports extensibility - objects like CDS, AMDP, Proxy can only be created by ADT, Only tool for ABAP on HANA
 Supports debug and Transport capability
 ATC (ABAP test cockpit)
 ABAP Profiler
 Supports UI development in parallel to Backend development
 Inbuilt quick fix capabilities
 Modularize code
 Code template

ABAP Project: just a channel to connect to your ABAP system.


Ctrl + Shift + A – to search any object in entire ABAP system
Ctrl + F2 = Syntax Check
Ctrl + F3 = activate object
Ctrl + 6 =open SAPGUI Window
Ctrl + O = quick outline view (helps you to look at structure of your code)
Ctrl + T = open ABAP type hierarchy
Ctrl + Shift + G = open where used list

1. An interface – It is known to be pure abstract class. We only have method definition inside interface, never the
implantation.
2. Abstract class = We cannot create an instance of abstract class. A class which has at least one abstract method.
3. Concrete class = which implements all the methods, the actual functionality.

Fly, load Interface


Template “Design Pattern”

Abstract Abstract
Fly

Cargo Passenger Concrete Class


Load Load
IF_PLANE
Load, fly

ABAP Report
AC_PLANE
FLY
Load*

CL_PLANE_PASS CL_PLANE_CARGO
Load Load
NW 7.4

1. Inline data declaration, We can declare our Data object inline of code itself.

Data: itab type table of <type>


Select * from <table> into table itab.

select * from <table> into data(itab).


Loop itab into data(wa).

2. It is possible to separate the columns in select statement with comma.

Select col1, col2, col3 into corresponding fields of table itab.

With comma separated column list it is mandatory to use host variable @ symbol.

3. Creating object of class – using new keyword

Data(lo_obj) = new className( Constructor variable ).

( ) – parenthesis
{ } – Curly braces
[ ] - bracket
4. Table expression

Read table itab into wa with key col = val.


Itab[ col = key ]-column.

5. String Expression

Concatenate lv_str1 lv_str2 ‘Hard code values’ into lv_final.

Pipe operator to concatenate strings and variables

Lv_str = | Hello all ABAPers this is session from { lv_var } by { lv_by } on { sy-datum } |.
Use Case: Create a program where input is a string (can include numbers, chars, special char), traverse through each char
and print them separately.

Since we cannot tell the char. Data type we need to define dynamic reference and loop over it and print the data.

Memory
WA Anubhav
Anubhav

pointer

https://help.sap.com/viewer/f1cccec432514a3181f2852f2b91d306/7.4.15/en-US/c84cb8db0b3b43908ae4e987f3a3ade5.html
Is my custom code still valid?
Mostly.

What kind of performance improvement i


AS ABAP foresee automatically?
Custom Code Where to put effort to improve
performace?
What can i do to improve performance?

Oracle HANA
When we migrate to SAP HANA what is valid, whats not?
OrderId Amount
Every single statement which you wrote in Open SQL and Core ABAP will be valid. 1 100
Open SQL and Native SQL
2 600
1. Native SQL statements may not work where you were directly calling DB. 3 200
EXEC SQL. 4 300
Select ROWNUM, ORDID from SAPABAP.VBAK
5 60
OPEN CURSOR C1 FOR SELECT FROM DB TABLE.....
ENDSQL.
2. DB specific hints for performance improvement – Not a show stopper
‘%_HINTS MSSQLNT ‘&prefer_join0&’’
3. Selecting data from db table without order by and then using columns for binary search
select from tab order by amount Amount
loop at itab into wa where amount < 200 binary search. 100
4. Direct access to pool and cluster tables will not work
600
5. DB specific checks for secondary indexes.
200
10000 objects which i developed over years in my company. 300
60
Code inspector – SCI – SAP NW 7.02 SP12

Standard code inspector variant : FUNCTIONAL_DB


Package level
EXEC SQL.
--native SQL
ABAP Program END.
SELECT ...

Open SQL Database


Application Layer
Abstraction
mySql MaxDB HANA
Native SQL

Native SQL
SQL, PL SQL,
SQL Script

Database Layer
before migrating .. first we need to identify the changes using SCII.. and do the changes after
that.. migrate it to HANA .. is my understanding correct..?

Fiori UX

SELECT * , SELECT * ALL ENTRIES Guidelines


implementation was improved
More complex types of Joins are now
possible RIGHT OUTER JOIN
Open SQL syntax has been enhanced
Extended Code Inspector Improved
Performance imp. In tooling performance Reuse New features
tool Components Extension to CDS Views,
Fast Data Access
like ALV, Fuzzy Open SQL AMDP,
Optimized data access to HANA SQLM search ADBC
SWLT

Transparent optimization
Performance improvement guidelines – Talking to database
Discard records which are not required – WHERE
Keep the result set small Nested loops, Exit statements with loop
Use having with group by clause

Nested queries, queries inside loop


Loop with DML
Minimize the number of requests
to DB
Use FOR ALL ENTRIES...
Use array operation
INSERT dbtable FROM TABLE itab.
Minimize the amount of data Select *
transfer Select Single *

Use aggregation function


Overhead your db with Full Text search, fault tolerant search
unnecessary load
Search load
Report Loop At itab into wa
Perform get_record.
Select *
FM Endloop

PERFORMANCE_DB

You ran these Function DB checks and Performance DB Checks, You identified 5000 issues in you custom package. Can
you change everything?

7 days improving performance – 2 users in 1 month are using it.


Runtime Statistics
50 k concurrent request per minute
130k SQL statements
12 bn Select request
140 bn records modified every days

Challenges:

We need some trace to find which programs are used the most, which tables are queried modified the most to be able to
prioritize where to improve. Which program is the highest entry point.

ST05 & SAT – cause overhead on system. Executions of your production become slow.
STAD & ST03 – system level tools used by basis to get aggregated performance results (high-level), it doesn’t tell which query
(Statement) caused it.
ST04 – comprehensive data but cannot tell entry point.

SWLT
1. Which of the business process (transaction/report/bapi) takes the most of the time in production system.
2. What is the SQL profile of my main business process. – At the statement level.
3. Most expensive SQL statement in your production system and which business process is triggering the same.
4. Which process works with most of my production load and process huge number of data records.
5. Most often executed SQL statement.

SAP NW 7.21 onwards – SQLM – SQL Monitor


NW7.4 SP5 = Total Request execution Time.
NW7.4 SP8 = Time series analysis
Administration – SQLM – Activate the trace.
SQLMD

Advantage:
 You can this both for standard and custom packages.
 You can activate the tool in certain server or for all servers.
 You download the results and keep them as a back up for future reference or analysis on a different system.
 Look at the results of the tool from multiple angles.

SWLT – SQL Performance Tuning Worklist

Find Improve Explore


Batch Report
user Asyc.
External
External
Session
External
Session
External
Session
External DB
Session
External
Session Shared
Session swap
Memory
External
Session
Internal
Session Int Ses.
Report Memory SQLM

FM query
User: Get the employee of team A and get all Sales orders of that team.

LOOP AT ITAB team Where teamname = ‘A’. User Ids


select * from orders where emp = empId.
ENDLOOP.

Delete entry from itab where team <> ‘A’. X - A


If itab is not initial. Y -A
Select order from Orders FOR ALL ENTRIES in itab where User = itab-User. Z -A
endif. K–B
L–B
S-B

Sales order (20 Bn Orders)


Ordid User
X
X
Y
Y
Pre Pre Pre

NW 7.3

Code Inspector 2000

Dev Q Prod.

SWLT 20 SQLM

HANA DB

HANA DB HANA DB
OpenSQL
DB6

Usage
EPM Data Model – Enterprises Procurement Model
This includes a model company named as ITeIO – Selling Electronic products on internet. Just like Amazon, eBay.

Sales Order Products


(include line items)
2 laptops
3 Mobiles
Business 10 pen drives
Partners
(Customers) Post goods issue ITeIO Purchase Order
Invoice
Items <= orderitem
Billing &
Shipping
Supplier
(Post goods
receipt)

Stock
EPM Data model – Training data model – should not be used for productive purpose
NW 7.4> these tables are there in your company system.

All the tables starts from SNWD*

SNWD_PD – Product Table


SNWD_TEXT – Product Descriptions (Text Table) – language specific description of data – Same PK+SPRAS
SNWD_SO – Sales orders
SNWD_SO_I – Line items of sales orders
SNWD_INV_HEAD – invoice header
SNWD_INV_ITEMS – invoice items
SNWD_BPA – Business partner table (Customers and Supplier, BP_ROLE = 01 – customer, 02-Supplier)
SNWD_ADDRESS

May so happen that data inside these tables are not there:
New Open SQL Enhancements in NW 7.4

Types of SQL statements in DB:

DDL – Data Definition Language – Create,change,delete new DB objects like tables, str, View etc.
Example: CREATE, ALTER, DROP, TRUNCATE
DML – Data Manipulation Language – INSERT, DELETE, UPDATE, UPSERT – Data Manipulation
DQL – Data Query Language - SELECT
DCL – Data Control Language – GRANT, REVOKE
TCL – Transaction Control Language – Commit, Rollback

Fresher interview Q
What is transaction?
It is a DML statement(s) given to database between stable state of database. A transaction ends with TCL.
Come to me with Certification. (85-98%)

Transaction has ACID.


Atomicity – Success or Failed.
Consistency – Leave database in consistent state.
Isolation – every transaction is unique and independent of previous one.
Durability – Accomodable .
SELECT col1, col2, col3 FROM dbtab INTO TABLE itab WHERE condition.
MIN, MAX, AVG, COUNT. GROUP BY, HAVING

NW 7.4 New Features in SQL:

1. Use String literals with Select query.


2. Arithmetic expression with Select
3. New functions which can be used with select queries like FLOOR, COALEASE, CEIL, ABS...
4. Case Expression
1. Simple
2. Search Case
5. Now we can use HAVING clause with aggregated columns.
6. Earlier in the join condition only ‘=‘ operator was supported, now we also can use < and > operators in ON condition.
7. Earlier only 9 tables can participate in Join, this has been increased to 50.
8. Number of sub queries earlier was 9 and now 50.
9. CLIENT SPECIFIED syntax in SELECT queries, now you can use new keyword called USING CLIENT ‘client’
10. It is possible to use RIGHT OUTER JOIN

Exercise: write a report program to print sales orders of a given range of Business partner id. (Technical GUID)
Snwd_bpa-bp_id

Output list should be


Sales Id LineItemPos ProductName GrossAmount Currency CompanyName
Exercise: (nested case)
Write a report when you list all the products from snwd_pd table. Print the product id, category, price and discounted price.

How discounted price is calculated

Category Price Discount


Software < 5000 2%
>= 5000 5%
Notebooks <1800 3%
>= 1800 9%
Other < 500 2%
500 3%
Job Profile: Account Receivable Accountant
Employee Name: Mr. Jems (who is working in company since last 14 year)

Cash plays very important role in a company’s running business. It is in the best interest of a company to collect outstanding
payments (receivables) from the customers as quickly as possible. By quickly turning the sales into the cash, a company has to
put its cash back again ideally in the business or re-invest to increase sales.

Mr. Jems is an A/c Receivable accountant in this company, who’s main job role is to manage the cash. Typically, search, display
Invoices that are overdue and also exceeded a pre-defined and customizable threshold in terms of Days or Amount. Also
classify the customers based on the risk of non-payment.

Dunning: Sending the reminder to customers who exceeded a threshold.

His department also has Barbra she also works with top notch customers but she has different criteria to classify customers.

If the problem is complex, what you do to solve?


Golden Rule: Break it down in pieces.

Tcode in your NW : SEPM_DG


Tech Specification for Mr. Jems

1. Check how long on average the invoices has been outstanding from customers (customer wise report) – Takt 1
Step 1: get the all the open invoices (unpaid inv) from invoice header table. Table SNWD_SO_INV_HEAD, column
PAYMENT_STATUS = ‘’
Step 2: Loop at each open invoice, calculate the total number of days since when invoice is open ( TODAY -
CREATED_DATE ), also count the number of invoices per customer. Calculate Average.

2. Check the gross amount of open invoices in a “common currency” – Takt 2 and Takt 3
Step 1: Get the items for each ( invoice which are open ) and items which are shipped get it per customer.
inv item = SNWD_SO_INV_ITEM – all items which are shipped
inv header – SNWD_SO_INV_HEAD – unpaid, customer
BP table – SNWD_BPA – company name
Step 2: Loop at each item and does a currency conversion of gross amount to a common currency lets say EUR.
Step 3: Calculate the total of gross amount to converted amount to a common currency.

3. Classify the customers regarding their ability to pay their bills (based on threshold value which they want) – Takt 4
Design a customizing table and replace hard coding with values of threshold based on user (jems or barbra....)
4. Perform a dunning for data – Takt 5

Formula for Average?


Sum / count
10 20 30 = (10 + 20 +30 ) / 3
BPID Date
1 01.01.2017
1 01.03.2017
1 01.04.2017
2 01.02.2017
2 01.03.2017

1 368+338+308 1+1+1
Amazon

invoice

2000

US IN

Colgate

DE
4 types of people:
Sleepers: Least bother about anything, old ways, old things.
Snoozers: I have, i will i want , i should change but now,
Slamers: Took right path, leave it.
Active passionate: Walkers –

Schema in a DB?
Is a mandatory database object. Used to organize and control the authorizations of Database objects inside of a DB system.
Database object like Table, Structures, Types, Views, Procedure, Sequences, Triggers resides inside of Schema. Usually
Schema inside SAP HANA has 1:1 relationship with ABAP / non-ABAP systems.

SAP NW 7.4
Customizing

user
SAPABAP1
MARA
Old DB
Customizing Data Provisioning
MARA SAP HANA
SAPECC
MARA
Folder structure in HANA DB
Catalog : Collection of All schemas. Home of mandatory database object called “Schema”.
Provisioning : is used by DB migration experts during provisioning process.
Content: Collection of packages inside of HANA, each package includes the object, We can transport from D-Q-P objects of SAP
HANA only and only when they are part of a package.
Security: Used by Admin to control authorizations for users.

When you do productive ABAP development, where do you store your FG, FM, Rep?
Package.
Organize the application artifacts in a package.
Group of packages becomes and Application Component.
Transport layer.

In SAP HANA, When we do DB development e.g. Information models, views, procedures, functions must be part of a package.

Content stores the design time information of object (definition), When is the object is activated, it is persisted inside of
schema.

I am slow learner.....Once i learn i never forget.


Write everything in my notebooks.
Information/Data modelling in SAP HANA?

The data in an enterprise is stored in multiple database tables. We need to fire complex queries (joins, selections, conditions,
sub queries) to pull the data from db.

Challenges:
 Complex for business users to write such queries.
 End up writing a query which is performance disaster.
 Queries also has limitations as they do aggregations and use ready to use functions but they cannot perform
transformations like currency conversion.

Information models: Main purpose of IM is to hide the technicalities of SELECT queries and make it easier for functional
consultants with little technical knowhow to produce desired data and out comes.

Table Table
Table Model SQL Statements
Table
It can be used to convert linear structure to a multi-dimensional structure w/o technical knowledge of SQL.
Data can be fetched in business understandable format.
 The model execution happens with the DB layer, it can leverage the power of SAP HANA.
 As a result it reduces the amount of Data transfer to application layer, Only final result is sent to DB.
 Complex transformations like curr. Conversion can be also done within the DB.
Information Models

Calculation View\ Decision Table


Attribute View Analytical View
CV DT_

Master Data Transaction combined with More complex cases Planning scenarios
Join Master UNION, INTER
AT_ Calculate aggregates
Join Fact – dimension
AN_ Graphical Scripted

SQL Optimizer

Join Engine
Calculation Engine
OLAP Engine
Types of Data in an SAP system?

 Org Data- CCA, CO, SO, SLA, PO, PLT – doesn’t even change. (Configuration for Applications)
 Master Data- Doesn’t change so often, used to create transaction data. E.g. Material, Leg. A/c, BP, Product.
 Transaction Data- tend to change/created frequently. E.g. Sales orders, invoices, Billing, Porders.

 Configuration Data – For the Basis


Company
Asset of company is like Products, Employees, Partners.
All these assets are dimensions. All the company’s master data is considered
as dimension.
What are all the KPI (Key Performance Indicator)
Employee – Salary, Bonus, No of Hours
Company – Profit, Sales, Revenue , Loss
Payroll – Tax, Hours spend, Expenses, Paystub
CRM - Complaints, SR, Productivity

All the KPIs Should be measurable and they are numbers (numeric) and so called MEASURE.
Measures are stored in Fact Tables.(Transaction data)
SOID Amount Currency PID NAME CATEGORY
1 1000 EUR 100 Lenovo 550 Laptop
2 2000 EUR 200 Lenovo 450 Laptop
3 4500 USD 300 Canon D500 DSLR
4 8200 INR 400 Canon 1200 DLSLR
5 1960 INR 500 RAM FINc. 1 TB RAM

Sales Data – Fact Product - Dimension

Empid NAME City


Calculate Revenue: Total.
Future planning: 950 Anubhav Mumbai
How many products in a category sold the most 980 Shikha Delhi
Which is highest selling laptop
Which is most promising employee
Sales Rep. - Dimension
Product Sales Rep.

Sales

Time Customer
Attribute Views:
Semantics
Attribute output of dimension has to have
Orders Invoices
one mandatory key.

01
Data Foundation 02
03

8 TYPES OF JOINS IN HANA:


Referential join – its smart inner join. The selection of data in table/view determine the behaviour of the join.
Inner Join – join which evaluates, data from both tables with matching criteria.
Text Join – used for join between text table and master table.
Left Outer Join – perform an inner join + also gets the records of left table corresponding to which right table doesnt have
record.
Right Outer Join - just like outer join, but if table position is on right.
Temporal Join – used to join tables with time data.
Spatial Join – used for geo spatial analysis.
Star join – Join between two star schema.
OrderID Date Partner Date
1 01012019 FedEx 0101.2019
2 01022019 DHFL 01022019
3 01032019 FirstFlight 01042019
4 01032019
5 01042019

Referential join
ABAP:

SELECT ORDERID FROM View;


Inner Join: 1 2 5 (always evaluated)
Referential join 1 2 3 4 5
If there is a referential join and select query doesn’t select data from another table, The join will be “pruned”

SELECT ORDERID, PARTNER FROM VIEW;


Referential join:
1 Fedex 2 DHFL 3 FirstFlight
Inner join:
1 Fedex 2 DHFL 3 FirstFlight
Analytical View:
Mandatory to mark one of the property as Measure.
Used for purpose of analytics and joins the fact with Dimension.

All Orders

View

Order -> Shipping


Analytical Views: Are best in calculating aggregates, they can be used to also do calculation @ DB level e.g. Currency
conversion. Mainly used in cases where we join Fact table with Dimensions.

Use Case: You have been asked to calculate which product in company has highest volume of sales.

HANA 2.0 – Attribute views and Analytical views are getting deprecated.

I am the CEO of ITeIO, I as a leader often listen many complaints from customers asking timely delivery and vendor’s asking
payment for products.

Supply and demand.


You have ordered 1 mn Floopy Drives. – I will not be able to sell. My Cash is stuck.
USB, USB banks, DVDs, Blue Ray – High in Demand

Use Case: Design something, which provides the details of each product in main line stream with information about volume of
sales orders v/s purchase order.

Product Sales Order Volume PO Volume


Floopy 12 2000
USB 5000 1500
Blue Ray 9000 600
TEXT SALES_GROSS TEXT PURCH_GROSS
PRD1 100 PRD1 250
PRD2 200 PRD3 600
PRD3 400 PRD5 800
PRD4 600 PRD6 950

TEXT SALES_GROSS PURC_GROSS


PRD1 100
PRD1 100 250 PRD2 200
PRD3 400 600 PRD3 400
PRD4 600
PRD1 250
PRD3 600
PRD5 800
PRD6 950
DEV QTY PRD

ABAP - SAPQTY ABAP - SAPPRD


ABAP - SAPDEV

SAP<SID>
SALQTY SAPPRD
SAPDEV

CV_ANUBHAV CV_ANUBHAV
SAP NW 7.4 and above you can use View proxy concept to consume the HANA IM in ABAP system.
SAP BW 7.31 and above. SAP NW 7.4 SP05 – CDS VIEW
Transport of the object.
transport request = HTC (contain delivery unit ) + view proxy ( Consume IM in ABAP layer )
Application Layer Application Layer

CDS View CDS View


a Transport
c
t
View Proxy View Proxy
HANA Transport
i
SE11 View Container SE11 View
ac
v (HANA Delivery Unit)
tiv
a
at
t
e
e HANA (Database Layer)
HANA (Database Layer)
HANA View

Information Information
package Delivery Unit Model HANA View
Model
Delta field
Cons of View proxy approach:

1. If you transport to the Q system, corresponding HANA view is not available, Your ABAP transport will fail.
2. Delta changes in the IM would kick-out the view proxy object out of sync.

How to consume IM:


1. How to pass parameter values from ABAP to the view input?

select company_name, round(avg(days_diff),0), floor(sum(final_gross))


from "_SYS_BIC"."BATCHAPR/AN_OIA" group by company_name order by company_name
with PARAMETERS ('PLACEHOLDER' = ('$$IM_CURR$$','USD'))

2. What if i am even below SAP NW 7.4, which means i am running SAP HANA as a side car scenario.
ADBC – ABAP DataBase Connectivity
When our ABAP system runs on any DB connected as secondary DB or Primary DB, we can fire DB specific queries directly to
Database (Native SQL query). Since we want to directly talk to DB we need an channel to do so. That is ADBC is.

When to use ADBC?


 When you dont have proxy object concept < SAP NW 7.4
 HANA DB is running on ABAP as a secondary DB (Side Car Scenario)
 IM needs to be called by passing paramater
 Call a HANA procedure directly.
ADBC is an API (Methods and classes)
What is an API (Application Processing Interface)?
It is a class or group of methods of these classes exposed by a framework to consume and build something on top of it.

Competence

Cl_sql_statement – class which can be used to establish connection to db.


Create_statement() – pass the select query which will be executed in HANA db direct.
Set_param_tab() – to tell your internal table where the data will come and sit inside.
Next_package() – shoots the query to DB, fetches the data and assign to your ITAB
Disadvantage of using SAP HANA views?

 Cannot debug the views


 if there is complex requirement, the decomposition of the solution is not possible.
 There is no possibility to write any control flow, orchestration logic inside of a view example IF...ELSE, FOR...
 SQL queries always return one result, chaining of results are not possible or possible to some extent.
 Not possible to handle any imperative logic. (complex looping. Sorting, searching etc.)

SQL Script

SQL script is a collection of extensions to SQL (DML,DDL,DQL,DCL). The purpose is to give procedural capabilities to SQL. It
allows developers to write data intensive logic inside of core DB. This is one of the technique to achieve code-to-data
paradigm.

https://help.sap.com/viewer/p/SAP_HANA_PLATFORM
Types of Statement

Declarative Logic Imperative Logic


Data Flow logic (Pure SQL Orchestration logic (IF,LOOPING,
statement) FOR, WHILE)
Code gets converted to Data Flow Graph There is no parallel processing of such logic
It has a strong chance of getting processed in parallel
--Q1 result
Lt_product = select * from snwd_pd where price > 1000;

--Q2
Lt_sales = select * from snwd_so where product_id in ( select prod_id from :lt_product); Q4

--Q3
Lt_pruchase = select * from snwd_po where product_id in ( select prod_id
from :lt_products);
Q2 Q3
--Q4
Select SUM(gross_amount) from :lt_sales;

What will kick-you-out of parallel mode


 Local variable or scalar parameter is in use, it will come out.(declare) Q1
 Inside a processing block, system finds a DML / DDL.
 Encounters imperative logic (IF, LOOPING, CURSOR)
 SQL statements which are not assigned to implicit variable.

Guideline – In case you cannot avoid any processing logic


Split the code where the logic which can be processed in parallel move-in to the
separate container.
 Put all the imperative logic at the end of container.
Syntax to declare variables in ABAP

Data: variable_name TYPE dt/DDIC/Ct.

Declare variableName datatype;

Funda fox:
 Every statement in SQL script ends with semi-column (;)
 SQL script is not case-sensitive.
 When we use a variable in SQL script, we have to put a colon before that (:). When we you are assigning a value to a
variable we must avoid the column.
delcare x integer;
delcare y integer;
y := :x;
:x = 4; ---wrong
x := 5; ---Correct
 The assignment variable in SQL script is := not just =.

Data types in SQL Script:


Numeric : TINYINT, SMALLINT, INT, BIGINT, SMALL-DECIMAL, DOUBLE, DECIMAL
Char : VARCHAR, NVARCHAR, ALPHANUM
Data: TIMESTAMP, DATETIME
Binary: VARBINARY
Large objects: CLOB, BLOB, NLOB
Data Variables

Scalar Table Type Array


(Implicit, explicit) (Single Column table)

Container – Block of
SQL Script code

UDF – User Defined


Anonymous SQL Block Procedure
Functions

Do begin CREATE PROCEDURE procname( IN p1 type, CREATE FUNCTION functionname( p1 type)


OUT p2 type, INOUT p3 type) DEFAULT SCHEMA “schemaname” AS BEGIN
End; LANGUAGE SQLSCRIPT/R DEFAULT SCHEMA ....
“schemaname” READS SQL DATA AS BEGIN ....
.... END;
....
END;
Funda fox:
 Schema is a mandatory object in DB, Which includes all the runtime definition of Database objects. When you connect to
SQL console, the system defaults the Schema as USERNAME schema. Hence in order to read and work with tables or other DB
objects inside of other schemas (for example SAPABAP1 for ABAP), We must put the schema name before DB table.
 You can default the current session schema using SET SCHEMA statement.

select current_schema from dummy;


SET Schema SAPABAP1;
SELECT * FROM SNWD_so_i;

Create an anonymous block

do begin
declare z integer;
z := 20;
select z from dummy;
end;

do (IN x integer => ?, IN y integer => ?) begin


declare z integer;
z := :x + :y;
select z from dummy;
end;
create procedure totalNum (IN x integer, IN y integer, OUT z
integer)
language sqlscript default schema "ANUBHAV"
reads sql data as begin
z := :x + :y + 30;
end;

call totalnum(10,20,?)

drop procedure totalNum;


Disadvantage of using Anonymous block?

1. Cannot be used for productive purpose.


2. Bad maintenance.
3. Every time system runs, it compiles it.

Stored Procedure: It is anonymous block which is pre-compiled and stored in DB permanently. It can be reused by other
containers. It can also accept IN, OUT, INOUT parameters.

create procedure totalNum (IN x integer, IN y integer, OUT z integer)


language sqlscript default schema "ANUBHAV"
reads sql data as begin
z := :x + :y;
end;

We can use ALTER statement to Change procedure, we are only allowed to change code not parameters.
It is a good practice that we drop procedure and re-create.+

select * from procedures where procedure_name like '%NUM%';


IF condition in SQL Script

IF condition THEN
Else
End if;

create procedure calculateOE (IN x integer, OUT result varchar(10))


language sqlscript default schema "ANUBHAV"
reads sql data as begin

declare res varchar(10);


if( mod(x,2) = 0) then
res := 'Even';
else
res := 'Odd';
end if;

result := :res;

end;

call calculateOE(?,?);
While loop – it is used for conditional looping.

WHILE condition DO
....
END WHILE;
3
3*10 + 2*10 + 1*10 = 60

Funda fox:
When we create a variable in SQL script and do not assign a default value to it, it gets assigned with NULL value.
X = x + NULL;  NULL
create procedure calcFact (IN x integer, OUT result BIGINT)
language sqlscript default schema "ANUBHAV"
reads sql data as begin

declare counter integer;


result = 0;
counter := :x;
while :counter > 0 do
result := :result + (:counter * 10);
counter := :counter - 1;
end while;

end;
Call one procedure in another

alter procedure calcFact (IN x integer, OUT result BIGINT)


language sqlscript default schema "ANUBHAV"
reads sql data as begin

declare counter integer;


result = 0;
counter := :x;
call TOTALNUM(x,1,:counter);
while :counter > 0 do
result := :result + (:counter * 10);
counter := :counter - 1;
end while;

end;

FOR loop
FOR indexVariable startIndex..EndIndex DO

END FOR;
For loop

CREATE procedure pumpEmployee (IN x integer)


language sqlscript default schema "ANUBHAV"
as begin

declare i integer = 0;
create table Emp( empId integer, empName varchar(80), salary integer, primary key(empid));
FOR i in 1..x do
insert into emp values(i, 'Employee ' || i, i * 1000);
end for;

end;

Exercise: In above procedure first time it creates and insert record. Next time i want to just insert record, do not want to
recreate or drop table.
Hint: check if table exist. If not, create table. If yes, just insert record.
In case you are unable to connect to RDP from Windows 10 laptop, please uninstall security path
https://serverfault.com/questions/911590/this-could-be-due-to-credssp-encryption-oracle-remediation-rdp-to-windows-10-
p

Uninstall KB4103727 (no restart required)

Exception: unanticipated/anticipated errors which may arise during execution of your programming code. When such error
occurs, end user will be exposed to dumps and technical information's, which is not really under stable for end users.

TRY.
--code
CATCH.
ENDTRY.

OOPS ABAP- CX_ROOT (super class of all exceptions in ABAP). CX_STATIC_ERROR


SQLEXCEPTION – generic exception class in SQL script
For custom exceptions we need to define an exception code, which has to be a number and that number should be grater
than 10000.
Syntax to handle exception: DECLARE EXIT HANDLER FOR <exceptionClassName>.
Exception handling example with generic exception class

ALTER procedure createInsertEmp (in IN_A INT)


LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "ANUBHAV"
AS
BEGIN
declare x int = 0;
declare i int = 0;
declare y int = 0;
declare z int = 0;

DECLARE EXIT HANDLER FOR SQLEXCEPTION


SELECT 'An internal error occured while creating table in SAP, contact support' from dummy;

create table emptab(EmpID int, EmpName varchar(50), salary double, primary key (EmpID));
FOR z in z..IN_A DO
INSERT into emptab values(z, 'Employee' ||z, z*1000);
END FOR;
END;
Exception handling with exact error code and SQLEXCEPTION

ALTER procedure createInsertEmp (in IN_A INT)


LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "ANUBHAV"
AS
BEGIN
declare x int = 0;
declare i int = 0;
declare y int = 0;
declare z int = 0;

DECLARE EXIT HANDLER FOR SQL_ERROR_CODE 288


SELECT 'An internal error occured while creating table in SAP, contact support' from dummy;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
select 'i dont know, contact dev team' from dummy;

--create table emptab(EmpID int, EmpName varchar(50), salary double, primary key (EmpID));
FOR z in z..IN_A DO
INSERT into emptab values(z, 'Employee' ||z, z*1000);
END FOR;
END;
How to throw exception (RAISE clause in ABAP)
SIGNAL SQL_ERROR_CODE xxxx(>=10000) set message_text = ‘any message’;

alter procedure createEmpRecord (in empid INT, in empname varchar(80), in sal integer)
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "ANUBHAV"
AS
BEGIN

declare exit handler for sql_error_code 10001


select ::sql_error_message, ::sql_error_code from dummy;

if(sal > 1000000) then


signal sql_error_code 10001 set message_text = 'salary cannot exceed 1 mn';
end if;
INSERT into emptab values(empid, empname, sal);

END;
Table type: is a template of a table structure which can hold data (multiple records) @ runtime like internal table.
1. Implicit creation of tables
2. Explicit creation
2.1 Creating on fly
2.2 Creating using TABLE TYPE syntax

Use Case: Get all products from db table where product belongs to Veg Pizza category, get the total of all the sales gross for
those products. SNWD_PD (CATEGORY = Veg Pizza ‘Softwares’), SNWD_SO – (sum(gross_amount) where product into the
previously selected list).
create procedure getOrderGrossByCat (in imCategory VARCHAR(60), out gross bigint)
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN

--implicit table in SQL Script


lt_products = select * from snwd_pd where category = :imCategory;

--pass output of first to now second


select sum(gross_amount) into gross
from snwd_so_i where "PRODUCT_GUID.NODE_KEY" in ( select node_key from :lt_products );

END;
Use Case: Return all the product item information where the product category items are used.

create procedure getOrderItemsByCat (in imCategory VARCHAR(60),


out out_order_items table
(
item_pos nvarchar(3),
size varchar(40),
qty decimal(15,2),
gross decimal(15,2),
currency nvarchar(5)
)
)
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN

--implicit table in SQL Script


lt_products = select * from snwd_pd where category = :imCategory;

--pass output of first to now second


out_order_items = select
so_item_pos as item_pos,
"Size" as Size, "Qty" as Qty, gross_amount as gross,
currency_code as currency
from snwd_so_i where
"PRODUCT_GUID.NODE_KEY" in
( select node_key from :lt_products );

END;
Caution: NEVER create table types and procedures in SAPABAP1 schema, create them in your own schema calling DB tables of
SAPABAP1 schema from EPM model;

Syntax to create table type


CREATE TYPE tabletypename AS TABLE( col1 coltype, col2 coltype....);

CREATE TYPE anubhaviscrazy as table (


item_pos nvarchar(3),
size varchar(40),
qty decimal(15,2),
gross decimal(15,2),
currency nvarchar(5));

create procedure getOrderItemsByCat1 (in imCategory VARCHAR(60),


out out_order_items "ANUBHAV".ANUBHAVISCRAZY
)
Array: Single column table. Hold data of a single data type.
Syntax:
DECLARE arrayName arrayType ARRAY := ARRAY(val1, val2, va3....);
Access of data inside of an array is done by Index of an Array, index here starts with 1.
How to access array elements ArrayName[index]

create procedure arrayDemo (in idx integer, out ret integer)


LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN

declare tableOfTwo integer ARRAY = ARRAY(2,4,6,8,10,12,14,16,18,20);


ret = :tableOfTwo[:idx];

--can you return an array out of a procedure?


--NO

END;
Transfer data from an Array to a table

create procedure calculateTable (in num integer, out ret table(num integer))
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN
declare i integer := 1;
declare calc integer ARRAY;
for i in 1..10 do
calc[:i] = :i * :num;
end for;

--transfer data from an Array to a table


ret = unnest(:calc) as (num);
--can you return an array out of a procedure?
--NO

END;
Cursor: Cursors are used to fetch data from DB tables, they are actually a named query. Whenever a cursor is created, it is
assigned/bound to a query. It is possible to also pass parameters to the query.
It is not recommended to use cursor. When you use cursor, your are directly talking to DB interface. Typically when you use
queries, the data base optimizes your query.
Steps:
Declare  Open  Fetch  Close

Use case: read product infor by category.


Simple cursor with param:
create procedure cursorDemo (in im_cat varchar(30), out rprice integer)
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN

declare cursor c1 (cat varchar(30)) for select S from snwd_pd where category = :cat;

open c1(:im_cat);

--fetch statement will read row by row in the variable, here my_row variable is created automatically
fetch c1 into rprice;

close c1;
END;
Manipulate data with cursor

create procedure cursorTable (in im_cat varchar(30), out rprice table(


prod_id varchar(30),
price integer))
LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN

declare arr_price integer ARRAY;


declare prod_ids varchar(30) ARRAY;

declare cursor c1 (cat varchar(30)) for select * from snwd_pd where category = :cat;

--you dont need to open, fetch and close - erquivalent to loop at itab
for my_row as c1(:im_cat) do
--access the row index cursorname::rowcount
arr_price[c1::rowcount] = my_row.S + 100;
prod_ids[c1::rowcount] = my_row.product_id;
end for;

rprice = unnest(:prod_ids, :arr_price) as (prod_id, price);


--open c1(:im_cat);

--fetch statement will read row by row in the variable, here my_row variable is created automatically
--fetch c1 into rprice;

--close c1;
END;
How to check if the data is returned back from db table. Sy-dbcnt, sy-subrc.

create procedure checkIfTable (in tabName varchar(30), out hasRecord integer


LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN
select count(*) into x from :tabName;
if(:x > 0) then
hasRecord = 1;
end if;
END;

create procedure checkIfTable (in tabName varchar(30), out hasRecord integer)


LANGUAGE SQLSCRIPT
DEFAULT SCHEMA "SAPABAP1"
AS
BEGIN
itab = select * from snwd_so;
hasRecord = RECORD_COUNT(:itab);
END;
Application Layer
ADBC
CALL PROCEDURE
ABAP Program

Procedure Proxy
NW 7.4 AMDP
Class and method

Database Layer

HANA Procedure HANA Procedure


UTF- User Defined Functions
Is one of the containers used to define reusable code in SQL Script. Function always return one value. Functions can be
created only in SQLSCRIPT.
Functions never have bi-directional params like INOUT.

Types of UDF
 Scalar UDF – returns a scalar value, cannot use any table operations like cursor, CE, Array, input can be table
 Table UDF – Returns a table value

Use case: return the list of all the customers from snwd_bpa
Where bp_role = ‘1’

Example:
create function getCustomers returns
table(bp_id varchar(20), company_name varchar(80), currency_code varchar(4)) as
begin
return select bp_id, company_name, currency_code from sapabap1.snwd_bpa where bp_role = '1';
end;

Calling:

select * from getCustomers()


Scalar UDF to calculate the area

create function getCircleArea(radius integer) returns


area decimal as
begin
area = ( 3.14 * radius * radius );
end;

select getCircleArea(10) from dummy

are these stored in catalog ?


AMDP
ABAP Managed Data
< 7.4 > 7.4 SP02 to < 7.4 SP05 Procedures

7.4 Sp05

ADBC Procedure Proxy AMDP


Procedure Functions

Procedures are called by CALL statements Functions are always called by SQL statements
You can never call procedures in SQL queries They can be called also directly with assignment operator
CircleArea = calcularArea(10); //SPS 9
We can have INOUT parameters in procedure
Cannot have INOUT parameters
It can return multiple values
Always returns one value either Scalar or table
Direct assignment of output to variable is not possible.
AMDP : AMDP stands for ABAP Managed Data Procedure

 It is just a method inside an AMDP class.


 What makes a class as AMDP class, when we add a special power to an normal class by adding a marker interface, the
class becomes AMDP class. Name of interface is IF_AMDP_MARKER_HDB
 A method should be created as (typically as Static) inside the AMDP class. This is the container for SQL Script.

Syntax to create An AMDP method

METHOD method_name BY DATABASE PROCEDURE


FOR HDB LANGUAGE SQLSCRIPT
USING <table names which are used in SQL code has to be listed here>.

ENDMETHOD.

Advanage
 Lifecycle has been simplified using AMDP
 When the procedure in underlying HANA DB gets created?
not on activation, it when the AMDP is called first time.
AMDP and SQL Script Cautions with following points

 You need to take care of client handling by yourself. Unlike open sql there are no implicit client handling while sending SQL
statements to DB.
 You need to also handle LUW (Logical Unit Work) – not perform WRITE operation on DB SQL Script.
 Locking of data.
 Only work for HANA DB

CDS Views

1. Code push down


2. Better synchronization of ABAP and HANA View
3. Takes care of client handling
4. Integration with BOPF
What is CDS?
CDS stands for Core Data Service, it is an enhancement of SQL standard in ABAP layer. It is used to define semantically rich data
models (annotations) and user defined data types in database.

Which layer CDS is created?


Created in Application layer (designed)

When you activate the view is created in which layer?


DB layer

Is CDS view only work with ABAP running on HANA?


No. 7.4 SP05

Types of CDS in terms of technology


Can you create CDS views using SAP GUI?
No.

 ABAP CDS
 HANA CDS

What is enhanced?
 DDL (Data Definition Language)
 DQL (Data Query Language)
 Expression Language
CDS views are defined in ABAP layer, When activated an SQL view in HANA gets generated.

CDS SQL View (SE11)


activate
CDS Data Definition (ADT)

CDS Document CDS Entity (SQL View in HANA)


CDS Source Code
Parameters CDS Views DDIC Views (SE11)
Code To data Paradigm Yes No
Complexity Easy Not Easy
Outer Join Yes No
Complex Expression Yes (Case statement, reuse function) No
Analytical Adoptions Yes No
OData Services Direct Creation No
@Odata.publish: true
Types Yes No
Metadata Extension – Modularization Yes No
Built in function UNION, INTERS – Yes No
Parameters Yes No
Ready to use system variables Yes $session.user No
S/4Embbeded Analytics Yes No
(Query Browser)
S/4HANA – VDM – Virtual Data Modelling

When we design CDS views in S/4, We need to follow SAP best practices.

S/4 – Simplified Suite Pr

ECC  Business Suite  S/4


HANA primary
Best Practice
Scope Items
Application
OP
Cloud
Public
Private

DB - HANA

VDM is an annotation which indicates that


What type of data is exposed out of this CDS views (XL,L,S)
Category of CDS (S/4)
 Basic (Interface) – Master Data (ZTEAM_I_)
 Composite Views ( Cube Category ) – Join between master and fact (*_CO_*)
 Consumption views – Final consumption by UI and tools. (C_*)
EG – Engg. Graphics

CDS is created for the purpose of its consumers.

Fiori Application
@UI annotation
OData
Transactional App using BOPF
@ObjectModel
CDS Views
DML

Analytical Tools
@Analytics
OData

S/4HANA Embedded Analytics


Query Browser

https://help.sap.com/doc/abapdocu_751_index_htm/7.51/en-US/abencds_f1_association.htm
1. Basic CDS View
2. Design a CDS of Composite CDS view with a fact table, where total sales of customer exceeds a certain amount.

What is VDM
https://help.sap.com/saphelp_hba/helpdata/en/e1/1389b514ca4e828a5f6e97cab8be02/frameset.htm

Association : It is a relation ship between entities (db table or another CDS view).

 Simplicity of usage – association[1..1]


 Also provides options to pass parameters to the dependent entity
 Exposed Association and Ad-hoc Association – Performance improvement
 The associations are automatically transformed to Odata Associations.
Browser / Mobile
SAP Fiori

OData

Backend

When we want exactly one CDS view to be used for all the purpose of Fiori App, we can use
@Odata.expose: true
If we have multiple CDS views or some other tables and want to keep Odata service name based on your need, You can
design an Odata project in SEGW
From the perspective of Analytical tools

User case: Design CDS consumption to expose the sales data for products and suppliers.

RSRTS_ODP_DIS - Display Transient Provider Preview

Enhancement of CDS?
Z view on top of standard CDS view and include fields of your choice from exposed association of standard cds.

Limitations
1. You cannot debug CDS Views
2. Sometimes, we may have to use tables and columns of tables which are not supported by CDS. These are limitations of
CDS.

CDS Table function: (7.5 NW onwards)


A CDS view which can invoke a AMDP. Plug a AMDP which SQL script code with CDS view.
CDS DCL – CDS Security
We can restrict the data at record level. Analytical privilege.
Row level security on data. Majority of the time CDS views are used for read scenarios in enterprise data. We cannot expose
all the out. You are an MNC operating in different regions. You want to make sure, users america can only see sales orders
belonging to America region.

Roles

User
User
User Role_IN
User
User
User
Give access to these roles to the users Role_US

Auth. Object : ZBUP_CTRY


Auth field: COTRY and ACTVT
Role_ALL
1. Create CDS View
2. Make the authority check annotation to #CHECK
3. Create a DCL for CDS
4. Create Authorization class, Object and fields in SU21
5. Code with ( Country ) = aspect pfcg_auth( ZBUP_CTRY , COTRY , ACTVT = '03' ); with Auth object and field
6. Go to PFCG, create a new role
7. Add the profile with injecting the auth object inside
8. Decide the field values
9. Generate profile
10. Grant the role to the user.

Authority-check ‘S_DEVELOP’

https://blogs.sap.com/2016/11/25/hierarchies-in-cds-views/

UI Annotations

https://wiki.scn.sap.com/wiki/display/EmTech/OData+4.0+Vocabularies+-+SAP+UI#DataPointType
Any S/4HANA system, we have a standard SAP Fiori Application delivered by SAP called Query browser.
This is Fiori application, which has details of all the consumption CDS views, Using these built-in CDS view, we can perform
analytics on of Business data at Real-time, hence it is so called SAP S/4HANA embedded analytics.

Assign an Business role delivered by SAP called SAP_BR_EMPLOYEE.


http://sts4srvr.st.com:8005/sap/bc/ui5_ui5/ui2/ushell/shells/abap/FioriLaunchpad.html
UX
SAP GUI UX Rid of Server
Presentation Server Stickiness stickiness Fiori
layer Collaboration performance
Device Switch
Performance
OData
Gmail – write - Draft $batch

Application Layer Application Layer


ABAP
Assets: Workflows, Idocs, BDC, Assets: Workflows, Idocs, BDC,
SmartForms, BAPIs, Reports, BO, SPRO SmartForms, BAPIs, Reports, BO, SPRO
BOPF - CDS
LUW, Locking LUW, Locking

Draft state
Database Layer
Database Layer
Oracle, DB6, MaxDB,
HANA
MYSQL
Program Program

Int.Ses Int.Ses
FM sion FM
sion
memor memor
y y
FM FM
IMPOR IMPOR
T T
EXPOR Class EXPOR Class
T T

FM FM

SET

GET
Use case: design a database table for in flight meals. Where we can store preferences of meals per flight. We should allow
operator to create, edit and delete new entries in our custom db table with Fiori UX and draft functionality.

In last session, we created a Smart filter app using @UI annotations in CDS view.
DATA: LS_MEAL TYPE ZOFT_FLIGHT_MEAL.
DATA: LT_MEALS TYPE TABLE OF ZOFT_FLIGHT_MEAL.
SELECT * FROM SFLIGHT INTO TABLE @DATA(LT_SFLIGHT).
DELETE FROM ZOFT_FLIGHT_MEAL.
LOOP AT LT_SFLIGHT INTO DATA(LS_FLIGHT).
LS_MEAL-CARRID = LS_FLIGHT-CARRID.
LS_MEAL-CONNID = LS_FLIGHT-CONNID.
LS_MEAL-MEAL_ID = CL_UUID_FACTORY=>CREATE_SYSTEM_UUID( )->CREATE_UUID_C32( ).

IF SY-TABIX MOD 2 = 0.
LS_MEAL-MEAL = 7.
ELSE.
LS_MEAL-MEAL = 8.
ENDIF.
LS_MEAL-TOTAL_SEATS = LS_FLIGHT-SEATSMAX.
LS_MEAL-STATUS = 'X'.
APPEND LS_MEAL TO LT_MEALS.
ENDLOOP.
SORT LT_MEALS BY CARRID CONNID MEAL.
DELETE ADJACENT DUPLICATES FROM LT_MEALS COMPARING CARRID CONNID MEAL.
INSERT ZOFT_FLIGHT_MEAL FROM TABLE LT_MEALS.
How to expose Odata from SAP On Premise system over SCP (aka HCP) = SAP Cloud Platform using HANA Cloud Connector

https://www.youtube.com/watch?v=Cx3cXAEcnUs&list=PLcxqFaocb9WLtnq-rpXbRy5hnKECxr95G&index=8

https://blogs.sap.com/2016/09/20/fioriui5-cds-bopf-for-beginners/

ALV with IDA


Text Search capabilities with HANA used for ABAP Search

You might also like