Uploaded by gaikwad.soumitra24

HA400

advertisement
HA400
ABAP Programming for SAP HANA
.
.
PARTICIPANT HANDBOOK
INSTRUCTOR-LED TRAINING
.
Course Version: 16
Course Duration: 3 Day(s)
Material Number: 50151161
SAP Copyrights, Trademarks and
Disclaimers
© 2020 SAP SE or an SAP affiliate company. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any
purpose without the express permission of SAP SE or an SAP affiliate company.
SAP and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP SE (or an SAP
affiliate company) in Germany and other countries. Please see http://
global12.sap.com/corporate-en/legal/copyright/index.epx for additional trademark
information and notices.
Some software products marketed by SAP SE and its distributors contain proprietary
software components of other software vendors.
National product specifications may vary.
These materials may have been machine translated and may contain grammatical
errors or inaccuracies.
These materials are provided by SAP SE or an SAP affiliate company for
informational purposes only, without representation or warranty of any kind, and SAP
SE or its affiliated companies shall not be liable for errors or omissions with respect
to the materials. The only warranties for SAP SE or SAP affiliate company products
and services are those that are set forth in the express warranty statements
accompanying such products and services, if any. Nothing herein should be
construed as constituting an additional warranty.
In particular, SAP SE or its affiliated companies have no obligation to pursue any
course of business outlined in this document or any related presentation, or to
develop or release any functionality mentioned therein. This document, or any related
presentation, and SAP SE’s or its affiliated companies’ strategy and possible future
developments, products, and/or platform directions and functionality are all subject
to change and may be changed by SAP SE or its affiliated companies at any time for
any reason without notice. The information in this document is not a commitment,
promise, or legal obligation to deliver any material, code, or functionality. All forwardlooking statements are subject to various risks and uncertainties that could cause
actual results to differ materially from expectations. Readers are cautioned not to
place undue reliance on these forward-looking statements, which speak only as of
their dates, and they should not be relied upon in making purchasing decisions.
Typographic Conventions
American English is the standard used in this handbook.
The following typographic conventions are also used.
This information is displayed in the instructor’s presentation
Demonstration
Procedure
Warning or Caution
Hint
Related or Additional Information
Facilitated Discussion
User interface control
Example text
Window title
Example text
© Copyright. All rights reserved.
iii
iv
© Copyright. All rights reserved.
Contents
vii
Course Overview
1
Unit 1:
Introduction
2
13
17
Lesson: SAP HANA Basics and Technical Concepts
Exercise 1: Log On to ABAP Systems and Create Packages
Lesson: Introducing the SAP HANA Studio
27
32
47
Exercise 2: Log On to SAP HANA
Lesson: ABAP and SAP HANA
Exercise 3: Analyze SAP HANA-specific settings in ABAP
Dictionary
Lesson: Introducing the ABAP Development Tools (ADT)
Exercise 4: Create a Project in ABAP Development Tools
52
59
65
Unit 2:
67
71
Lesson: SAP HANA as Secondary Database– Access via Open SQL
Exercise 5: Access SAP HANA Via a Secondary Database
Connection
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
Exercise 6: Search for Potential Functional Issues with Code
Inspector
Lesson: Tools to Analyse Potential Performance Issues
Exercise 7: Analyze Potential Performance Issues
Lesson: Guided Performance Analysis
Exercise 8: Perform a Structured SQL Performance Analysis
Lesson: SQL Performance Rules for SAP HANA
81
87
96
103
115
121
131
139
141
145
151
158
169
180
185
193
199
Taking ABAP to SAP HANA
Unit 3:
Database Independent Code-to-Data
Lesson: Classical Open SQL and Its Limitations
Lesson: Enhanced Open SQL
Exercise 9: Use Features of Enhanced Open SQL
Lesson: The Basics of Core Data Services in ABAP
Exercise 10: Create a Core Data Services View and Use It in
ABAP
Lesson: Associations in Core Data Services
Exercise 11: Use Associations in Core Data Services in ABAP
Lesson: Outlook: More Interesting Features of CDS
Exercise 12: Optional: Define and Use a CDS View with Input
Parameter
© Copyright. All rights reserved.
v
217
Unit 4:
SAP HANA specific Code-to-Data
219
223
233
Lesson: SAP HANA Native SQL Syntax
Lesson: ABAP-Managed Database Procedures
Exercise 13: Create and Call an ABAP-Managed Database
Procedure
247
251
Lesson: ABAP Database Connectivity (ADBC)
Exercise 14: Issue a Native SQL Statement via ADBC
263
Unit 5:
265
271
275
285
291
307
Lesson: Working with SAP HANA Objects in SAP HANA Studio
Lesson: Consuming SAP HANA Objects with Native SQL
Exercise 15: Access an SAP HANA View via Native SQL
Lesson: Using Proxy Objects to Consume SAP HANA Objects
Exercise 16: Create an External View for SAP HANA View and
Use it in an Open SQL SELECT
Unit 6:
309
357
Unit 7:
368
369
391
395
vi
Case Study: Optimize a Report on Flight Customer Revenue
Lesson: Optimizing a Report with CDS View and ALV IDA
Exercise 20: Case Study Part 1: Code Push Down with ABAP
Core Data Services
Exercise 21: Case Study Part 2: Use ALV Optimized for SAP
HANA
377
389
Advanced Topics
Lesson: Transporting SAP HANA Objects with ABAP Transport
Requests
Lesson: Using SAP HANA Full Text Search
Exercise 17: Implement a Fuzzy Search
Exercise 18: Implement a Value Help with Fuzzy Search
Lesson: ABAP List Viewer with Integrated Database Access (ALV
IDA)
Exercise 19: Use ALV with Integrated Data Access for a CDS
View
321
329
337
346
367
Consuming SAP HANA Objects in ABAP
Unit 8:
Appendix
Lesson: Additional ABAP Language Enhancements
Lesson: External Session Debugging of ABAP-Managed Database
Procedures
© Copyright. All rights reserved.
Course Overview
TARGET AUDIENCE
This course is intended for the following audiences:
●
Developer
© Copyright. All rights reserved.
vii
viii
© Copyright. All rights reserved.
UNIT 1
Introduction
Lesson 1
SAP HANA Basics and Technical Concepts
Exercise 1: Log On to ABAP Systems and Create Packages
2
13
Lesson 2
Introducing the SAP HANA Studio
Exercise 2: Log On to SAP HANA
17
27
Lesson 3
ABAP and SAP HANA
Exercise 3: Analyze SAP HANA-specific settings in ABAP Dictionary
32
47
Lesson 4
Introducing the ABAP Development Tools (ADT)
Exercise 4: Create a Project in ABAP Development Tools
52
59
UNIT OBJECTIVES
●
Describe SAP HANA basics
●
Understand the fundamental technical concepts of SAP HANA
●
Know SAP HANA studio
●
Connect SAP HANA studio to an SAP HANA system
●
Understand SAP HANA catalog (schemas and tables)
●
Know SAP HANA content (packages, views, procedures)
●
Explain the SAP HANA and ABAP evolution
●
Indentify SAP HANA-specific settings in ABAP Dictionary
●
Describe the various code-to-data concepts
●
Work with ABAP Development Tools
© Copyright. All rights reserved.
1
Unit 1
Lesson 1
SAP HANA Basics and Technical Concepts
LESSON OVERVIEW
In this lesson, you learn how to describe SAP HANA goals, technical innovations, and
challenges; understand the fundamental technical concepts of SAP HANA; and determine if
SAP HANA’s row store or column store is used for an ABAP transparent table and which
indices are used on SAP HANA.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Describe SAP HANA basics
●
Understand the fundamental technical concepts of SAP HANA
SAP HANA Goals
Figure 1: Today's Technology Requires Trade off Decisions
Animation: Today's Technology Requires Trade off Decisions
For more information on Today's Technology Requires Trade off Decisions,
please view the animation in the lesson SAP HANA Basics and Technical
Concepts, online in the SAP Learning Hub.
Developing applications using technology that pre-dates SAP HANA typically required making
several trade-off decisions.
2
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
The figure, Today's Technology Requires Trade-off Decisions, shows the five dimensions of
requirements that are typical for business applications. So far, these dimensions have been in
conflict.
For example, you had to decide between providing a high-speed application and developing an
application that does not require special preparation of the data, such as calculating
aggregations beforehand and storing the results in addition to the base data. In addition, it
was not possible to develop an application which is both real-time and able to analyze a large
amount of data, perhaps even unstructured data, simultaneously.
Figure 3: SAP HANA: Delivers Across Five Dimensions
Animation: SAP HANA Delivers Across Five Dimensions
For more information on SAP HANA Delivers Across Five Dimensions, please
view the animation in the lesson SAP HANA Basics and Technical Concepts,
online in the SAP Learning Hub.
SAP HANA tries to deliver across all these five dimensions, so that you no longer have to
make so many trade-off decisions. The goal is to enable the development of applications that
combine Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP)
usage patterns.
SAP HANA Goals
●
Enable new applications and optimize existing applications
●
High performance and scalability
●
Hybrid data management system – combining different paradigms in one system
●
Compatibility and standard Database Management System (DBMS) features
●
Support for text analysis, indexing, and search
●
Cloud support and application isolation
●
Support for temporal tables
© Copyright. All rights reserved.
3
Unit 1: Introduction
●
Executing application logic inside the data layer
SAP HANA has the following goals:
Enable new applications and optimize existing applications
SAP HANA is an in-memory data platform that is deployable as an appliance or in the
cloud and makes full use of the capabilities of current hardware to increase application
performance, reduce cost of ownership, and enable new scenarios and applications that
were not possible before.
High performance and scalability
SAP HANA is designed to make full use of multi-core CPUs by parallelization of
execution. It can be distributed across multiple servers to achieve good scalability in
terms of both data volume and concurrent requests.
Hybrid data management system – combining different paradigms in one system
SAP HANA architecture integrates different in-memory storages (column-based, rowbased, and object-based), traditional disk-based tables, text analysis and search, and
built-in support for planning. Combining all these capabilities in a single product not only
improves performance but reduces overall complexity and cost.
Compatibility and standard DBMS features
An important goal is the possibility to use the SAP HANA database system as a
replacement for any standard relational database management system. The SAP HANA
database system is a full relational database management system with SQL interface,
transactional isolation, and recovery (ACID properties), and high availability. SAP
applications that use Open SQL should be able to run on SAP HANA without changes.
Support For text analysis, indexing and search
An important goal of SAP HANA is to provide powerful analysis, and text indexing and
search capabilities that support a state-of-the-art search experience. This includes full
text search with advanced features, such as freestyle search (without knowing the name
of attributes in the database), linguistic search, and fault-tolerant fuzzy search.
Cloud support and application isolation
In cloud deployments, a system must be shared – including physical servers and installed
software – between multiple customers. SAP HANA will support this in the future, with
the planned ability to host multiple isolated databases within a single SAP HANA system.
The databases inside one system will have their own data, metadata, and users, but will
share the same hardware, the same SAP HANA software installation, and the system
administration. This feature helps to support cloud scenarios – but it can also be used in
an on-premise deployment, for example, for running multiple unrelated applications in
one SAP HANA system with effective isolation and resource management.
Support for temporal tables
SAP applications that use Open SQL should run on SAP HANA without changes. In
temporal tables, update operations do not modify the existing records. Instead, new
versions of the data records are inserted. Applications may use temporal tables, for
example, for time-based reporting and analysis or for versioning and change recording
purposes.
Executing application logic inside the data layer
To benefit from the parallelization and optimization capabilities of SAP HANA,
applications must execute data intensive operations on the database level. Pushing
calculations to the database layer can also significantly reduce the amount of data that
4
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
needs to be transferred between the database and application server. SAP HANA allows
application developers to define application-specific functions that are executed inside
the database layer.
SAP HANA Application Architectures
SAP HANA can be used in different architectural scenarios, which in turn provide the
technological base for the different application areas.
Types of SAP HANA-Based Applications
Figure 5: Architectural Scenarios
SAP HANA can be used in different architectural scenarios, which in turn provide the
technological base for the different application areas.
From an ABAP programmer’s point of view, there are two groups of scenarios, as follows:
●
Scenarios in which SAP HANA functions as the database for an Application Server ABAP
●
Scenarios based on a standalone SAP HANA Server
Although the non-ABAP scenarios are mentioned here, they are not the focus of this course.
The first type are data warehouses, in which data is typically replicated from existing
applications into a separate SAP HANA database, on top of which analytical content is
developed and then consumed using business intelligence tools or simply Microsoft Excel.
A second type of HANA-based application consists of the newly-built, native applications
developed using SAP HANA extended application services.
Animation: Architectural Scenarios
For more information on Architectural Scenarios, please view the animation in
the lesson SAP HANA Basics and Technical Concepts, online in the SAP Learning
Hub.
© Copyright. All rights reserved.
5
Unit 1: Introduction
Figure 7: SAP HANA as Database for ABAP Applications
The primary concern of this course is to learn how to optimize ABAP applications directly
running on SAP HANA, that is, applications using SAP HANA as the primary database
underneath the ABAP stack. A typical example of this kind of application is SAP CRM powered
by SAP HANA, or the Business Suite powered by SAP HANA.
The course also covers the types of applications shown on the right-hand side of the SAP
HANA as Database for ABAP Applications figure, which use SAP HANA to accelerate ABAP
applications by using a separate SAP HANA server apart from the ABAP stack. This replicates
some of the ABAP system’s data into SAP HANA and calls SAP HANA remotely from ABAP to
speed up selected reports or transactions.
Animation: SAPHANA as Database for ABAP Applications
For more information on SAPHANA as Database for ABAP Applications, please
view the animation in the lesson SAP HANA Basics and Technical Concepts,
online in the SAP Learning Hub.
6
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
SAP HANA Innovations and Challenges
Figure 9: What Made SAP HANA Possible?
Dramatically improved hardware economics and technology innovations in software made it
possible for SAP to deliver its vision of the real-time enterprise with in-memory business
applications. Understanding them is important to an understanding of SAP HANA’s
performance characteristics.
In-Memory Computing and the Shift of Performance Bottlenecks
Historically, database systems were designed to perform well on computer systems with
limited RAM. This had the effect that slow disk I/O was the main bottleneck in data
throughput. Consequently, the architecture of those systems was designed with a focus on
optimizing disk access, for example, by minimizing the number of disk blocks (or pages) to be
read into the main memory when processing a query. In addition, CPUs had a single core and
networks were far slower.
© Copyright. All rights reserved.
7
Unit 1: Introduction
Figure 10: Shift of Performance Bottlenecks
Computer architecture has changed in recent years. Multi-core CPUs (multiple CPUs on one
chip or in one package) are now standard, with fast communication between processor cores
enabling parallel processing. Main memory is no longer a limited resource, and modern
servers can have 2TB of system memory, which allows complete databases to be held in
RAM.
Currently, server processors have up to 64 cores and 128 cores will soon be available. With
the increasing number of cores, CPUs are able to process increased data per time interval.
This shifts the performance bottleneck from disk I/O to the data transfer between CPU cache
and main memory.
Figure 11: New Bottlenecks Become Important
To get the best performance from current hardware, the new bottlenecks have to be avoided
by addressing the challenges as follows:
8
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
●
●
Avoid CPU cache misses and expensive data transfer from main memory into the CPU –
optimize loading the data into the CPU.
Avoid idling CPU cores – make use of parallelism by using all the cores of a CPU, and
several CPUs.
Animation: New Bottlenecks Become Important
For more information on New Bottlenecks Become Important, please view the
animation in the lesson SAP HANA Basics and Technical Concepts, online in the
SAP Learning Hub.
Column Store Versus Row Store
Figure 13: Row Store
By accessing data in column-store order, you benefit immensely from simplified table scan
and data pre-caching. This can make all the difference in performance.
Figure 14: Column Store
© Copyright. All rights reserved.
9
Unit 1: Introduction
Data Compression
Figure 15: Columnar Dictionary Compression
SAP HANA uses different, efficient compression methods, such as dictionary encoding, runlength encoding, and more. This has the following benefits:
●
●
●
It reduces the amount of memory required.
It speeds up operations on columns because the columns can be loaded into the CPU
caches faster and with fewer loading cycles.
It speeds up operations on columns because many comparisons become integer value
comparisons. For example, these are faster than string comparisons.
Animation: Columnar Dictionary Compression
For more information on Columnar Dictionary Compression, please view the
animation in the lesson SAP HANA Basics and Technical Concepts, online in the
SAP Learning Hub.
10
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
Partitioning and Parallel Processing
Figure 17: Parallel Processing
On SAP HANA and with column storage, data is only partially blocked. This makes parallel
processing possible. Even the same column can be split up and processed by different cores
at the same time.
Animation: Parallel Processing
For more information on Parallel Processing, please view the animation in the
lesson SAP HANA Basics and Technical Concepts, online in the SAP Learning
Hub.
© Copyright. All rights reserved.
11
Unit 1: Introduction
Figure 19: Using Partitioning to Further Leverage Parallelism
The use of parallelism can be taken a step further by creating different partitions of the data
to be stored and processed on different blades. This allows for the management and
processing of huge amounts of data.
12
© Copyright. All rights reserved.
Unit 1
Exercise 1
Log On to ABAP Systems and Create Packages
Simulation: Log On to ABAP Systems and Create Packages
For more information on Log On to ABAP Systems and Create Packages, please
view the simulation in the lesson SAP HANA Basics and Technical Concepts
online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Task 1: Log On to Application Server ABAP with SAP HANA as the Primary Database
Using SAP Logon, log on to the Application Server ABAP that uses SAP HANA as a primary
database. Create a development package ZHA400_##, where ## stands for your group ID.
1. Log on to system T8N, which uses SAP HANA as its primary database.
2. Open system status and check the system's release and database.
3. Create ABAP package ZHA400_##.
Task 2: Log On to Other Application Server ABAP with Sybase as the Primary Database
Using SAP Logon, log on to the Application Server ABAP that does not have SAP HANA as a
primary database. Use the system ID, user, and password provided by your instructor. Create
a development package ZHA400_##, where ## stands for your group ID.
1. Log on to system ZME, which uses Sybase as its primary database.
2. Open the system status and check the system's release and database.
3. Start transaction SE80 and create the package. Assign the package to application
component CA and software component HOME. Use the workbench request already
created by your instructor (press Own Requests to find and use this request).
© Copyright. All rights reserved.
13
Unit 1
Solution 1
Log On to ABAP Systems and Create Packages
Simulation: Log On to ABAP Systems and Create Packages
For more information on Log On to ABAP Systems and Create Packages, please
view the simulation in the lesson SAP HANA Basics and Technical Concepts
online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Task 1: Log On to Application Server ABAP with SAP HANA as the Primary Database
Using SAP Logon, log on to the Application Server ABAP that uses SAP HANA as a primary
database. Create a development package ZHA400_##, where ## stands for your group ID.
1. Log on to system T8N, which uses SAP HANA as its primary database.
a) Choose Start → SAP Logon from the Microsoft Windows Start menu.
b) Double-click the connection named T8N[SPACE].
c) Enter your user name and password for the ABAP system(s), as provided by your
instructor, and press Enter.
2. Open system status and check the system's release and database.
a) From the main menu bar, open System → Status.
b) In the SAP System data frame, choose Details to see the installed components and
their versions.
c) In the Database data frame, check the content of the Database System field.
3. Create ABAP package ZHA400_##.
a) Start transaction SE80.
b) Ensure the Repository Browser is selected in the left-hand frame, and that Package is
chosen in the first list box.
c) Enter the package name in the second input field and press Return.
d) Confirm that you want to create the non-existing package.
e) Enter a short description, application component CA, and software component HOME,
and press Enter.
f) When prompted for a transportable workbench request, use the workbench request
already created by your instructor (choose Own Requests to find and use this request).
14
© Copyright. All rights reserved.
Lesson: SAP HANA Basics and Technical Concepts
Task 2: Log On to Other Application Server ABAP with Sybase as the Primary Database
Using SAP Logon, log on to the Application Server ABAP that does not have SAP HANA as a
primary database. Use the system ID, user, and password provided by your instructor. Create
a development package ZHA400_##, where ## stands for your group ID.
1. Log on to system ZME, which uses Sybase as its primary database.
a) Choose Start → SAP Logon from the Microsoft Windows Start menu.
b) Double-click the connection named ZME[SPACE].
c) Enter your user name and password for the ABAP system(s) as provided by your
instructor and press Enter.
2. Open the system status and check the system's release and database.
a) Perform this step as before.
3. Start transaction SE80 and create the package. Assign the package to application
component CA and software component HOME. Use the workbench request already
created by your instructor (press Own Requests to find and use this request).
a) Perform this step as before.
© Copyright. All rights reserved.
15
Unit 1: Introduction
LESSON SUMMARY
You should now be able to:
16
●
Describe SAP HANA basics
●
Understand the fundamental technical concepts of SAP HANA
© Copyright. All rights reserved.
Unit 1
Lesson 2
Introducing the SAP HANA Studio
LESSON OVERVIEW
In this lesson, you learn how to explain the central functions of SAP HANA studio, switch
between different perspectives in SAP HANA studio, set up a connection to an SAP HANA
database, understand schemas and tables in SAP HANA studio, and analyze the definition of
tables in SAP HANA studio.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Know SAP HANA studio
●
Connect SAP HANA studio to an SAP HANA system
●
Understand SAP HANA catalog (schemas and tables)
●
Know SAP HANA content (packages, views, procedures)
SAP HANA Studio – An Eclipse-Based Tool
Figure 21: SAP HANA Studio – An Eclipse-Based Development Environment
© Copyright. All rights reserved.
17
Unit 1: Introduction
When you start optimizing ABAP applications for SAP HANA, you may have to access the SAP
HANA layer or the SAP HANA database server itself to, for example, prototype native SQL
statements, to look at SAP HANA artifacts such as attribute views, column views, or database
procedures, or to debug database procedures.
The tool to perform such tasks on the SAP HANA layer is the SAP HANA studio.
SAP HANA studio is an Eclipse-based integrated development environment that provides
tools to administer, monitor, and configure SAP HANA systems.
These tools are based on existing Eclipse frameworks.
Animation: SAP HANA Studio – An Eclipse-Based Development Environment
For more information on SAP HANA Studio – An Eclipse-Based Development
Environment , please view the animation in the lesson Introducing the SAP HANA
Studio, online in the SAP Learning Hub.
SAP chose Eclipse as the platform for an SAP HANA Integrated Development Environment
(IDE) because Eclipse is SAP’s strategic platform for integrated design-time and development
tools in general. The open Eclipse platform offers first-class user experience, powerful
platform capabilities, and a broad and vivid ecosystem that regularly contributes
enhancements and extensions.
Eclipse is a platform that has been designed for building integrated Web and application
development tools. The platform does not provide a great deal of end-user functionality by
itself. The value of the platform is what it encourages: rapid development of integrated
features based on a plug-in model.
SAP plays an active role in the Eclipse Foundation as one of its strategic members. Many of
the SAP design-time, development, and administration tools already use the Eclipse platform.
These include SAP NetWeaver Visual Composer, the Sybase Unwired Platform, and the SAP
HANA studio.
As a result of this SAP strategy, SAP also provides an Eclipse-based development
environment for ABAP called ABAP Development Tools for Eclipse (ADT). This makes it
possible to combine both development environments in a single, common IDE for both ABAP
and SAP HANA development.
18
© Copyright. All rights reserved.
Lesson: Introducing the SAP HANA Studio
Figure 23: SAP HANA Studio – Perspectives and Views
Animation: SAP HANA Studio – Perspectives and Views
For more information on SAP HANA Studio – Perspectives and Views, please
view the animation in the lesson Introducing the SAP HANA Studio, online in the
SAP Learning Hub.
Like most Eclipse-based development environments, SAP HANA studio provides several
perspectives within the Eclipse workbench.
Each perspective is tailored for particular groups of tasks and is a pre-configured set of panes
called views. Examples of perspectives are as follows:
●
Administration Console – to administer, monitor and configure SAP HANA systems
●
Modeler – to develop information models and database procedures
●
SAP HANA development – to develop native SAP HANA-based applications using SAP
HANA extended application services
Examples of views are as follows:
●
●
●
Systems – visible in most SAP HANA perspectives and showing the list of SAP HANA
systems the IDE is connected to
Properties – showing properties of the currently selected object, for example, of a
configured SAP HANA system
Job log – showing the list of recent jobs performed, for example, imports of development
objects and activations
© Copyright. All rights reserved.
19
Unit 1: Introduction
Details of SAP HANA Studio
Figure 25: Most Relevant Perspective For ABAP Developers: Modeler
The Modeler is the perspective most relevant for ABAP developers. It provides access to the
views and database procedures that you can consume in the ABAP environment. You can
open it using the menu item Window → Open Perspective or the Open Perspective button in
the toolbar.
A central part of this perspective is the Systems view on the left-hand side. This view contains
a list of systems. Each system represents a logon to an SAP HANA system with a particular
user. Systems can be grouped in folders to structure the list.
Figure 26: System View
20
© Copyright. All rights reserved.
Lesson: Introducing the SAP HANA Studio
Each system shows a hierarchy of objects visible to this user.
The catalog consists of one or several schemas, each containing a set of database objects,
such as database tables and database views.
The content contains models, which are specific objects that allow optimized access to the
database tables. Part of these models are SAP HANA views and database procedures. SAP
HANA views and database procedures are arranged in content packages, which are similar to
ABAP packages, as they group objects that logically belong together.
Systems – Access to SAP HANA Server
Figure 27: Connecting to an SAP HANA Database
Animation: Connecting to an SAP HANA Database
For more information on Connecting to an SAP HANA Database, please view the
animation in the lesson Introducing the SAP HANA Studio, online in the SAP
Learning Hub.
To connect to an SAP HANA system and see the corresponding catalog and content, use the
Systems view, and the context menu item Add System.
To add a system, you need the following:
●
●
The host name, on which the SAP HANA system is installed. Note that this is typically
different from the host of the ABAP system.
The instance number of the SAP HANA system. Again, note that this is typically different
from the instance number of the ABAP system.
●
A description.
●
The database user – also different from your ABAP user.
●
The password for the database user.
© Copyright. All rights reserved.
21
Unit 1: Introduction
Schemas and Tables
Figure 29: Table Definitions
Once connected, you can open the database catalog and look, for example, at the definition of
tables on the SAP HANA layer. The table editor also allows exporting the SQL statement used
to create the database table.
SAP HANA Information Models
Figure 30: SAP HANA Information Models
Under the Content node, you find the SAP HANA information models.
22
© Copyright. All rights reserved.
Lesson: Introducing the SAP HANA Studio
The information models are organized in a hierarchy of packages and consist of SAP HANA
views and SAP HANA stored procedures.
Every package defines a name space, that is, views and procedures may have identical names
as long as they are located in different packages.
Note:
Attribute views and analytic views shown in the figure, SAP HANA Information
Models, have become obsolete with SAP HANA 1.0 SPS12. SAP strongly
recommends not to create new views of those types. Furthermore, SAP HANA
studio offers tools to convert existing attribute and analytic views into calculation
views.
Search for SAP HANA Artefacts
SAP HANA studio provides two different search dialogs: A global search and a local search in
a subtree of the content hierarchy.
Figure 31: Search Functions - Global Search
You perform a global search via the search field in the toolbar of SAP HANA Studio. The global
search covers not only information models in subtree Content but also the various schemas in
the Catalog.
© Copyright. All rights reserved.
23
Unit 1: Introduction
Figure 32: Search Functions - Local Search in Content
You can perform a local search by right-clicking a content package and choosing Find. This
search covers only the selected content package and its subpackages.
Delivery Units
Figure 33: Delivery Units for Transport of SAP HANA Content
You open the administration view for delivery units from the Quick Launch view.
24
© Copyright. All rights reserved.
Lesson: Introducing the SAP HANA Studio
Each delivery unit must have a unique name. When creating a new delivery unit, a vendor
name is automatically derived from the system settings and linked with this delivery unit. The
SAP vendor name is sap.com.
© Copyright. All rights reserved.
25
Unit 1: Introduction
26
© Copyright. All rights reserved.
Unit 1
Exercise 2
Log On to SAP HANA
Simulation: Log On to SAP HANA
For more information on Log On to SAP HANA, please view the simulation in the
lesson Introducing the SAP HANA Studio online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Task 1: Log On to SAP HANA
Open the SAP HANA Modeler perspective that is included in Eclipse.exe and establish a
connection to the SAP HANA server.
1. Open the SAP HANA Modeler perspective that is included in Eclipse.exe.
2. Add the SAP HANA system to the Systems view. Use the server name, user ID and
password provided by your instructor.
Task 2: Open the Definition of a Table in SAP HANA Studio
Using the SAP HANA tools in Eclipse, open the definition of table SBOOK in schema SAPT8N
and display its content.
1. Open Eclipse, switch to the SAP HANA Modeler perspective and log on to the SAP HANA
system if you haven’t already done so yet.
2. Expand schema SAPT8N and filter the tables of this schema to locate table SBOOK.
3. Open the definition of table SBOOK.
Task 3: Find and Open the Definition of an SAP HANA View
Using the SAP HANA tools in Eclipse, search for view CA_DAYS_AHEAD.
1. Search the SAP HANA content for the string “CA_DAYS”.
The search result contains the following view:
© Copyright. All rights reserved.
27
Unit 1: Introduction
The view is located in package:
2. Open the definition of the view.
28
© Copyright. All rights reserved.
Unit 1
Solution 2
Log On to SAP HANA
Simulation: Log On to SAP HANA
For more information on Log On to SAP HANA, please view the simulation in the
lesson Introducing the SAP HANA Studio online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Task 1: Log On to SAP HANA
Open the SAP HANA Modeler perspective that is included in Eclipse.exe and establish a
connection to the SAP HANA server.
1. Open the SAP HANA Modeler perspective that is included in Eclipse.exe.
a) Choose Start → All Programs → Eclipse.exe from the Microsoft Windows Start menu.
Alternatively you can choose Eclipse.exe from the windows task bar.
b) If the Welcome page is open, close the page or choose the Workbench link.
c) Choose the Open Perspective button or menu item Window → Perspective → Open
Perspective → Other ... , select item SAP HANA Modeler and choose OK.
2. Add the SAP HANA system to the Systems view. Use the server name, user ID and
password provided by your instructor.
a) Make sure you are in the SAP HANA Modeler perspective. If not, change the
perspective using the buttons in the upper right-hand corner.
b) Right-click the area in the Systems window on the left and choose Add System.
c) Enter the host name and instance number provided by your instructor, and the
description SAP HANA.
d) In the Locale dropdown list, choose English (United States).
e) Choose Next.
f) Enter the user ID and password provided by your instructor, then choose Finish.
Task 2: Open the Definition of a Table in SAP HANA Studio
Using the SAP HANA tools in Eclipse, open the definition of table SBOOK in schema SAPT8N
and display its content.
1. Open Eclipse, switch to the SAP HANA Modeler perspective and log on to the SAP HANA
system if you haven’t already done so yet.
© Copyright. All rights reserved.
29
Unit 1: Introduction
a) Open Eclipse if it is not open yet.
b) Switch to the SAP HANA Modeler perspective.
c) Log on to the SAP HANA system using the connection prepared earlier in this exercise.
2. Expand schema SAPT8N and filter the tables of this schema to locate table SBOOK.
a) In the Navigator window on the left side, expand Catalog → SAPT8N
b) Right-click subnode Tables and choose Filters....
c) Enter the search string SBOOK and choose Okay.
3. Open the definition of table SBOOK.
a) Expand node Tables and double-click table SBOOK.
Task 3: Find and Open the Definition of an SAP HANA View
Using the SAP HANA tools in Eclipse, search for view CA_DAYS_AHEAD.
1. Search the SAP HANA content for the string “CA_DAYS”.
a) In the Navigator window on the left side, right-click the connection’s node Content and
choose Find.
b) Enter the search string “CA_DAYS”.
The search result contains the following view:
CA_DAYS_AHEAD
The view is located in package:
ha400.primdb
2. Open the definition of the view.
a) Double-click the view CA_DAYS_AHEAD (ha400.primdb) in the search results, or
select it and choose OK.
30
© Copyright. All rights reserved.
Lesson: Introducing the SAP HANA Studio
LESSON SUMMARY
You should now be able to:
●
Know SAP HANA studio
●
Connect SAP HANA studio to an SAP HANA system
●
Understand SAP HANA catalog (schemas and tables)
●
Know SAP HANA content (packages, views, procedures)
© Copyright. All rights reserved.
31
Unit 1
Lesson 3
ABAP and SAP HANA
LESSON OVERVIEW
In this lesson you learn how SAP HANA influences the way we design and implement ABAP
applications. You get an overview of the strategies that exist for optimizing ABAP applications
based on SAP HANA. And you will see that starting with ABAP release 7.40, SAP introduced
new ABAP language features, repository object types, development tools and analysis tools in
order to support such optimizations.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain the SAP HANA and ABAP evolution
●
Indentify SAP HANA-specific settings in ABAP Dictionary
●
Describe the various code-to-data concepts
SAP NetWeaver AS ABAP Support for SAP HANA
Figure 35: Evolution of ABAP Programming for SAP HANA
32
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Support for Optimizing Applications on SAP HANA
Starting with release 7.4, ABAP provides support for optimizing ABAP applications running on
SAP HANA.
Figure 36: SAP NetWeaver AS ABAP Support for Optimizing Applications
There are transparent optimizations you do not see as an application developer, but which
you benefit from because they happen under the hood. An example is the SELECT… FOR ALL
ENTRIES… statement in Open SQL, the implementation of which has been improved.
New performance analysis tools are available and existing tools, such as static code checks
and the runtime analysis, have been improved to effectively support the optimization of
existing ABAP code.
The ABAP language and the Open SQL language have been extended. For example, OpenSQL
now supports more complicated joins and sub-queries, and there are ways to integrate SAP
HANA stored procedures in ABAP code.
The use of SAP HANA artifacts has been simplified. For example, you can access SAP HANA
column views through the ABAP Dictionary using Open SQL.
Some re-use components have been extended or optimized for SAP HANA, such as the SAP
List Viewer (ALV).
On top of all this, the ABAP platform team provides guidelines for optimizing ABAP code
running on SAP HANA.
Changes to SAP Tables when SAP HANA is the Primary Database
Common Changes to SAP Tables when SAP HANA is the Primary Database
Animation:
For more information on , please view the animation in the lesson ABAP and SAP
HANA, online in the SAP Learning Hub.
Common Changes to SAP Tables when SAP HANA is the Primary Database
© Copyright. All rights reserved.
33
Unit 1: Introduction
When comparing an SAP system with SAP HANA as its primary database to the same system
on another database, you may find the following differences:
De-Pooling and De-Clustering
Many tables that used to be pool tables and cluster tables are transparent tables if the
primary database is SAP HANA.
Deactivation of Secondary Indexes
Many secondary indexes that are required on other databases are not activated on SAP
HANA database.
Empty Aggregate Tables
Some aggregate tables are not needed on SAP HANA database and are therefore not
populated with data.
In systems that use SAP HANA as their primary database, many tables that used to be pool
tables and cluster tables are defined transparent tables. This became necessary because the
pools and clusters with their one big binary VARDATA column do not go together well with
SAP HANA’s column store.
SAP HANA, with its in-memory technology, can perform full scans of database tables in
sufficiently short time, which makes most of the existing secondary indexes a waste of
memory space that doesn’t pay back. Therefore, SAP deactivated most of the secondary
indexes in systems that use SAP HANA as primary database.
New Settings in ABAP Dictionary to Support SAP HANA DB
Animation:
For more information on , please view the animation in the lesson ABAP and SAP
HANA, online in the SAP Learning Hub.
The following are settings in ABAP Dictionary to support SAP HANA:
Storage type for tables
Set storage type (column store or row store) in technical settings
Depooling and Declustering
Make pool and cluster tables transparent on certain databases.
Selective Activation of Secondary Indexes
Create secondary indexes only for certain databases.
Definition of Fulltext Indexes
Define secondary indexes as SAP HANA-specific fulltext indexes.
Setting the Storage Type for a Table
34
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Figure 37: Setting the Storage Type for a Table
To support setting the storage type for a table in ABAP Dictionary, a new tab has been added
to the Maintain Technical Settings form for database tables. The new tab is called DB-Specific
Properties and allows for switching between the following three storage types:
●
●
Storage type Column Store creates the database table in the SAP HANA column store, or
moves it there.
Storage type Row Store creates the database table in the SAP HANA row store, or moves it
there.
If the current database does not support a differentiation between column and row store, the
setting is ignored.
Note:
This setting can be changed after the table has been created, and the table will be
moved into the other store. Use this with caution, however, since it may involve
reorganizing table contents, should such content exist already.
De-Clustering
© Copyright. All rights reserved.
35
Unit 1: Introduction
Figure 38: De-Clustering
To support de-pooling and de-clustering on SAP HANA, a new option has been added to the
Choose Table Category dialog. You find this dialog under Extras → Change/Display Table
Category.
For pool or cluster tables, you can specify a list of databases on which these tables should be
considered transparent tables.
If you do so, the table will be created as a database object on the specified databases. On all
other databases, its content will be stored as usual in the corresponding table pool or table
cluster.
Selective Activation of Secondary Indexes
36
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Figure 39: Selective Activation of Secondary Indexes
You can activate secondary indexes selectively via the respective dialog in the index
definition.
Note:
Technically speaking, this is not a new feature in ABAP Dicitionary. The selective
activation of secondary indexes has been available for some time, but it has only
been used widely as a standard setting with SAP HANA database.
Secondary Index as Full-Text Index
© Copyright. All rights reserved.
37
Unit 1: Introduction
Figure 40: Secondary Index as Full-Text Index
To support the definition of SAP HANA-specific full text indexes in the ABAP Dictionary, the
new dialog Full Text Index has been added to the menu that is available when editing a
secondary index.
Note:
We will discuss SAP HANA full text search and SAP HANA full text index in a later
unit of this course.
What's in It for ABAP Programmers?
The new capabilities of SAP HANA offer a huge variety of opportunities for ABAP Developers.
Figure 41: What's in It for ABAP Programmers?
38
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Accelerate
By optimizing the coding of long-running background jobs for SAP HANA, the runtime for
these jobs can be reduced. More jobs can be executed in the same time, and particularly
costly tasks are possible in one go, rather than splitting them up.
Extend
In the past, some reports had to be executed in the background, simply because their
runtime was too long for dialog processing. Consequently, users worked on snapshots or
pre-aggregated data sets. By optimizing these reports with SAP HANA, they can be
offered as online reports again, displaying real-time data with full drill-down capability.
Innovate
With SAP HANA's analysis and calculation capabilities, ABAP developers can design new
applications that would not have been possible in the past.
A good practice when transitioning and optimizing ABAP applications to SAP HANA is to
follow a three-step approach.
Animation: What's in It for ABAP Programmers?
For more information on What's in It for ABAP Programmers?, please view the
animation in the lesson ABAP and SAP HANA, online in the SAP Learning Hub.
Figure 43: Steps to Transition ABAP Code for SAP HANA
The first step is to detect those places where performance can or should be improved, and to
analyze and prioritize the findings based on the importance of the places detected.
The next step is to optimize the existing code, using the prioritized list.
An optional last step is to use SAP HANA’s new features to redesign and innovate your
business processes.
© Copyright. All rights reserved.
39
Unit 1: Introduction
Animation: Steps to Transition ABAP Code for SAP HANA
For more information on Steps to Transition ABAP Code for SAP HANA, please
view the animation in the lesson ABAP and SAP HANA, online in the SAP
Learning Hub.
A New Programming Approach
Figure 45: New Programming Approach
The arrival of in-memory technology on the database layer also requires a change in the way
we design and implement applications.
The basic approach of classic ABAP programming was as follows:
Keep the load from the database.
Get all the data you need on the application server.
Do your processing in ABAP.
In order to benefit the most from SAP HANA's capabilities, it is better to do expensive
calculations and aggregations on the database itself, rather than transferring huge amounts
of data onto the ABAP application server. This is a fundamental change to the ABAP
programming paradigm. It is very often referred to as “Code-to-Data” as opposed to the
classic “Data-to-Code” approach.
Bottom-Up Approach for Code-to-Data
One way of approaching the code-to-data paradigm is to use native SQL to access SAP
HANA-specific functionality, such as built-in functions. Encoding all computations in native
SQL statements has a drawback, however, in that you have to get the SQL statements right,
for example the join conditions, the built-in functions, and so on. In addition, encoding
everything in native SQL statements makes reusing parts of the computations difficult.
40
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Bottom-Up Approach with Direct Access to SAP HANA Artefacts (Native SQL)
Figure 46: Possible Approaches with AS ABAP < 7.4 SP02
An alternative approach makes use of the fact that SAP HANA provides advanced view
modeling capabilities through SAP HANA column views. Modeling such views leads to more
reusable results and requires less programming.
If the computations are too complex to be modeled using SAP HANA views, using database
procedures implemented in SAP HANA SQL script is another alternative.
Both options can be interpreted as bottom-up approaches, because you first model and
respectively implement an artefact on the SAP HANA layer, and then call the existing SAP
HANA artefact in ABAP. In ABAP releases below ABAP 7.4 SP02, or in scenarios with SAP
HANA as secondary database, such calls always require using native SQL.
© Copyright. All rights reserved.
41
Unit 1: Introduction
Bottom-Up Approach with Proxy Objects
Figure 47: Bottom-Up Approach with AS ABAP 7.4 ≥ SP02
Starting with ABAP 7.4 SP02, ABAP provides new repository objects to simplify the bottomup approach. These new objects are created in the ABAP repository as representatives or
proxy objects for the objects created on SAP HANA. Access to the proxy objects does not
require the use of native SQL.
You can use existing SAP HANA artefacts natively in ABAP by doing the following:
●
●
Create so-called external views in the ABAP Dictionary to represent native SAP HANA
column views.
Create so-called database procedure proxies in the ABAP Dictionary to represent SAP
HANA native database procedures.
There is also a proxy object for SAP HANA delivery units, the so-called SAP HANA Transport
Container. It helps to synchronize the otherwise separated lifecycle managements of ABAP
objects and SAP HANA artefacts.
Caution:
Creating database procedure proxies is not recommended. It is covered in the
course only in case you encounter such proxies in your ABAP system.
42
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
Top-Down-Approach for Code-to-Data
Figure 48: Top-Down Approach with AS ABAP 7.4 SP05
Since release 7.40 SP05, ABAP provides additional capabilities to support the code-to-data
paradigm. This new approach can be called the top-down approach. Compared to the
bottom-up approach, the ABAP stack manages all entities and deploys all artefacts from the
ABAP layer into the database.
Figure 49: Code to Data Capabilities in ABAP7_4
Using SAP HANA-specific features is improved by introducing a new concept called ABAPManaged Database Procedures.
A database-oriented programming model is supported better through the following:
●
An advanced Open SQL, supporting more of the SQL-92 standard
© Copyright. All rights reserved.
43
Unit 1: Introduction
●
New capabilities for defining views using a common set of domain-specific languages and
services for defining and consuming semantically rich data models called Core Data
Services
Transparent optimizations are improvements in the ABAP stack itself. Your code directly
benefits from this without any adjustments. The following are examples of transparent
optimizations:
●
Fast Data Access, a new data exchange protocol between the ABAP stack and the
database
●
Optimizations of SELECT ... INTO ITAB and of SELECT SINGLE
●
Optimizations of SELECT ... FOR ALL ENTRIES
Animation: Code to Data Capabilities in ABAP7_4
For more information on Code to Data Capabilities in ABAP7_4, please view the
animation in the lesson ABAP and SAP HANA, online in the SAP Learning Hub.
Performance Improvement Versus Code Adjustments
Figure 51: Performance Improvement Versus Code Adjustments
The different code-to-data options correlate with the potential gain in performance. However,
the complexity of the resulting code may also increase as more code is moved to the
database or made database-specific, as follows:
●
●
44
Transparent optimizations in principle improve performance without any code
adjustments. Some code adjustments may be necessary while migrating to SAP HANA,
however, to profit from the adjustments.
Using enhanced Open SQL and the advanced view definition capabilities, you can create
new data models and consume them in ABAP, thereby improving the productivity and
performance without database-specific artefacts.
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
●
Using native database features may be necessary to achieve the best performance, but
the code adjustment effort might increase.
Animation: Performance Improvement Versus Code Adjustments
For more information on Performance Improvement Versus Code Adjustments,
please view the animation in the lesson ABAP and SAP HANA, online in the SAP
Learning Hub.
© Copyright. All rights reserved.
45
Unit 1: Introduction
46
© Copyright. All rights reserved.
Unit 1
Exercise 3
Analyze SAP HANA-specific settings in ABAP
Dictionary
Simulation: Analyze SAP HANA-specific settings in ABAP Dictionary
For more information on Analyze SAP HANA-specific settings in ABAP
Dictionary, please view the simulation in the lesson ABAP and SAP HANA online
in the SAP Learning Hub.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Analyze Transparent Table SBOOK
On application server T8N, which uses SAP HANA as a primary database, analyze the DBspecific settings and secondary indexes of transparent table SBOOK.
1. If you are not already logged on, log on to system T8N, which uses SAP HANA as its
primary database.
2. In the Object Browser (transaction SE80), open the definition of transparent table SBOOK.
3. Open the DB-specific properties of this transparent table.
Which of SAP HANA's table storage types is used for table SBOOK?
4. Inspect the secondary indexes defined for transparent table SBOOK.
How many secondary indexes are defined for transparent table SBOOK?
© Copyright. All rights reserved.
47
Unit 1: Introduction
Which of the indexes are generated when the ABAP system is deployed on an SAP HANA
database, and which are not created on SAP HANA?
48
© Copyright. All rights reserved.
Unit 1
Solution 3
Analyze SAP HANA-specific settings in ABAP
Dictionary
Simulation: Analyze SAP HANA-specific settings in ABAP Dictionary
For more information on Analyze SAP HANA-specific settings in ABAP
Dictionary, please view the simulation in the lesson ABAP and SAP HANA online
in the SAP Learning Hub.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Analyze Transparent Table SBOOK
On application server T8N, which uses SAP HANA as a primary database, analyze the DBspecific settings and secondary indexes of transparent table SBOOK.
1. If you are not already logged on, log on to system T8N, which uses SAP HANA as its
primary database.
a) Perform this step as in previous exercises.
2. In the Object Browser (transaction SE80), open the definition of transparent table SBOOK.
a) Choose Edit Object or press Shift + F5, enter the name of the table definition and
double-click Database Table in the following dialog box.
3. Open the DB-specific properties of this transparent table.
a) Open Technical Settings and go to the DB-Specific Properties tab.
Which of SAP HANA's table storage types is used for table SBOOK?
The storage type is Column Store.
4. Inspect the secondary indexes defined for transparent table SBOOK.
a) Return to Display Table, then open Indexes.
How many secondary indexes are defined for transparent table SBOOK?
Two secondary indexes are defined for transparent table SBOOK.
© Copyright. All rights reserved.
49
Unit 1: Introduction
Which of the indexes are generated when the ABAP system is deployed on an SAP HANA
database, and which are not created on SAP HANA?
None of the secondary indexes are created if the ABAP system runs on SAP HANA, but
they are created on all other supported databases.
50
© Copyright. All rights reserved.
Lesson: ABAP and SAP HANA
LESSON SUMMARY
You should now be able to:
●
Explain the SAP HANA and ABAP evolution
●
Indentify SAP HANA-specific settings in ABAP Dictionary
●
Describe the various code-to-data concepts
© Copyright. All rights reserved.
51
Unit 1
Lesson 4
Introducing the ABAP Development Tools
(ADT)
LESSON OVERVIEW
As an open framework, Eclipse can host a whole range of development tools. As well as the
SAP HANA studio environment, SAP also provides a suite of tools known as the ABAP
Development Tools. These enable you to develop ABAP resources using Eclipse as a frontend development environment.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Work with ABAP Development Tools
Knowing ABAP Development Tools
Figure 54: ABAP Development Tools for SAP NetWeaver – Architecture
52
© Copyright. All rights reserved.
Lesson: Introducing the ABAP Development Tools (ADT)
ABAP Development Tools provides the following:
●
A brand new ABAP development experience on top of the Eclipse platform
●
An open platform for developing new ABAP-related tools
●
A set of open, language and platform-independent APIs that developers can use to build
new custom tools for the ABAP environment
Benefits of Eclipse
With ABAP Development Tools in Eclipse you benefit from the usability, speed, and flexibility
of Eclipse, while also benefitting from proven ABAP Workbench features.
ABAP Development Tools improves developer productivity by offering better refactoring
functionality, code completion, auto-insertion, and code templates. It also includes an
invaluable Quick Fix feature and is highly navigable.
ABAP Development Tools allows you to connect to multiple ABAP systems and provides
session failover, reducing the impact of lost connections. It also enables cross-platform
development by integrating ABAP and non-ABAP development tools in a single, powerful
integrated development environment (IDE).
Note:
In addition, ABAP Development Tools is tightly integrated with SAP HANA studio,
SAP UI5 tools, and Java.
The architecture of ABAP Development Tools for SAP NetWeaver is an architecture designed
for ease of use and flexibility. It is designed to allow developers to use a single Eclipse client,
installed locally, that connects to several ABAP back-end systems of different releases using a
Remote Function Call (RFC)/Representational State Transfer (REST)-based protocol.
This allows developers to control all activities in a central location and helps avoid timeconsuming context switches. The client provides a set of standard Eclipse development tools,
such as the project explorer for system browsing and search views.
When you use ABAP Development Tools, you log on to an SAP back-end system and work
directly with its repository objects. In this sense, the development process is exactly the same
as when you use the ABAP Workbench, in that there is no check-out and check-in of the
objects. Each connection that you make is represented in Eclipse by an ABAP project.
An ABAP project serves as the container for the development objects that are stored in the
particular ABAP back-end system containing the logon parameters for a particular system
logon, such as the following:
●
System
●
Client
●
User and language
You must be logged on to the system in order to edit a particular resource. Within the project,
you can access any development object in the repository. However, to make it easier to
manage the objects you use regularly, you can set up favorite packages for each project.
Within the project, there is a navigation view similar to the one in the ABAP Workbench. The
source library contains not only programs, but also classes, interfaces, and function modules,
which you edit in a source code editor rather than in the traditional form-based mode.
© Copyright. All rights reserved.
53
Unit 1: Introduction
Note:
You can create multiple ABAP projects in Eclipse, each related to a different
system.
Figure 55: ABAP Development Tools – Editors
There are two kinds of editors in ABAP Development Tools – those for which there is a native
Eclipse implementation and those that appear in-place in the SAP GUI. The figure, ABAP
Development Tools – Editors, shows each kind – the ABAP Editor as an example of an Eclipse
editor and the ABAP Dictionary showing how the classic SAP GUI visualization appears within
the Eclipse environment.
Generally speaking, there is no requirement to use ABAP Development Tools for ABAP
development, and each developer is free to choose whether to use ABAP Development Tools
or the classic ABAP Workbench. The functions and features of Eclipse in general and ABAP
Development Tools in particular lend themselves particularly well to object-oriented
programming, with various built-in refactoring functions and support for unit testing. There
are other tasks to which the ABAP Workbench is better suited, in particular working with
module pools and the Screen Painter.
Some new functions, however, are only provided within ABAP Development Tools, and do not
have an equivalent function in the ABAP Workbench. Several of these pertain to ABAP
development for SAP HANA.
54
© Copyright. All rights reserved.
Lesson: Introducing the ABAP Development Tools (ADT)
Working with ABAP Development Tools
Figure 56: ABAP Project
Editing ABAP Code
Figure 57: Editing Source Code
The source code editor in ABAP Development Tools provides many helpful features, such as
the following:
●
Code completion, which includes keyword completion, using code templates for
completion and Content Assist to suggest completions for variable names, method names,
and so on, while typing.
© Copyright. All rights reserved.
55
Unit 1: Introduction
●
Quick Fix, which allows you to quickly resolve errors or warnings reported about the code.
There are many quick fixes available for ABAP, such as the following:
-
Creating method implementations from the method definition
-
Creating method definitions from implementation parts
-
Creating implementation parts for interface methods
-
Creating method definitions from method calls
-
Creating ABAP classes or ABAP interfaces from the source code
For a complete list, check the documentation.
Figure 58: ABAP Development Tools Quick Reference Card
ABAP Development Tools provides a large number of keyboard shortcuts that can make you
more productive. You can download a quick reference card with the most important shortcuts
from the following SCN page: https://blogs.sap.com/2012/07/02/adt-quick-referencecard/.
Examples of keyboard shortcuts ABAP developers new to ABAP Development Tools often do
not find quickly are as follows:
●
●
●
56
Shift + F1 to format the source code, that is, use the Pretty Printer
Ctrl + < and Ctrl + > to turn a line of code into a comment or to remove a comment, or Ctrl
+ 7 to toggle between commenting/de-commenting a line
F3 to navigate to the definition of the currently selected object (forward navigation).
Pressing the Ctrl key while positioning the mouse over an object, such as a class or method
name, adds a link and allows you to navigate to the definition or implementation of the
object.
© Copyright. All rights reserved.
Lesson: Introducing the ABAP Development Tools (ADT)
Debugging ABAP Code
Figure 59: Troubleshooting Tools – ABAP Debugger in Eclipse
The latest ABAP Debugger is completely integrated into the Eclipse debug framework.
Although it is an ABAP debugger, it behaves like all other debuggers in Eclipse you might be
familiar with because the look, feel, and functionality are all Eclipse. In other words, you can
now debug your reports, transactions, classes, Web Dynpro applications, and so on, natively
in Eclipse.
The ABAP Debugger in the ABAP Development Tools can satisfy most of your debugging
requirements. For special purposes – other than observing running code – you may still want
to use the new ABAP Debugger in the SAP GUI.
Note:
The Run → Debug menu function in Eclipse is not enabled in the ABAP
perspective.
You start the debugger by setting a breakpoint in your code and then running the ABAP
program. You can start it directly with F8.
The debugger offers, among other features, editing in the debugger. You can correct a bug
when you find it. Debugging in the IDE is not supported if you are working with a 7.0 EHP3
back-end system. For more information, find the latest information on the SAP Service
Marketplace.
© Copyright. All rights reserved.
57
Unit 1: Introduction
Information Sources
Figure 60: Information Sources
If you want to get a local installation of the SAP Development Tools for Eclipse, there are
several sources you can choose from, such as the following:
●
●
The SAP Software Download Center: https://support.sap.com/en/my-support/softwaredownloads.html, part of the SAP Support Portal.
The SAP Development Tools for Eclipse Web site: http://tools.hana.ondemand.com
You can also find other products like the SAP HANA studio or the tools for SAP UI5
development via this site. It describes how to install or update the SAP Development Tools for
Eclipse using the SAP Development Tools for Eclipse update Web site.
Hint:
For more information, see the following SAP Community Network page: https://
www.sap.com/community/topic/abap.html and documentation and support on
how to install the SAP Development Tools for Eclipse.
58
© Copyright. All rights reserved.
Unit 1
Exercise 4
Create a Project in ABAP Development Tools
Simulation: Create a Project in ABAP Development Tools
For more information on Create a Project in ABAP Development Tools, please
view the simulation in the lesson Introducing the ABAP Development Tools (ADT)
online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Create a Project in ABAP Development Tools
Open ABAP Development Tools and create a project for the application server T8N, which
uses SAP HANA as its primary database. Add your development package ZHA400_## and
development package HA400_PRIMDB_EXERCISE to the favorites of this project.
1. Open ABAP Development Tools (that is, the ABAP perspective in Eclipse).
2. Create a project connected to system T8N, which uses SAP HANA as its primary
database. Use the user ID and password provided by your instructor.
3. Add your package ZHA400_## as a favorite under your project.
4. Add package HA400_PRIMDB_EXERCISE to the favorites of this project.
5. Optionally, if you also want to use ABAP Development Tools for the exercises performed in
system ZME, which uses Sybase as its primary database, create a second ABAP project
that is connected to this system. Add your own package ZHA400_## and the package
HA400_SECDB_EXERCISE as favorite packages to this project.
© Copyright. All rights reserved.
59
Unit 1
Solution 4
Create a Project in ABAP Development Tools
Simulation: Create a Project in ABAP Development Tools
For more information on Create a Project in ABAP Development Tools, please
view the simulation in the lesson Introducing the ABAP Development Tools (ADT)
online in the SAP Learning Hub.
Business Example
Your company has identified SAP HANA as an important strategic topic and has asked you to
refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
Create a Project in ABAP Development Tools
Open ABAP Development Tools and create a project for the application server T8N, which
uses SAP HANA as its primary database. Add your development package ZHA400_## and
development package HA400_PRIMDB_EXERCISE to the favorites of this project.
1. Open ABAP Development Tools (that is, the ABAP perspective in Eclipse).
a) If you have not opened Eclipse Jee 2018-12, yet, do so now. Choose Eclipse Jee 2018-12
from the task bar of the Windows Terminal Server.
b) If the Welcome page is open, close it or choose the Workbench link.
c) Change to the ABAP perspective using the button in the upper right-hand corner.
2. Create a project connected to system T8N, which uses SAP HANA as its primary
database. Use the user ID and password provided by your instructor.
a) Right-click anywhere in the Project Explorer window on the left and choose
New → ABAP Project.
b) Choose the Browse button and choose system ID T8N.
c) Choose OK, followed by Next >.
d) Enter client 001, your user, and your password.
e) Choose Finish.
3. Add your package ZHA400_## as a favorite under your project.
a) In the Project Explorer, right-click Favorite Packages under your project and choose
Add a Package....
b) Enter the name of your own package and choose OK.
4. Add package HA400_PRIMDB_EXERCISE to the favorites of this project.
60
© Copyright. All rights reserved.
Lesson: Introducing the ABAP Development Tools (ADT)
a) In the Project Explorer, right-click Favorite Packages under your project and choose
Add a Package....
b) Enter package name HA400_PRIMDB_EXERCISE and choose OK.
5. Optionally, if you also want to use ABAP Development Tools for the exercises performed in
system ZME, which uses Sybase as its primary database, create a second ABAP project
that is connected to this system. Add your own package ZHA400_## and the package
HA400_SECDB_EXERCISE as favorite packages to this project.
a) Repeat the actions of previous steps with the appropriate adjustments to the package
names.
© Copyright. All rights reserved.
61
Unit 1: Introduction
LESSON SUMMARY
You should now be able to:
●
62
Work with ABAP Development Tools
© Copyright. All rights reserved.
Unit 1
Learning Assessment
1. Which of the following SAP HANA-based scenarios involve ABAP applications?
Choose the correct answers.
X
A Data marts based on SAP HANA
X
B AS ABAP with SAP HANA as primary database
X
C Native SAP HANA applications
X
D SAP HANA as Business Accelerator
2. On SAP HANA, tables are stored in row store by default.
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following entries are required when creating a system in the SAP HANA
Studio?
Choose the correct answers.
X
A Host name
X
B Instance number
X
C Client ID
X
D User name
X
E Logon Language
© Copyright. All rights reserved.
63
Unit 1: Learning Assessment
4. Which of the following entities can be found under the Catalog node, and not under the
Content node?
Choose the correct answers.
X
A Package
X
B Schema
X
C Table
X
D Calculation View
5. It is not possible to create secondary indexes on SAP HANA.
Determine whether this statement is true or false.
X
True
X
False
6. Which of the following new repository objects belong to the so-called “Top-Down
Approach” for Code-to-Data?
Choose the correct answers.
X
A External view
X
B CDS view
X
C Database procedure proxy
X
D ABAP-managed database procedure
7. Which of the following are benefits of ABAP Development Tools in Eclipse?
Choose the correct answers.
64
X
A Improved usability, speed, and flexibility of Eclipse
X
B Improved native SAP HANA applications
X
C Improved developer productivity due to betterment in refracting functionality,
code completion, auto-insertion, and code templates
X
D Improved Database Procedure Proxy
© Copyright. All rights reserved.
UNIT 2
Taking ABAP to SAP HANA
Lesson 1
SAP HANA as Secondary Database– Access via Open SQL
Exercise 5: Access SAP HANA Via a Secondary Database Connection
67
71
Lesson 2
Code Checks to Prepare ABAP Code for SAP HANA
Exercise 6: Search for Potential Functional Issues with Code Inspector
81
87
Lesson 3
Tools to Analyse Potential Performance Issues
Exercise 7: Analyze Potential Performance Issues
96
103
Lesson 4
Guided Performance Analysis
Exercise 8: Perform a Structured SQL Performance Analysis
115
121
Lesson 5
SQL Performance Rules for SAP HANA
131
UNIT OBJECTIVES
●
Access a secondary database via Open SQL
●
Use Code Inspector and ABAP Test Cockpit
●
Understand the Runtime Check Monitor
●
Understand the reason for potential performance issues
●
Use analysis tools to measure and compare runtime consumption
●
Search for potential performance issues with Code Inspector and ABAP Test Cockpit
●
Use SQL Trace (ST05) for in-depth analysis of database accesses
●
Understand the SQL Monitor (SQLM)
●
Use the Performance Tuning Worklist (SWLT)
© Copyright. All rights reserved.
65
Unit 2: Taking ABAP to SAP HANA
●
66
Know the performance rules and guidelines for SAP HANA
© Copyright. All rights reserved.
Unit 2
Lesson 1
SAP HANA as Secondary Database– Access
via Open SQL
LESSON OVERVIEW
In this lesson, you learn how to access the SAP HANA database by using Open SQL and a
secondary database connection.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Access a secondary database via Open SQL
Secondary Database Connections
Each Application Server ABAP is connected to a database management system (DBMS) that
contains the ABAP Repository and the database tables and views defined in this system's
ABAP Dictionary. This DBMS is referred to as its primary database. Aside from this primary
database connection, it is possible to establish connections to additional database
management systems or secondary database connections. In the scenario, SAP HANA as
Accelerator, where SAP HANA is used as a secondary DBMS, it is necessary to establish such
a secondary database connection to SAP HANA.
Secondary database connections, among other things, are created and maintained via
transaction DBACOCKPIT. Each database connection is identified by a name that must be
unique within the application server.
© Copyright. All rights reserved.
67
Unit 2: Taking ABAP to SAP HANA
Figure 62: Transaction DBACOCKPIT
Figure 63: Database Connection Details
Inside the connection, the DBMS is identified by a hostname and an instance number, which
relates to an SQL port. Furthermore, a database user (with password) has to be maintained.
Any access to the database via this secondary database connection is equivalent to a log on
to the database with this user.
68
© Copyright. All rights reserved.
Lesson: SAP HANA as Secondary Database– Access via Open SQL
Access to a Secondary Database with Open SQL
Once the secondary database connection is established, it is easy to use it in ABAP programs.
Open SQL offers an additional CONNECTION, which has to be followed by the name of the
secondary database connection.
Figure 64: Open SQL Using Secondary Database Connection
However, some restrictions apply when using Open SQL to access a secondary database.
Figure 65: Open SQL Using Secondary Database Connection Restrictions
Animation: Open SQL Using Secondary Database Connection Restrictions
For more information on Open SQL Using Secondary Database Connection
Restrictions, please view the animation in the lesson SAP HANA as Secondary
Database– Access via Open SQL, online in the SAP Learning Hub.
Due to the syntax check for Open SQL statements, the tables and fields the statement refers
to must exist in the ABAP Dictionary of the application server.
© Copyright. All rights reserved.
69
Unit 2: Taking ABAP to SAP HANA
This implies that objects only known to SAP HANA (such as SAP HANA views or procedures)
are not accessible by Open SQL.
Note:
We learn later in this course that in order to access these objects, either native
SQL has to be used or new objects have to be created in the ABAP Dictionary that
make the SAP HANA objects visible for the syntax check.
Finally, Open SQL access to a secondary database is restricted to the default schema of the
database user in the connection. Normally, the name of this schema is identical to the user
name.
70
© Copyright. All rights reserved.
Unit 2
Exercise 5
Access SAP HANA Via a Secondary Database
Connection
Simulation: Access SAP HANA Via a Secondary Database Connection
For more information on Access SAP HANA Via a Secondary Database
Connection, please view the simulation in the lesson SAP HANA as Secondary
Database– Access via Open SQL online in the SAP Learning Hub.
Business Example
You have an ABAP program that does not perform well in your ABAP system running on a
database different than SAP HANA. You want to adjust this program to use an SAP HANA
database as a secondary database, in preparation for further performance improvements
using SAP HANA.
Template:
Report HA400_SEC_DB_CON_T1
Solution:
Report HA400_SEC_DB_CON_S1
Task 1: Copy and Understand Templates
In SAP GUI, log on to system ZME, which uses Sybase as its primary database, and start the
ABAP Workbench. Create a copy of report HA400_SEC_DB_CON_T1 in your package
ZHA400_## (suggested name: ZHA400_##_SEC_DB_1, where ## is your group number).
Analyze the program code to get an idea of its functionality. Activate and execute the
program.
1. If you are not still logged in, log on to the system labelled ZME on Sybase and start the
ABAP workbench (transaction SE80).
2. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench request.
Hint:
Make sure to mark Screens and User Interface in the Copy Program dialog
step.
© Copyright. All rights reserved.
71
Unit 2: Taking ABAP to SAP HANA
3. Analyze the source code of the program. 1. Which are the two main parts of the data
processing? 2. In which processing blocks are they encapsulated?
4. The data comes from database tables ___________(1) and ___________(2). All columns but
one come from database table ___________(3). The remaining column is the result of a
calculation. As input, this calculation uses two fields of table ___________(4). These fields
are___________(5) and ___________(6). The calculated column returns the
_____________________________________________________(7).
5. Activate the program.
Task 2: Analyze a Secondary Database Connection
Look for a secondary database connection that points to the SAP HANA server. Find out
which tables can be accessed with Open SQL via this connection.
1. Look up the secondary database connections that have been maintained in your SAP
NetWeaver Application Server for ABAP.
Note:
You do not need to change anything.
2. Find a database connection that points to your SAP HANA server and note the database
user and connection name.
3. The connection name is __________(1) and the database user for the SAP HANA server is
__________(2).
4. Go to the SAP HANA Modeler perspective in Eclipse and open the schema with the same
name as the user in the database connection.
5. Look for the tables you find in this schema. Those are the ones you can access via the
secondary database connection using Open SQL.
Hint:
Tables starting with DD0 and RS_ are technical objects and should not be
considered here. They are used by the mechanism that replicates data from
primary to secondary databases. Tables starting with SNWD belong to the
Enterprise Procurement model which is not used in this training.
72
© Copyright. All rights reserved.
Lesson: SAP HANA as Secondary Database– Access via Open SQL
6. Which tables are of interest to the application programmer?
7. Verify for at least one table that the definition in the SAP HANA database is identical to the
definition in the primary database.
Task 3: Access SAP HANA
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, make sure all SELECT-statements read
from SAP HANA instead of the primary database.
In all select statements of subroutine get_data_solution, read from SAP HANA rather than the
primary database.
1. Edit your program ZHA400_##_SEC_DB_1. Copy the source code of subroutine
get_data_template to subroutine get_data_solution.
2. In subroutine get_data_solution, search for all SELECT-statements and use the
CONNECTION addition to access the secondary database rather than the primary
database.
Hint:
Instead of hard coding the connection, it is recommended that you define a
constant of type dbcon_name (ABAP Dictionary data element).
3. Activate and test your program.
© Copyright. All rights reserved.
73
Unit 2
Solution 5
Access SAP HANA Via a Secondary Database
Connection
Simulation: Access SAP HANA Via a Secondary Database Connection
For more information on Access SAP HANA Via a Secondary Database
Connection, please view the simulation in the lesson SAP HANA as Secondary
Database– Access via Open SQL online in the SAP Learning Hub.
Business Example
You have an ABAP program that does not perform well in your ABAP system running on a
database different than SAP HANA. You want to adjust this program to use an SAP HANA
database as a secondary database, in preparation for further performance improvements
using SAP HANA.
Template:
Report HA400_SEC_DB_CON_T1
Solution:
Report HA400_SEC_DB_CON_S1
Task 1: Copy and Understand Templates
In SAP GUI, log on to system ZME, which uses Sybase as its primary database, and start the
ABAP Workbench. Create a copy of report HA400_SEC_DB_CON_T1 in your package
ZHA400_## (suggested name: ZHA400_##_SEC_DB_1, where ## is your group number).
Analyze the program code to get an idea of its functionality. Activate and execute the
program.
1. If you are not still logged in, log on to the system labelled ZME on Sybase and start the
ABAP workbench (transaction SE80).
a) Perform this step as in previous exercises.
2. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench request.
Hint:
Make sure to mark Screens and User Interface in the Copy Program dialog
step.
a) Start the ABAP Workbench (for example, using transaction code SE80).
74
© Copyright. All rights reserved.
Lesson: SAP HANA as Secondary Database– Access via Open SQL
b) In the toolbar, choose Edit Object ... (Shift-F5).
c) Enter development object HA400_SEC_DB_CON_T1.
d) Choose Copy (CTRL-F5).
e) Enter the target program name, ZHA400_##_SEC_DB_1, where ## is your group
number, and choose Copy.
f) Select User interface and Screens and choose Copy.
g) Enter the name of your package and press Enter.
h) Choose your workbench request and press Enter.
3. Analyze the source code of the program. 1. Which are the two main parts of the data
processing? 2. In which processing blocks are they encapsulated?
1. Reading from the database and computing a list of customers; subroutine
get_data_template, 2. Displaying the list of customers; subroutine display.
4. The data comes from database tables ___________(1) and ___________(2). All columns but
one come from database table ___________(3). The remaining column is the result of a
calculation. As input, this calculation uses two fields of table ___________(4). These fields
are___________(5) and ___________(6). The calculated column returns the
_____________________________________________________(7).
(1) SCUSTOM, (2) SBOOK, (3) SCUSTOM, (4) SBOOK, (5) ORDER_DATE, (6) FLDATE, (7)
average number of days between booking date and flight date
5. Activate the program.
a) Complete this step as you learned to do in previous classes, in other words, choose the
Activate button.
Task 2: Analyze a Secondary Database Connection
Look for a secondary database connection that points to the SAP HANA server. Find out
which tables can be accessed with Open SQL via this connection.
1. Look up the secondary database connections that have been maintained in your SAP
NetWeaver Application Server for ABAP.
Note:
You do not need to change anything.
a) Start transaction DBACOCKPIT.
b) In the navigation area on the left, choose Database Connections.
2. Find a database connection that points to your SAP HANA server and note the database
user and connection name.
a) To find all database connections that point to an SAP HANA database, in the list on the
right, expand the SAP HANA database node.
b) Find the connection with the correct server in the DB Host column.
© Copyright. All rights reserved.
75
Unit 2: Taking ABAP to SAP HANA
3. The connection name is __________(1) and the database user for the SAP HANA server is
__________(2).
(1) HANADB, (2) REPZME
4. Go to the SAP HANA Modeler perspective in Eclipse and open the schema with the same
name as the user in the database connection.
a) In Eclipse, open perspective SAP HANA Modeler.
b) In the navigation window on the left, choose Catalog → REPZME.
5. Look for the tables you find in this schema. Those are the ones you can access via the
secondary database connection using Open SQL.
Hint:
Tables starting with DD0 and RS_ are technical objects and should not be
considered here. They are used by the mechanism that replicates data from
primary to secondary databases. Tables starting with SNWD belong to the
Enterprise Procurement model which is not used in this training.
a) Under the REPZME schema, expand the tables node.
6. Which tables are of interest to the application programmer?
MARA, SBOOK, SCARR, SCUSTOM, SFLIGHT, SPFLI, STRAVELAG
7. Verify for at least one table that the definition in the SAP HANA database is identical to the
definition in the primary database.
a) To see the list of fields, double-click one of the tables, their SQL data types, and
dimensions.
b) On the SAP NetWeaver Application Server for ABAP, open the definition of this table in
the ABAP Dictionary (transaction SE11 or SE80).
c) To see the definition of this table on the primary database, from the menu, choose
Utilities → Database Object → Display.
Task 3: Access SAP HANA
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, make sure all SELECT-statements read
from SAP HANA instead of the primary database.
In all select statements of subroutine get_data_solution, read from SAP HANA rather than the
primary database.
1. Edit your program ZHA400_##_SEC_DB_1. Copy the source code of subroutine
get_data_template to subroutine get_data_solution.
a) Use the Copy & Paste functions of the ABAP Editor to copy the source code of
subroutine get_data_template to subroutine get_data_solution.
2. In subroutine get_data_solution, search for all SELECT-statements and use the
CONNECTION addition to access the secondary database rather than the primary
database.
76
© Copyright. All rights reserved.
Lesson: SAP HANA as Secondary Database– Access via Open SQL
Hint:
Instead of hard coding the connection, it is recommended that you define a
constant of type dbcon_name (ABAP Dictionary data element).
a) See the source code extract from the model solution.
3. Activate and test your program.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_SEC_DB_CON_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: ls_scustom TYPE scustom,
ls_sbook
TYPE sbook.
* help variables
DATA lv_count TYPE i.
* Processing
*****************
CLEAR ct_customers.
SELECT * FROM scustom
INTO ls_scustom.
ls_customer-id
= ls_scustom-id.
ls_customer-name
= ls_scustom-name.
ls_customer-postcode = ls_scustom-postcode.
ls_customer-city
= ls_scustom-city.
ls_customer-country = ls_scustom-country.
CLEAR ls_customer-days_ahead.
CLEAR lv_count.
SELECT * FROM sbook
INTO ls_sbook
WHERE customid = ls_scustom-id
AND cancelled = space.
ls_customer-days_ahead = ls_customer-days_ahead
+ ( ls_sbook-fldate
© Copyright. All rights reserved.
77
Unit 2: Taking ABAP to SAP HANA
- ls_sbook-order_date ).
lv_count = lv_count + 1.
ENDSELECT.
IF lv_count <> 0.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
INSERT ls_customer INTO TABLE ct_customers.
ENDIF.
ENDSELECT.
SORT ct_customers BY id.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Database connection
CONSTANTS lc_con TYPE dbcon_name VALUE 'HANADB'.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: ls_scustom TYPE scustom,
ls_sbook
TYPE sbook.
* help variables
DATA lv_count TYPE i.
* Processing
*****************
CLEAR ct_customers.
SELECT * FROM scustom
CONNECTION (lc_con)
INTO ls_scustom.
ls_customer-id
= ls_scustom-id.
ls_customer-name
= ls_scustom-name.
ls_customer-postcode = ls_scustom-postcode.
ls_customer-city
= ls_scustom-city.
ls_customer-country = ls_scustom-country.
CLEAR ls_customer-days_ahead.
CLEAR lv_count.
SELECT * FROM sbook
CONNECTION (lc_con)
INTO ls_sbook
WHERE customid = ls_scustom-id
AND cancelled = space.
78
© Copyright. All rights reserved.
Lesson: SAP HANA as Secondary Database– Access via Open SQL
ls_customer-days_ahead = ls_customer-days_ahead
+ ( ls_sbook-fldate
- ls_sbook-order_date ).
lv_count = lv_count + 1.
ENDSELECT.
IF lv_count <> 0.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
INSERT ls_customer INTO TABLE ct_customers.
ENDIF.
ENDSELECT.
SORT ct_customers BY id.
ENDFORM.
© Copyright. All rights reserved.
"
79
Unit 2: Taking ABAP to SAP HANA
LESSON SUMMARY
You should now be able to:
●
80
Access a secondary database via Open SQL
© Copyright. All rights reserved.
Unit 2
Lesson 2
Code Checks to Prepare ABAP Code for SAP
HANA
LESSON OVERVIEW
This lesson introduces some tools to analyze potential functional and performance issues in
ABAP programs when migrating to SAP HANA.
Business Example
You want to run existing ABAP code on SAP HANA. You heard of functional issues and
performance problems that might occur. You want to analyze whether this is the case and
what you can do to make your coding SAP HANA-ready.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use Code Inspector and ABAP Test Cockpit
●
Understand the Runtime Check Monitor
Considerations Before Migrating to SAP HANA
ABAP Developer’s Questions: SAP HANA Impact on Custom ABAP Code
●
●
●
●
Which of my ABAP code must be changed to avoid potential functional issues when
migrating to SAP HANA?
Which of my ABAP code shall be optimized to ensure good performance?
Which of my main business processes have potential for SAP HANA so that I can speed
those up massively?
How can I find all this ABAP code easily and do the adaption efficiently?
Most likely, you use SAP HANA because you want to improve the performance of your ABAP
applications. If you consider fully migrating to SAP HANA, you may also ask how to prepare
your ABAP code to avoid functional issues after the migration, and to what extent you have to
rewrite ABAP code.
SAP tools and guidelines help with these issues, and enable you to get your custom code
ready and optimized for SAP HANA.
For more information about the details, see OSS note 1785057.
© Copyright. All rights reserved.
81
Unit 2: Taking ABAP to SAP HANA
Potential Functional Issues
Figure 68: Potential Functional Issues: Native SQL and DB Hints
Standard ABAP code is fully portable between different database types. However, it is also
possible to use database-specific features explicitly or implicitly. In such situations, the code
has to be revisited when migrating to SAP HANA.
Animation: Potential Functional Issues: Native SQL and DB Hints
For more information on Potential Functional Issues: Native SQL and DB Hints,
please view the animation in the lesson Code Checks to Prepare ABAP Code for
SAP HANA, online in the SAP Learning Hub.
Some concrete scenarios are as follows:
●
●
82
If ABAP code uses native SQL (for example, via EXEC SQL), this code must be checked
and adapted.
A second example are hints to the database, respectively the database interface. These
enable optimization of query execution for specific databases. In the example shown in the
figure, Potential Functional Issues: Native SQL and DB Hints, a specific behavior for
treating the SELECT statement is defined for SAP Sybase ASE database. Such hints are
ignored after a database migration, for example, to SAP HANA. In general, it should be
checked if a hint is still needed for the target database. In almost all cases, the default
behavior of SAP HANA should be sufficient.
© Copyright. All rights reserved.
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
Figure 70: Potential Functional Issues: Relying on Undocumented Behaviour
There are more subtle scenarios. Although Open SQL is database-independent, it is possible
to rely on unspecified behavior or internals.
If for example an ABAP program accesses physical clusters and pools, or depends explicitly
on the existence of a particular secondary index. Such cases must be checked and most likely
adapted before or after migration.
More common — and more difficult to identify — are scenarios where an existing ABAP
program relies on the fact that some databases tend to return the result of a certain SELECT
statements in a given sort order (for example, by primary key or by a secondary key) although
the statement does not include an ORDER BY clause.
But this behavior is neither documented nor guaranteed, and SAP HANA, with its internal data
processing specialities such as, for example, parallel processing and partitioning, is much
more likely to return the data in an arbitrary order than other databases.
For example, subtle problems can occur when accessing such a SELECT result with a READ
TABLE statement, using a BINARY SEARCH addition assuming a sorted table.
In principle, the following options exist to tackle this problem:
1. Use the ORDER BY addition in the SELECT statement.
2. Use a sorted table in the INTO clause of the SELECT statement.
3. Explicitly sort the internal table using the SORT statement.
4. Use an internal table with a sorted secondary key.
Code Inspector and ABAP Test Cockpit
Before migrating to SAP HANA, a static code analysis should be performed to identify
functional issues and potential impairments of performance.
© Copyright. All rights reserved.
83
Unit 2: Taking ABAP to SAP HANA
Figure 71: ABAP Code Inspector
With the ABAP Code Inspector you can perform a whole range of static functional and
performance checks.
Of course, the ABAP Code Inspector has been in use long before SAP HANA and most of the
checks are not SAP HANA-specific. The rules and guidelines checked by them are also valid
for any database.
However, since SAP NetWeaver 7.40, SAP continuously extended the range of available
checks, and some of the new checks are particularly important with regard to SAP HANA
(although they are valid for other databases, too). Many of these checks have been
downported into lower releases.
Code Inspector Checks to Search for Potential Functional Issues
Animation:
For more information on , please view the animation in the lesson Code Checks
to Prepare ABAP Code for SAP HANA, online in the SAP Learning Hub.
Critical Statements
Search for DB hints and native SQL (EXEC SQL ... ENDEXEC)
Use of ADBC Interface
Search for native SQL that is sent to the DB via the ADBC framework (see later in this
course)
Search DB Operations in Pool/Cluster Tables
Search for direct accesses to table pools and table clusters
Search problematic statements for result of SELECT/OpenCursor without ORDER BY
84
© Copyright. All rights reserved.
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
Search for statements that rely on implicit sorting of SELECT results
Find ABAP Statement Pattern
Search for an arbitrary pattern; use it with search string “CALL FUNCTION
'DB_EXISTS_INDEX' *”to find static usage of function module DB_EXISTS_INDEX.
All these checks have documentation available describing how the check works, and the
meaning of the check parameters that can be maintained.
Note:
In order to support customers during database migration, SAP shipped global
check variant FUNCTIONAL_DB that contains the checks listed above.
Inspection Results
The figure, Code Inspector – Inspection Results, shows an example of the inspection result,
where two of the new checks have resulted in an error message. Remember, you can doubleclick the message to navigate to the problem code.
Figure 72: Code Inspector – Inspection Results
© Copyright. All rights reserved.
85
Unit 2: Taking ABAP to SAP HANA
Code Inspector As a Part of ABAP Test Cockpit (ATC)
Figure 73: ABAP Test Cockpit
With ABAP 7.02, ABAP Test Cockpit (ATC) was introduced as a holistic quality assurance
tool. The ATC integrates the Code Inspector, including the configuration of Code Inspector
check variants. Compared to the stand-alone Code Inspector, ATC offers the following
additional functions:
●
Flexible scheduling of check runs
●
Distribution of results
●
General support for quality management processes
ATC is available in SAP GUI (transaction code ATC) but it is also integrated into ABAP
Development Tools and into SAP Solution Manager.
86
© Copyright. All rights reserved.
Unit 2
Exercise 6
Search for Potential Functional Issues with
Code Inspector
Simulation: Search for Potential Functional Issues with Code Inspector
For more information on Search for Potential Functional Issues with Code
Inspector, please view the simulation in the lesson Code Checks to Prepare
ABAP Code for SAP HANA online in the SAP Learning Hub.
Business Example
You have an ABAP program that you want migrate to a system with an SAP HANA database.
You want to perform a static code analysis to find potential functional issues that might occur
when executing the program on SAP HANA.
Template:
Report HA400_CODE_CHECK_T1
Solution:
Report HA400_CODE_CHECK_S1
Task 1: Copy and Understand the Template
Log on to the application server ZME on Sybase with system ID ZME. Create a copy of report
HA400_CODE_CHECK_T1 in your package ZHA400_## (suggested name:
ZHA400_##_CHECK_1, where ## is your group number). Activate and execute the program,
first on the primary database (Sybase ASE), then on the secondary database (SAP HANA).
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Activate and execute the program with the default settings.
What data does the report display?
3. Execute the program again, but this time let it read its data from the secondary database.
© Copyright. All rights reserved.
87
Unit 2: Taking ABAP to SAP HANA
What does the report display this time?
Task 2: Analyze the Program with ABAP Code Inspector
Analyze the program with the Code Inspector (transaction SCI) to identify the source of this
functional issue. Use globally shipped check variant FUNCTIONAL_DB for this check.
1. In Code Inspector (transaction SCI), create a local inspection for your program
ZHA400_##_CHECK_1 based on check variant FUNCTIONAL_DB (suggested name for
the inspection: HA400_##_FUNCTIONAL).
2. Execute the inspection and analyze the inspection result. Navigate to the ABAP source
code. Read the check documentation for hints on how to correct the program.
Which check reports an error?
What is the reason for this error?
What can you do to correct the coding?
Task 3: Improve the Program
1. Edit subroutine get_data of your program. Apply one of the possible corrections for the
Code Inspector error.
2. Activate and test your program. Make sure both databases deliver exactly the same data.
88
© Copyright. All rights reserved.
Unit 2
Solution 6
Search for Potential Functional Issues with
Code Inspector
Simulation: Search for Potential Functional Issues with Code Inspector
For more information on Search for Potential Functional Issues with Code
Inspector, please view the simulation in the lesson Code Checks to Prepare
ABAP Code for SAP HANA online in the SAP Learning Hub.
Business Example
You have an ABAP program that you want migrate to a system with an SAP HANA database.
You want to perform a static code analysis to find potential functional issues that might occur
when executing the program on SAP HANA.
Template:
Report HA400_CODE_CHECK_T1
Solution:
Report HA400_CODE_CHECK_S1
Task 1: Copy and Understand the Template
Log on to the application server ZME on Sybase with system ID ZME. Create a copy of report
HA400_CODE_CHECK_T1 in your package ZHA400_## (suggested name:
ZHA400_##_CHECK_1, where ## is your group number). Activate and execute the program,
first on the primary database (Sybase ASE), then on the secondary database (SAP HANA).
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Activate and execute the program with the default settings.
a) Complete this step as you learned to do in previous classes.
What data does the report display?
The report displays a list of carriers — each with revenues separated by economy,
business, and first class.
3. Execute the program again, but this time let it read its data from the secondary database.
a) Complete this step as before.
© Copyright. All rights reserved.
89
Unit 2: Taking ABAP to SAP HANA
What does the report display this time?
The report displays a much longer list on which the same carrier appears several times.
Task 2: Analyze the Program with ABAP Code Inspector
Analyze the program with the Code Inspector (transaction SCI) to identify the source of this
functional issue. Use globally shipped check variant FUNCTIONAL_DB for this check.
1. In Code Inspector (transaction SCI), create a local inspection for your program
ZHA400_##_CHECK_1 based on check variant FUNCTIONAL_DB (suggested name for
the inspection: HA400_##_FUNCTIONAL).
a) Enter transaction SCI.
b) In the Inspection frame, enter the name for the inspection and choose Create.
c) In the Object Selection frame, enter Single, Program, and the name of your program.
d) In the Check Variant frame, enter the name of the check variant.
Hint:
You might have to choose the button to the left of the input field before
you can choose global check variants.
2. Execute the inspection and analyze the inspection result. Navigate to the ABAP source
code. Read the check documentation for hints on how to correct the program.
a) On the toolbar, choose Execute.
b) To see the inspection result, choose Results on the toolbar.
c) Check the reported error(s). To navigate to the ABAP source, double-click a message
code.
d) To display the check documentation, choose the “i”-icon next to the error message.
Which check reports an error?
Check Search problematic statements for result of SELECT/OPEN CURSOR without
ORDER BY
What is the reason for this error?
Internal table lt_sbook is filled with a SELECT statement from database table SBOOK. A
subsequent LOOP over this internal table makes use of control structures AT ... ENDAT.
This only works correctly if the content of lt_sbook is sorted by column CARRID.
90
© Copyright. All rights reserved.
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
What can you do to correct the coding?
Make sure the content of lt_sbook is sorted by column CARRID. There are several ways to
achieve this: 1. Add ORDER BY CARRID to the SELECT statement. 2. Add statement SORT
lt_sbook BY carrid. before the loop. 3. Declare lt_sbook as Sorted Table.
Task 3: Improve the Program
1. Edit subroutine get_data of your program. Apply one of the possible corrections for the
Code Inspector error.
a) Alternative 1: Add addition ORDER BY CARRID at the end of the SELECT statement .
b) Alternative 2: Add statement SORT lt_sbook BY carrid. before the loop.
c) Alternative 3: Replace the declaration of lt_sbook with statement DATA lt_sbook
TYPE SORTED TABLE OF sbook with NON-UNIQUE KEY carrid.
d) See the source code extract from the model solution.
2. Activate and test your program. Make sure both databases deliver exactly the same data.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_OPT_OSQL_S1)
&---------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_carriers TYPE ty_t_carriers.
* Declarations
****************
DATA ls_carrier LIKE LINE OF ct_carriers.
* Alternative 3: Sorted table
* DATA:
*
lt_sbook TYPE SORTED TABLE OF sbook
*
WITH NON-UNIQUE KEY carrid.
DATA:
lt_sbook TYPE TABLE OF sbook,
ls_sbook TYPE sbook,
ls_scarr TYPE scarr.
* Processing
*****************
*Alternative 1: ORDER BY
* SELECT * FROM sbook
*
CONNECTION (pv_dbcon)
*
INTO TABLE lt_sbook
SELECT * FROM sbook
CONNECTION (pv_dbcon)
INTO TABLE lt_sbook
© Copyright. All rights reserved.
91
Unit 2: Taking ABAP to SAP HANA
ORDER BY carrid.
* Alternative 2: SORT ...
* SORT lt_sbook BY carcid.
LOOP AT lt_sbook INTO ls_sbook.
AT NEW carrid.
IF ls_carrier-carrid IS NOT INITIAL.
APPEND ls_carrier TO ct_carriers.
CLEAR ls_carrier.
ENDIF.
SELECT SINGLE * FROM scarr
CONNECTION (pv_dbcon)
INTO ls_scarr
WHERE carrid = ls_sbook-carrid.
MOVE-CORRESPONDING ls_scarr TO ls_carrier.
ENDAT.
CASE ls_sbook-class.
WHEN 'Y'.
ls_carrier-revenue_economy
= ls_carrier-revenue_economy
+ ls_sbook-loccuram.
WHEN 'C'.
ls_carrier-revenue_business = ls_carrier-revenue_economy
+ ls_sbook-loccuram.
WHEN 'F'.
ls_carrier-revenue_first
= ls_carrier-revenue_economy
+ ls_sbook-loccuram.
ENDCASE.
AT LAST.
APPEND ls_carrier TO ct_carriers.
CLEAR ls_carrier.
ENDAT.
ENDLOOP.
SORT ct_carriers BY carrid.
ENDFORM.
92
"
© Copyright. All rights reserved.
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
Runtime Check Monitor
Figure 75: Runtime Check Monitor - Setup
You cannot expect to detect all functional issues by static code checks. If, for example, your
code uses dynamic programming techniques, not all the details are visible to the code check
and it depends on the program behavior at runtime whether there is an issue or not.
The Runtime Check Monitor allows you to execute a limited range of runtime checks. In each
specific check, you can collect runtime-relevant information during program execution. In
addition, you will be provided with specialized views for data analysis.
You can use these specific runtime checks to perform a final, remaining cleanup of the ABAP
code - for example, following the corresponding static code checks.
Currently, two individual runtime checks are available:
Empty table in FOR ALL ENTRIES clause
This check records all events where the internal table itab in the clause ...FOR ALL ENTRIES IN
itab... within the SELECT statement is empty.
Missing ORDER BY or SORT after SELECT
This check records every SELECT in an unsorted internal table without the clause ORDER BY
or subsequent SORT and followed - either immediately or later on - by a statement that
assumes the internal table to be sorted.
Using transaction SRTCM, you can activate each of these checks individually - either on a
specific server or globally.
The Runtime Check framework is designed in a way that it has minimum impact on the overall
system performance. This allows for switching it on in productive systems, too.
© Copyright. All rights reserved.
93
Unit 2: Taking ABAP to SAP HANA
Figure 76: Runtime Check Monitor -Result Display
To display Runtime Check results, you can either use the respective button in transaction
SRTCM or launch transaction SRTCMD, directly.
Note:
To minimize the effect on overall performance, runtime check results are not persisted at real
time. You have to schedule executable program RTM_COLLECT_ALL (or execute it manually)
before you can analyze the check results.
94
© Copyright. All rights reserved.
Lesson: Code Checks to Prepare ABAP Code for SAP HANA
LESSON SUMMARY
You should now be able to:
●
Use Code Inspector and ABAP Test Cockpit
●
Understand the Runtime Check Monitor
© Copyright. All rights reserved.
95
Unit 2
Lesson 3
Tools to Analyse Potential Performance Issues
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Understand the reason for potential performance issues
●
Use analysis tools to measure and compare runtime consumption
●
Search for potential performance issues with Code Inspector and ABAP Test Cockpit
●
Use SQL Trace (ST05) for in-depth analysis of database accesses
Performance Considerations when Migrating to SAP HANA
Besides the functional issues we already discussed, you have to keep an eye on the runtime of
your ABAP programs. The new database will have a noticeable effect on the performance of
existing ABAP code.
Performance of Existing ABAP Code After a Migration
●
Some code immediately runs faster
●
Some code might be negatively impacted and should be revisited
It can be hoped that some code immediately runs faster on SAP HANA. This is particularly
true for coding that follows the classical ABAP performance recommendations.
However, there can also be situations in which existing code is negatively impacted. In most of
these cases the classical performance recommendations were not taken into account.
Note:
In general, well-written ABAP code has a good chance of experiencing
performance improvements on SAP HANA.
Runtime Analysis
Before starting to optimize ABAP code detected with Code Inspector or ABAP Test Cockpit,
you may have to perform a detailed runtime analysis to better understand the origin of the
performance issue.
96
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
Runtime Analysis in the ABAP Workbench
Figure 77: Runtime Analysis: ABAP Trace
One of the tools to perform such a runtime analysis in the classical SAP GUI is the ABAP trace
(transaction code SAT), which replaces the older ABAP runtime analysis (SE30).
ABAP runtime analysis and ABAP trace have the following characteristics:
●
●
●
The functions of the classic ABAP runtime analysis (SE30) and the new ABAP trace (SAT)
can be completely used in the SAP HANA context.
Both tools measure runtime of processing blocks (methods, functions, and subroutines)
or single statements.
No database-specific functions are available.
© Copyright. All rights reserved.
97
Unit 2: Taking ABAP to SAP HANA
Runtime Analysis in ABAP Development Tools
Figure 78: Runtime Analysis: ABAP Profiling Perspective in ABAP Development Tools
When using the ABAP Development Tools in Eclipse, an alternative to using the SAP GUIbased ABAP trace is to use a dedicated perspective in ABAP Development Tools, called the
ABAP Profiling perspective. With this perspective, you can also create ABAP traces. The trace
files are the same as those created using the ABAP trace, which means that a trace created
using any of the two tools can also be analyzed in the other tool.
Depending on which configuration is used to generate a trace, the ABAP Profiling perspective
provides different views, including the following:
●
An overview that shows, for example, which percentage of the execution time was spent in
ABAP, and which percentage on the database
●
A hit list of the most time-consuming programs or methods
●
Database accesses
●
An ABAP trace call tree view to analyze the execution path of a program. You can use the
call tree to do the following:
-
-
●
98
Analyze the flow of a program as part of the analysis of an error. You can see which
ABAP programs are involved in the error and easily find useful places to set
breakpoints.
Understand how an unfamiliar program works and which ABAP programs play a role in
its execution.
A Call Timeline view, which visualizes the trace events and time consumed in the form of a
diagram. In general, information shown in this graphical view corresponds to the one in the
Call Tree view. The horizontal axis of the diagram displays the temporal sequence of each
trace event measured, whereas the vertical axis represents the call depth within a call
hierarchy. In contrast to the Call Tree, the trace events are represented not as discrete
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
tree nodes, but as a continuous sequence. The advantage lies in the graphical
representation and a quick detection of eye-catching patterns.
Call Tree and Call Timeline are only shown if the call tree was created when tracing (no
aggregated measurement).
Performance Checks in Code Inspector and ABAP Test Cockpit
When migrating to SAP HANA database, Code Inspector can not only help you to identify
functional issues. It also offers a large variety of checks that search for patterns that are
known to cause performance problems. The following checks are particularly important for
SAP HANA migration:
Code Inspector Checks to Search for Potential Performance Issues
Animation:
For more information on , please view the animation in the lesson Tools to
Analyse Potential Performance Issues, online in the SAP Learning Hub.
Search problematic SELECT * statements
Search for SELECT * statements where less than a certain percentage of the fields are
used later on
Search DB operations in loops across modularization units
Search for repeated identical selects
Search SELECT .. FOR ALL ENTRIES-clauses to be transformed
Search for SELECT statements with FOR ALL ENTRIES that can be replaced by a SELECT
statement with a join
The checks listed above were developed and shipped in SAP NetWeaver AS ABAP 7.40 to
improve the support for SAP HANA database migration.
Note:
In order to support customers during database migration, SAP shipped global
check variant PERFORMANCE_DB. This check variant contains the checks listed
above, some other performance checks and a search function that provides
statistics of database accesses.
In-Depth Analysis of Performance Issues
Before starting to optimize ABAP code detected with Code Inspector or ABAP Test Cockpit,
you may have to perform a detailed SQL analysis to better understand the origin of the
performance issue.
© Copyright. All rights reserved.
99
Unit 2: Taking ABAP to SAP HANA
Figure 79: Runtime Analysis: SQL Trace
Animation: Runtime Analysis: SQL Trace
For more information on Runtime Analysis: SQL Trace, please view the animation
in the lesson Tools to Analyse Potential Performance Issues, online in the SAP
Learning Hub.
Uses of SQL Trace (ST05)
●
Display record of all database access (including SQL calls over a secondary database
connection)
●
Detect redundant or identical SELECT statements
●
Locate database-related performance issues
●
Display database execution plan for statements
Another tool for runtime performance analysis is the SQL Trace (transaction ST05). This tool
in particular analyses database accesses. It can be used for a deeper analysis once an
analysis with the ABAP trace or the ABAP Profiling perspective indicates that database
access could be the cause of the performance issues.
100
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
Figure 81: Performance Trace
Figure 82: Execution Plan
Hint:
Note that the Explain function in the SQL Trace is database-specific. Hence, a
database execution plan looks different for each database platform supported by
SAP.
© Copyright. All rights reserved.
101
Unit 2: Taking ABAP to SAP HANA
102
© Copyright. All rights reserved.
Unit 2
Exercise 7
Analyze Potential Performance Issues
Simulation: Analyze Potential Performance Issues
For more information on Analyze Potential Performance Issues, please view the
simulation in the lesson Tools to Analyse Potential Performance Issues online in
the SAP Learning Hub.
Business Example
You have an ABAP program that does not perform well. You want to perform a static code
analysis to get clues about what can be the cause, especially if the program is supposed to
perform well when executed on SAP HANA.
Template:
Report HA400_OPT_OSQL_T1
Solution:
Report HA400_OPT_OSQL_S1
Task 1: Copy and Understand the Template
Log on to the application server ZME on Sybase with system ID ZME. Create a copy of report
HA400_OPT_OSQL_T1 in your package ZHA400_## (suggested name:
ZHA400_##_OSQL_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Activate and execute the program with default settings.
What does the report display?
Task 2: Analyze the Program with ABAP Code Inspector
Analyze the program with the Code Inspector (SCI) to identify potential performance
problems. Use globally shipped check variant PERFORMANCE_DB for this check.
1. Perform an inspection of your program based on your new check variant (suggested name
for the inspection: HA400_PERF##).
2. Execute the inspection and analyze the inspection result. Navigate to the ABAP source
code. Read the check documentation for hints on how to correct the program.
© Copyright. All rights reserved.
103
Unit 2: Taking ABAP to SAP HANA
In the search for problematic SELECT *-statements you should find an error related to
database table SBOOK. Why is there no error related to database table SCUSTOM?
Task 3: Analyze the Suggested Improvements
1. Uncomment the source code of subroutine get_data_solution1.
Analyze the coding in the get_data_solution1 subroutine and compare it to the coding in
the get_data_template subroutine. What are the two main improvements?
Why is it important that internal table lt_sbook is declared as a sorted table and not as a
standard table?
2. Uncomment the source code of subroutine get_data_solution2.
Analyze the coding in the get_data_solution2 subroutine and compare it to the coding in
the get_data_template subroutine. What is the main difference?
Why is it important that the content of internal table lt_cust_sbook is sorted?
3. Activate and test your program. Make sure all three subroutines deliver exactly the same
data.
Task 4: Quantify the Improvements
Perform a runtime measurement with the ABAP Trace (SAT). Compare the runtime
consumption of get_data_template, get_data_solution1 and get_data_solution2. Do this
analysis on both, primary and secondary database.
1. Perform a runtime measurement with the ABAP Trace (transaction SAT) on the primary
database and compare the gross runtime of the three subroutines.
104
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
On the primary database, the runtime of get_data_template is __________(1)
microseconds, the runtime of get_data_solution1 is __________(2) microseconds and the
runtime of get_data_solution2 is __________(3) microseconds.
On the secondary database (SAP HANA), the runtime of get_data_template is
__________(1) microseconds, the runtime of get_data_solution1 is __________(2)
microseconds and the runtime of get_data_solution2 is __________(3) microseconds.
2. Repeat the runtime measurement with data retrieval from the secondary database (SAP
HANA).
On SAP HANA, the runtime of get_data_template is __________(1) microseconds, the
runtime of get_data_solution1 is __________(2) microseconds and the runtime of
get_data_solution2 is __________(3) microseconds.
© Copyright. All rights reserved.
105
Unit 2
Solution 7
Analyze Potential Performance Issues
Simulation: Analyze Potential Performance Issues
For more information on Analyze Potential Performance Issues, please view the
simulation in the lesson Tools to Analyse Potential Performance Issues online in
the SAP Learning Hub.
Business Example
You have an ABAP program that does not perform well. You want to perform a static code
analysis to get clues about what can be the cause, especially if the program is supposed to
perform well when executed on SAP HANA.
Template:
Report HA400_OPT_OSQL_T1
Solution:
Report HA400_OPT_OSQL_S1
Task 1: Copy and Understand the Template
Log on to the application server ZME on Sybase with system ID ZME. Create a copy of report
HA400_OPT_OSQL_T1 in your package ZHA400_## (suggested name:
ZHA400_##_OSQL_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Activate and execute the program with default settings.
a) Complete this step as you learned to do in previous classes.
What does the report display?
The report displays a list of customers — each with the average number of days between a
booking and the actual flight.
Task 2: Analyze the Program with ABAP Code Inspector
Analyze the program with the Code Inspector (SCI) to identify potential performance
problems. Use globally shipped check variant PERFORMANCE_DB for this check.
1. Perform an inspection of your program based on your new check variant (suggested name
for the inspection: HA400_PERF##).
106
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
a) Start transaction SCI.
b) In the Inspection frame, enter the name for the inspection and choose Create.
c) In the Object Selection frame, enter Single, Program and type in the name of your
program.
d) In the Check Variant frame, enter the name of the check variant.
Hint:
You might have to click on the button left of the input field before you can
choose global check variants.
2. Execute the inspection and analyze the inspection result. Navigate to the ABAP source
code. Read the check documentation for hints on how to correct the program.
a) On the toolbar, choose Execute.
b) To see the inspection result, choose Results on the toolbar.
c) Check the reported error(s). To navigate to the ABAP source, double click a message
code.
d) To display the check documentation, choose the “i”-icon next to the error message.
In the search for problematic SELECT *-statements you should find an error related to
database table SBOOK. Why is there no error related to database table SCUSTOM?
The check has an input parameter that only reports SELECT * statements where less than
a certain percentage of all fields is actually needed. This parameter is 20% by default.
Task 3: Analyze the Suggested Improvements
1. Uncomment the source code of subroutine get_data_solution1.
a) Select the entire source code between FORM and ENDFORM.
b) Right-click on the selection and choose Format → Uncomment Lines or press Ctrl +
Shift + < on your keyboard.
Analyze the coding in the get_data_solution1 subroutine and compare it to the coding in
the get_data_template subroutine. What are the two main improvements?
NO SELECT * STATEMENTS: From both tables, only those fields are selected that are
actually needed by the program. NO NESTED SELECTS: In subroutine get_data_solution1,
the two nested SELECT-loops have been replaced by two array fetches on SCUSTOM and
SBOOK and two nested loops over the internal tables.
© Copyright. All rights reserved.
107
Unit 2: Taking ABAP to SAP HANA
Why is it important that internal table lt_sbook is declared as a sorted table and not as a
standard table?
If lt_sbook was a standard table, the runtime environment would not be able to optimize
the loop over this table and we would lose a lot of runtime by searching for the required
entries.
2. Uncomment the source code of subroutine get_data_solution2.
a) Select the entire source code between FORM and ENDFORM.
b) Right-click on the selection and choose Format → Uncomment Lines or press Ctrl +
Shift + < on your keyboard.
Analyze the coding in the get_data_solution2 subroutine and compare it to the coding in
the get_data_template subroutine. What is the main difference?
Instead of two separate SELECTs there is one SELECT statement with a join.
Why is it important that the content of internal table lt_cust_sbook is sorted?
If lt_cust_sbook was not sorted, the AT NEW and AT LAST logic inside LOOP would not
work.
3. Activate and test your program. Make sure all three subroutines deliver exactly the same
data.
a) Complete this step as you learned to do in previous classes.
Task 4: Quantify the Improvements
Perform a runtime measurement with the ABAP Trace (SAT). Compare the runtime
consumption of get_data_template, get_data_solution1 and get_data_solution2. Do this
analysis on both, primary and secondary database.
1. Perform a runtime measurement with the ABAP Trace (transaction SAT) on the primary
database and compare the gross runtime of the three subroutines.
a) Start transaction SAT.
b) Enter the name of your program and, if necessary, the name of the variant (DEFAULT).
c) Choose Execute.
d) On the selection screen of the report, choose All, one after the other and Primary
database, and choose Execute again.
e) After the report has finished, choose Back from the system toolbar or press F3 on your
keyboard to return to the selection screen.
f) Choose Back again or press F3 on your keyboard again to display the result of the
runtime measurement.
108
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
g) On the Profile Trace Results screen, double-click the node Runtime
Measurement → Internal Processing Blocks → Subroutines → PERFORM to filter the
Hit List on the right to display only subroutine calls.
h) Sort the Hit List by choosing the header of the Gross [microsec] column.
On the primary database, the runtime of get_data_template is __________(1)
microseconds, the runtime of get_data_solution1 is __________(2) microseconds and the
runtime of get_data_solution2 is __________(3) microseconds.
Your instructor will provide his measurement for comparison.
On the secondary database (SAP HANA), the runtime of get_data_template is
__________(1) microseconds, the runtime of get_data_solution1 is __________(2)
microseconds and the runtime of get_data_solution2 is __________(3) microseconds.
Your instructor will provide his measurement for comparison.
2. Repeat the runtime measurement with data retrieval from the secondary database (SAP
HANA).
On SAP HANA, the runtime of get_data_template is __________(1) microseconds, the
runtime of get_data_solution1 is __________(2) microseconds and the runtime of
get_data_solution2 is __________(3) microseconds.
Your instructor will provide his measurement for comparison.
a) Execute the runtime analysis as before but this time, choose the Secondary Database
option on the selection screen of the report.
Code Extract from program HA400_OPT_OSQL_S1
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: ls_scustom TYPE scustom,
ls_sbook
TYPE sbook.
* help variables
DATA lv_count TYPE i.
* Processing
© Copyright. All rights reserved.
109
Unit 2: Taking ABAP to SAP HANA
*****************
CLEAR ct_customers.
SELECT * FROM scustom
CONNECTION (pv_dbcon)
INTO ls_scustom.
ls_customer-id
= ls_scustom-id.
ls_customer-name
= ls_scustom-name.
ls_customer-postcode = ls_scustom-postcode.
ls_customer-city
= ls_scustom-city.
ls_customer-country = ls_scustom-country.
CLEAR ls_customer-days_ahead.
CLEAR lv_count.
SELECT * FROM sbook
CONNECTION (pv_dbcon)
INTO ls_sbook
WHERE customid = ls_scustom-id
AND cancelled = space.
ls_customer-days_ahead = ls_customer-days_ahead
+ ( ls_sbook-fldate
- ls_sbook-order_date ).
lv_count = lv_count + 1.
ENDSELECT.
IF lv_count <> 0.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
INSERT ls_customer INTO TABLE ct_customers.
ENDIF.
ENDSELECT.
SORT ct_customers BY id.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution1: Nested Loops
*&--------------------------------------------------------------------*
FORM get_data_solution1 USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Types for target fields
TYPES: BEGIN OF lty_s_cust,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode TYPE scustom-postcode,
city
TYPE scustom-city,
country TYPE scustom-country,
END OF lty_s_cust.
TYPES: BEGIN OF lty_s_book,
customid
TYPE sbook-customid,
110
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
fldate
TYPE sbook-fldate,
order_date TYPE sbook-order_date,
END OF lty_s_book.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: lt_scustom TYPE SORTED TABLE OF lty_s_cust
WITH NON-UNIQUE KEY id,
ls_scustom TYPE lty_s_cust,
lt_sbook
TYPE SORTED TABLE OF lty_s_book
WITH NON-UNIQUE KEY customid,
ls_sbook
TYPE lty_s_book.
* help variables
DATA lv_count TYPE i.
* Processing
*****************
CLEAR ct_customers.
SELECT id name postcode city country
FROM scustom
CONNECTION (pv_dbcon)
INTO TABLE lt_scustom.
*
ORDER BY id no improvement, sorting on Appl. server more efficient
SELECT customid fldate order_date
FROM sbook
CONNECTION (pv_dbcon)
INTO TABLE lt_sbook
WHERE cancelled = space.
"#EC CI_NOFIELD
*
ORDER BY customid no impr., sorting on AS more efficient
LOOP AT lt_scustom INTO ls_scustom.
ls_customer-id
= ls_scustom-id.
ls_customer-name
= ls_scustom-name.
ls_customer-postcode = ls_scustom-postcode.
ls_customer-city
= ls_scustom-city.
ls_customer-country = ls_scustom-country.
CLEAR ls_customer-days_ahead.
CLEAR lv_count.
LOOP AT lt_sbook INTO ls_sbook
WHERE customid = ls_scustom-id.
ls_customer-days_ahead =
ls_customer-days_ahead
+ ( ls_sbook-fldate
- ls_sbook-order_date ).
lv_count = lv_count + 1.
ENDLOOP.
IF lv_count > 0.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
INSERT ls_customer INTO TABLE ct_customers.
ENDIF.
ENDLOOP.
© Copyright. All rights reserved.
111
Unit 2: Taking ABAP to SAP HANA
*
SORT ct_customers BY id. " already sorted
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution_2: Join
*&--------------------------------------------------------------------*
FORM get_data_solution2 USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Types for target fields
TYPES: BEGIN OF lty_s_cust_book,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode
TYPE scustom-postcode,
city
TYPE scustom-city,
country
TYPE scustom-country,
fldate
TYPE sbook-fldate,
order_date TYPE sbook-order_date,
END OF lty_s_cust_book.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: lt_cust_book TYPE SORTED TABLE OF lty_s_cust_book
WITH NON-UNIQUE KEY id,
ls_cust_book TYPE lty_s_cust_book.
* help variables
DATA lv_count TYPE i.
* Processing
*****************
CLEAR ct_customers.
SELECT c~id c~name c~postcode c~city c~country
b~fldate b~order_date
FROM scustom AS c INNER JOIN sbook AS b
ON
c~id = b~customid
CONNECTION (pv_dbcon)
INTO TABLE lt_cust_book
WHERE b~cancelled = space
ORDER BY c~id.
LOOP AT lt_cust_book INTO ls_cust_book.
AT NEW country.
IF ls_customer-id IS NOT INITIAL.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
APPEND ls_customer TO ct_customers.
ENDIF.
112
© Copyright. All rights reserved.
Lesson: Tools to Analyse Potential Performance Issues
CLEAR lv_count.
CLEAR ls_customer.
ls_customer-id
= ls_cust_book-id.
ls_customer-name
= ls_cust_book-name.
ls_customer-postcode = ls_cust_book-postcode.
ls_customer-city
= ls_cust_book-city.
ls_customer-country = ls_cust_book-country.
ENDAT.
lv_count = lv_count + 1.
ls_customer-days_ahead =
ls_customer-days_ahead
+ ls_cust_book-fldate
- ls_cust_book-order_date.
AT LAST.
IF ls_customer-id IS NOT INITIAL.
ls_customer-days_ahead = ls_customer-days_ahead / lv_count.
APPEND ls_customer TO ct_customers.
ENDIF.
ENDAT.
ENDLOOP.
* SORT ct_customers BY id. "already sorted
ENDFORM.
© Copyright. All rights reserved.
113
Unit 2: Taking ABAP to SAP HANA
LESSON SUMMARY
You should now be able to:
114
●
Understand the reason for potential performance issues
●
Use analysis tools to measure and compare runtime consumption
●
Search for potential performance issues with Code Inspector and ABAP Test Cockpit
●
Use SQL Trace (ST05) for in-depth analysis of database accesses
© Copyright. All rights reserved.
Unit 2
Lesson 4
Guided Performance Analysis
LESSON OVERVIEW
In this lesson, you learn how to use the SQL Monitor (SQLM) to identify the most important
database access, use the Performance Tuning Worklist (SWLT) to combine static and dynamic
performance analysis results, and use SQL Trace (ST05) for in-depth analysis of database
accesses.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Understand the SQL Monitor (SQLM)
●
Use the Performance Tuning Worklist (SWLT)
Guided Performance Optimization When Migrating to SAP HANA
Figure 84: Steps of the Guided Performance Optimization
© Copyright. All rights reserved.
115
Unit 2: Taking ABAP to SAP HANA
Animation: Steps of the Guided Performance Optimization
For more information on Steps of the Guided Performance Optimization, please
view the animation in the lesson Guided Performance Analysis, online in the SAP
Learning Hub.
The first two steps are supported by several tools, which in total result in a guided
performance optimization procedure, as follows:
●
●
●
●
Static code check tools such as Code Inspector and ABAP Test Cockpit (ATC) to find
pieces of code using known critical constructs, such as deviations from the classical
performance recommendations
Tools analyzing performance at runtime, to determine if critical constructs really cause
issues at runtime, for example, the ABAP Trace
A new tool called SQL Monitor to determine the priority if different programs access the
database intensively
A new tool called SQL Performance Tuning Worklist, which combines the results of static
and runtime analyses to create a prioritized worklist
SQL Monitor (SQLM)
Figure 86: New ABAP SQL Monitor
The new SQL Monitor is a powerful tool for capturing the SQL profile of a system or
transaction. SQL profile refers to aggregated data about all SQL requests executed in the
context of a certain business process, application, and so on. This includes how often each
request is executed, which tables are accessed, the total runtime, how many records are
fetched, and more.
The SQL Monitor is a new development with ABAP 7.4. However, in order to support its use
before a migration, it is also offered as part of the so-called ST-PI support Add-On provided by
SAP Active Global Support.
116
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
Figure 87: The New ABAP SQL Monitor – Architecture
Animation: The New ABAP SQL Monitor – Architecture
For more information on The New ABAP SQL Monitor – Architecture, please view
the animation in the lesson Guided Performance Analysis, online in the SAP
Learning Hub.
A central design goal was to ensure that the SQL Monitor can run in the productive
environment because this is where the real SQL profile of an application can be observed. The
SQL Monitor introduces only a minimal performance overhead and all data collection is done
asynchronously without additional database interaction affecting the runtime of the actual
business processes.
When the SQL Monitor is enabled, the ABAP kernel logs information about database accesses
(for example, transaction, source code position, accessed tables, and so on) using the
runtime monitor infrastructure (file-based). This data is transferred periodically to the SQL
Monitor database tables (every 24 hours, with manual refresh possible). The transfer is
required for data analysis and to store the results permanently.
The SQL Monitor provides a dedicated transaction for displaying and analyzing the data,
which in turn reads from the respective database tables containing the collected data.
© Copyright. All rights reserved.
117
Unit 2: Taking ABAP to SAP HANA
Figure 89: Switching the SQL Monitor On and Viewing SQL Monitor Data
Animation: Switching the SQL Monitor On and Viewing SQL Monitor Data
For more information on Switching the SQL Monitor On and Viewing SQL Monitor
Data, please view the animation in the lesson Guided Performance Analysis,
online in the SAP Learning Hub.
After the initial setup of the SQL Monitor, you can activate or deactivate the monitor via
transaction SQLM. When you launch it, it displays the current status. You can activate it for all
application servers or for specific application servers. You can also specify an expiration date
and an upper limit for the number of records.
After data has been collected, you can view the collected SQL profile either by navigating from
transaction SQLM or by launching transaction SQLMD.
You can specify a number of filter criteria. For instance, you can filter by development objects,
such as package, object type, and name, or by request (transaction VA01, Web Dynpro
Application <ABC>), and the respective request type (for example, URL, RFC, report). You
can also define a filter for looking into accesses to concrete database tables.
You can select a certain aggregation type and a sorting of the result list.
118
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
Figure 91: Exporting and Importing SQL Monitor Snapshots
Animation: Exporting and Importing SQL Monitor Snapshots
For more information on Exporting and Importing SQL Monitor Snapshots,
please view the animation in the lesson Guided Performance Analysis, online in
the SAP Learning Hub.
Exporting and Importing SQL Monitor Snapshots
●
Transaction SQLM offers a simple management of SQL Monitor snapshots.
●
Snapshots can be as follows:
●
-
Created based on local data
-
Imported from a file (for example, from other systems)
-
Exported to a file
-
Removed
To reduce data volume, basic filter criteria can be applied before snapshot creation.
As the SQL Monitor should collect data in a productive system, and the code optimizations
are usually planned in another system, such as a development system or sandbox
environment, it is desirable to be able to export and import the collected data. The SQL
Monitor supports exporting and importing snapshot data for this purpose. These tasks can
also be performed using the SQLM transaction.
Note that the exported data can also be analyzed via other tools, such as a SAP Lumira,
allowing visualizations and more complex analytical operations.
© Copyright. All rights reserved.
119
Unit 2: Taking ABAP to SAP HANA
Performance Tuning Worklist (SQLT)
Figure 93: SQL Performance Tuning Worklist – Motivation
For performance optimization, combine the results of both static source code analysis
(carried out via the ATP or Code Inspector) and the SQL Monitor runtime data.
This correlation can be done in another new tool, the SQL Performance Tuning Worklist. This
tools can be used to create a ranking based on the cost and benefit of a potential
optimization.
Figure 94: SQL Performance Tuning Worklist – Usage
120
© Copyright. All rights reserved.
Unit 2
Exercise 8
Perform a Structured SQL Performance
Analysis
Simulation: Perform a Structured SQL Performance Analysis
For more information on Perform a Structured SQL Performance Analysis,
please view the simulation in the lesson Guided Performance Analysis online in
the SAP Learning Hub.
Business Example
You performed a static code analysis of a poorly performing ABAP program using the SAP
Code Inspector and collected run-time data for the same code. You want to combine the
results of both using the SAP Performance Tuning Worklist to analyze which pieces of code
should be improved with highest priority. You improve the corresponding pieces of code and
want to repeat the analysis to quantify the performance improvement achieved.
Sample classes:
CL_HA400_CI_PERFORMANCE_ISSUES
CL_HA400_CI_OPTIMIZED
Task 1: Analyze the Source Code of Class CL_HA400_CI_PERFORMANCE_ISSUES
Log on to the application server ZME on Sybase with system ID ZME. Open class
CL_HA400_CI_PERFORMANCE_ISSUES and analyze the coding.
1. Open class CL_HA400_CI_PERFORMANCE_ISSUES.
What are the public methods of the class?
What are the private methods and where are they called?
© Copyright. All rights reserved.
121
Unit 2: Taking ABAP to SAP HANA
Are there any conditions for these calls?
Task 2: Analyze Class CL_HA400_CI_PERFORMANCE_ISSUES with Code Inspector
Use the Code Inspector tool to see if class CL_HA400_CI_PERFORMANCE_ISSUES has any
SAP HANA relevant performance issues.
Hint:
Global check variant PERFORMANCE_DB contains the SAP HANA relevant
checks.
1. Perform an inspection of the class based on check variant PERFORMANCE_DB
(suggested name for the inspection: HA400_##_SWLT).
2. Analyze the inspection result.
How many SAP HANA-relevant performance errors does the check find and in which
methods?
What information is missing for prioritizing the performance errors?
Task 3: Analyze Existing SQL Monitor Data for Class
CL_HA400_CI_PERFORMANCE_ISSUES
With the SQL Monitor tool, analyze a snapshot of SQL Monitor data. Restrict the display to
measurements related to class CL_HA400_CI_PERFORMANCE_ISSUES.
Note:
The description of the snapshot begins with “SQLM Snapshot for HA400”.
1. Start the SQL Monitor tool and display the data of the snapshot.
2. Find the statement with the maximum consumption of database time.
122
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
Which SQL statement has consumed the maximum database time?
Which processing block contains this statement?
Task 4: Combine Static and Dynamic Analysis for Class
CL_HA400_CI_PERFORMANCE_ISSUES
With the SQL Performance Tuning Worklist tool, combine the Code Inspector findings and the
SQL Monitor data to build a prioritized work list for SQL Performance tuning.
1. Start the SQL Performance Tuning Worklist tool and restrict the analysis to your class.
2. Activate the analysis of SQL Monitor data and select the same SQLM snapshot as before.
3. Activate the analysis of static check data and specify your code inspector inspection.
Make sure the program aggregates findings by code position.
4. Execute the analysis in the SQL Performance Tuning Worklist tool.
5. Analyze the static and SQL Monitor findings for the various SQL statements of class
CL_HA400_CI_PERFORMANCE_ISSUES. Start with the finding with the maximum DB
time.
How often has the statement been executed?
What can you do to reduce the DB time consumption?
Task 5: Optional: Repeat the Analysis for Class CL_HA400_CI_OPTIMIZED
Assume you have developed an improved version of the class. Understand the coding in the
class and repeat your analysis to prove that there are no SAP HANA relevant findings in Code
Inspector and that you reduced the overall DB time consumption drastically.
1. Analyze the source code of class CL_HA400_CI_OPTIMIZED.
2. Analyze the CL_HA400_CI_OPTIMIZED class with the code inspector.
3. Combine your Code Inspector check result with SQL Monitor data from the same
snapshot as above.
© Copyright. All rights reserved.
123
Unit 2
Solution 8
Perform a Structured SQL Performance
Analysis
Simulation: Perform a Structured SQL Performance Analysis
For more information on Perform a Structured SQL Performance Analysis,
please view the simulation in the lesson Guided Performance Analysis online in
the SAP Learning Hub.
Business Example
You performed a static code analysis of a poorly performing ABAP program using the SAP
Code Inspector and collected run-time data for the same code. You want to combine the
results of both using the SAP Performance Tuning Worklist to analyze which pieces of code
should be improved with highest priority. You improve the corresponding pieces of code and
want to repeat the analysis to quantify the performance improvement achieved.
Sample classes:
CL_HA400_CI_PERFORMANCE_ISSUES
CL_HA400_CI_OPTIMIZED
Task 1: Analyze the Source Code of Class CL_HA400_CI_PERFORMANCE_ISSUES
Log on to the application server ZME on Sybase with system ID ZME. Open class
CL_HA400_CI_PERFORMANCE_ISSUES and analyze the coding.
1. Open class CL_HA400_CI_PERFORMANCE_ISSUES.
a) Start the ABAP Workbench (for example using transaction code SE80).
b) Choose Repository Browser if it is not chosen yet.
c) Choose the Class/Interface object category.
d) Enter the class name as the object name and press Enter.
e) Double-click the class.
What are the public methods of the class?
The public methods are get_customers and get_agencies.
124
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
What are the private methods and where are they called?
The private method get_days_ahead_for_customer is called from method get_customers
and method get_days_ahead_for_agencies is called from method get_agencies.
Are there any conditions for these calls?
Both private methods are only executed if import parameter iv_with_days of the
corresponding public method is set to abap_true.
Task 2: Analyze Class CL_HA400_CI_PERFORMANCE_ISSUES with Code Inspector
Use the Code Inspector tool to see if class CL_HA400_CI_PERFORMANCE_ISSUES has any
SAP HANA relevant performance issues.
Hint:
Global check variant PERFORMANCE_DB contains the SAP HANA relevant
checks.
1. Perform an inspection of the class based on check variant PERFORMANCE_DB
(suggested name for the inspection: HA400_##_SWLT).
a) Start transaction SCI.
b) In the Inspection frame, enter the name for the inspection and choose Create.
c) In the Object Selection frame, enter Single, Class, and
CL_HA400_CI_PERFORMANCE_ISSUES.
d) In the Check Variant frame, enter the name of the check variant.
Hint:
You might have to choose the button on the left of the input field before
you can choose global check variants.
e) On the toolbar, choose Execute (F8).
2. Analyze the inspection result.
a) To see the inspection result, on the toolbar, choose Results (Shift F6).
b) Check the reported errors. To navigate to the ABAP source code, double-click the
message.
How many SAP HANA-relevant performance errors does the check find and in which
methods?
There are three performance errors in methods get_days_ahead_for_customer and
get_days_ahead_for_agencies.
© Copyright. All rights reserved.
125
Unit 2: Taking ABAP to SAP HANA
What information is missing for prioritizing the performance errors?
How often the different methods are actually executed in the productive system, in
particular, how often import parameter iv_with_days is set to abap_true.
Task 3: Analyze Existing SQL Monitor Data for Class
CL_HA400_CI_PERFORMANCE_ISSUES
With the SQL Monitor tool, analyze a snapshot of SQL Monitor data. Restrict the display to
measurements related to class CL_HA400_CI_PERFORMANCE_ISSUES.
Note:
The description of the snapshot begins with “SQLM Snapshot for HA400”.
1. Start the SQL Monitor tool and display the data of the snapshot.
a) Start transaction SQLM.
b) In the Snapshots frame, choose Display Snapshots.
c) In the Results frame, choose Select Snapshot.
d) Select the line where the content of column Description starts with SQLM Snapshot for
HA400 and choose Enter.
e) In the Object name field, enter the name of the class and choose Execute (F8).
2. Find the statement with the maximum consumption of database time.
a) Sort the list descending by column Total DB time.
Which SQL statement has consumed the maximum database time?
A SELECT from table SBOOK.
Which processing block contains this statement?
Method get_days_ahead_for_customer.
Task 4: Combine Static and Dynamic Analysis for Class
CL_HA400_CI_PERFORMANCE_ISSUES
With the SQL Performance Tuning Worklist tool, combine the Code Inspector findings and the
SQL Monitor data to build a prioritized work list for SQL Performance tuning.
1. Start the SQL Performance Tuning Worklist tool and restrict the analysis to your class.
a) Start transaction SWLT.
b) In the Object name field, enter the name of the class.
2. Activate the analysis of SQL Monitor data and select the same SQLM snapshot as before.
a) Choose the SQL Monitor tab.
126
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
b) Choose Use SQL Monitor Data if it is not yet chosen.
c) Choose Select Snapshot.
d) Choose the SQLM snapshot with the description starting with “SQLM Snapshot for
HA400 ....”
3. Activate the analysis of static check data and specify your code inspector inspection.
Make sure the program aggregates findings by code position.
a) Choose the Static Checks tab.
b) Choose Use Static Check Data if it is not yet chosen.
c) Choose Code Inspector if it is not yet chosen.
d) Choose Select Inspection Result.
e) Select your inspection (suggested name was: HA400_##_SWLT).
f) In the Further Options frame, in the Aggregate Findings in Overview field, choose the By
Code Position entry.
4. Execute the analysis in the SQL Performance Tuning Worklist tool.
a) Choose Execute.
5. Analyze the static and SQL Monitor findings for the various SQL statements of class
CL_HA400_CI_PERFORMANCE_ISSUES. Start with the finding with the maximum DB
time.
a) In the Result Overview, make sure the results are ordered by column Total DB time.
b) Click on the SQL statement with the largest value in the Total DB time column.
c) Analyze the entries in SQL Monitor Results and Static Check Findings.
How often has the statement been executed?
Several hundred thousand times.
What can you do to reduce the DB time consumption?
Avoid the repeated single record accesses and get rid of the SELECT * in this statement.
Task 5: Optional: Repeat the Analysis for Class CL_HA400_CI_OPTIMIZED
Assume you have developed an improved version of the class. Understand the coding in the
class and repeat your analysis to prove that there are no SAP HANA relevant findings in Code
Inspector and that you reduced the overall DB time consumption drastically.
1. Analyze the source code of class CL_HA400_CI_OPTIMIZED.
a) Perform this step as before.
2. Analyze the CL_HA400_CI_OPTIMIZED class with the code inspector.
a) Perform this step as before.
3. Combine your Code Inspector check result with SQL Monitor data from the same
snapshot as above.
© Copyright. All rights reserved.
127
Unit 2: Taking ABAP to SAP HANA
a) Perform this step as before.
128
© Copyright. All rights reserved.
Lesson: Guided Performance Analysis
LESSON SUMMARY
You should now be able to:
●
Understand the SQL Monitor (SQLM)
●
Use the Performance Tuning Worklist (SWLT)
© Copyright. All rights reserved.
129
Unit 2: Taking ABAP to SAP HANA
130
© Copyright. All rights reserved.
Unit 2
Lesson 5
SQL Performance Rules for SAP HANA
LESSON OVERVIEW
In this lesson, you learn about the performance rules and guidelines for ABAP on SAP HANA.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Know the performance rules and guidelines for SAP HANA
Performance Guidelines for ABAP on SAP HANA
The classic performance guidelines for using Open SQL and for ABAP programming
essentially remain valid. These guidelines can be called the five golden rules.
Figure 96: Golden Rules for Open SQL
Animation:
For more information on , please view the animation in the lesson SQL
Performance Rules for SAP HANA, online in the SAP Learning Hub.
© Copyright. All rights reserved.
131
Unit 2: Taking ABAP to SAP HANA
The five golden rules are as follows:
●
Keep the result set small
This reduces both the amount of memory used in the database system and the network
load when transferring data to the application server. To reduce the size of your result
sets, use the WHERE and HAVING clauses.
●
Minimize the amount of data transferred
To only transfer the columns you really need, use SELECT with a field list, instead of
SELECT *.
●
Minimize the number of database accesses
On all database systems, there is a small performance overhead associated with every
request for connection handling, SQL parsing, execution plan determination, and so on.
Avoiding such frequent single database requests is more important on SAP HANA. You
can, therefore, minimize the load on the network and the database system by minimizing
the number of times you access the database. Use JOINs and/or sub-queries instead of
nested SELECT loops.
Do not retrieve unnecessary data from the database by selecting any of the following:
●
-
Minimal number of rows
-
Minimal number of columns
-
Minimal number of database interactions
Minimize the search overhead
Minimize the size of the result set by using the WHERE and HAVING clauses. To increase the
efficiency of these clauses, formulate them to fit with the database table indexes.
●
Reduce the database load
Unlike application servers and presentation servers, there is only one database server in
your system. Therefore, you should still aim to reduce the database load as much as
possible. Use the following methods: avoid reading data redundantly, use table buffering (if
applicable) and do not bypass it, and sort data in your ABAP programs.
Figure 97: Guidelines that Become More Important
132
© Copyright. All rights reserved.
Lesson: SQL Performance Rules for SAP HANA
Animation: Guidelines that Become More Important
For more information on Guidelines that Become More Important, please view
the animation in the lesson SQL Performance Rules for SAP HANA, online in the
SAP Learning Hub.
Some guidelines become even more important with SAP HANA.
Keep the result set small and reduce the amount of data transferred, as follows:
●
●
Do not retrieve rows and discard them later using CHECK or EXIT statements, for example,
in loops.
The more fields you use in the field list, the more columns have to be unpacked. This
unpacking and reconstruction of rows is more expensive on a column store than on a row
store.
Reduce the number of database accesses, as follows:
●
●
Use mass processing wherever possible.
All rows and columns that are needed should be selected in one SQL statement (avoid
nested SELECTs and SELECTs in loops).
Use SELECT … FOR ALL ENTRIES instead of lots of SELECTs or SELECT SINGLEs.
Use array variants of INSERT, UPDATE, MODIFY, and DELETE.
Figure 99: Guidelines that are Changed
© Copyright. All rights reserved.
133
Unit 2: Taking ABAP to SAP HANA
Animation: Guidelines that are Changed
For more information on Guidelines that are Changed, please view the animation
in the lesson SQL Performance Rules for SAP HANA, online in the SAP Learning
Hub.
New guidelines are as follows:
●
●
A WHERE clause containing non-indexed fields is not bad when executed on SAP HANA –
the in-memory full table scan is fast. To reduce main memory consumption and to improve
insert performance, most existing non-unique secondary database indices on columnar
tables can be removed.
Calculation and aggregation in the database are efficient. On SAP HANA, it is beneficial to
move data-intensive calculations into the database.
Nevertheless, executing the same operations redundantly is not recommended.
LESSON SUMMARY
You should now be able to:
●
134
Know the performance rules and guidelines for SAP HANA
© Copyright. All rights reserved.
Unit 2
Learning Assessment
1. When using a secondary database connection, the default schema is derived from the
database user, which is stored in the secondary database connection.
Determine whether this statement is true or false.
X
True
X
False
2. Which of the following are potential functional issues when migrating ABAP code to SAP
HANA?
Choose the correct answers.
X
A Use of native SQL or DB Hints
X
B Use of secondary database connections
X
C Coding that assumes that a SELECT result is always sorted
X
D The existence of customer-specific cluster tables
X
E The existence of table appends
3. Where do you define a set of Code Inspector checks that you want to perform?
Choose the correct answer.
X
A In a Code Inspector object list
X
B In a Code Inspector object check variant
X
C In a Code Inspector inspection
4. When migrating to SAP HANA, every SELECT statement immediately becomes faster.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
135
Unit 2: Learning Assessment
5. Because SAP HANA stores all data in memory, buffering of data on the application server
becomes less important.
Determine whether this statement is true or false.
X
True
X
False
6. Which of the following patterns are known to potentially cause performance issues when
accessing an SAP HANA database?
Choose the correct answers.
X
A Use of SELECT ... FOR ALL ENTRIES
X
B Use of joins with more than 3 tables
X
C Use of SELECT statements in loops
X
D Use of SELECT * for tables with many fields
7. Which of the following are steps in the recommended sequence for a guided performance
analysis?
Choose the correct answers.
X
A Do static code checks with Code Inspector or ABAP Test Cockpit
X
B Collect runtime data with SQL Monitor
X
C Collect runtime data with Runtime Analysis
X
D Combine runtime data and static check result in SQL Performance Tuning Worklist
8. Which part of a guided performance analysis is done with the SQL Monitor tool?
Choose the correct answer.
X
A Collect runtime data in the productive system
X
B Do static SQL checks in the productive system
X
C Do static SQL checks in the development system
X
D Combine runtime data and static check results
9. Why are SQL Monitor measurements not immediately visible?
136
© Copyright. All rights reserved.
Unit 2: Learning Assessment
10. Which of the SQL performance rules become more important with SAP HANA?
Choose the correct answers.
X
A Keep the result set small
X
B Minimize amount of transferred data
X
C Minimize number of database accesses
X
D Minimize search overhead
X
E Keep unnecessary load away from the DB
11. Which of the SQL performance rules become less important with SAP HANA?
Choose the correct answers.
X
A Keep the result set small
X
B Minimize amount of transferred data
X
C Minimize number of database accesses
X
D Minimize search overhead
X
E Keep unnecessary load away from the DB
© Copyright. All rights reserved.
137
Unit 2: Learning Assessment
138
© Copyright. All rights reserved.
UNIT 3
Database Independent Code-toData
Lesson 1
Classical Open SQL and Its Limitations
141
Lesson 2
Enhanced Open SQL
Exercise 9: Use Features of Enhanced Open SQL
145
151
Lesson 3
The Basics of Core Data Services in ABAP
Exercise 10: Create a Core Data Services View and Use It in ABAP
158
169
Lesson 4
Associations in Core Data Services
Exercise 11: Use Associations in Core Data Services in ABAP
180
185
Lesson 5
Outlook: More Interesting Features of CDS
Exercise 12: Optional: Define and Use a CDS View with Input Parameter
193
199
UNIT OBJECTIVES
●
Know the limitations of classical Open SQL
●
Describe the motivation for enhanced Open SQL
●
Use the new syntax of Open SQL
●
Use new features of Open SQL in SELECT statements
●
Describe the concept of ABAP Core Data Services
●
Use expressions, joins, aggregations, grouping and filtering in CDS views
●
Use Open SQL to select data based on CDS views
●
Use CDS views with associations
●
Explain CDS view extensions
© Copyright. All rights reserved.
139
Unit 3: Database Independent Code-to-Data
140
●
Define and use CDS views with input parameters
●
Explain authorization checks with CDS
© Copyright. All rights reserved.
Unit 3
Lesson 1
Classical Open SQL and Its Limitations
LESSON OVERVIEW
In this lesson you learn about the limitations of classical Open SQL and why it can only be
used to a limited extent to follow the code-to-data paradigm and benefit from the potential of
SAP HANA.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP applications
considerably by making use of SAP HANA, installed as a secondary database side-by-side
with the ABAP system.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Know the limitations of classical Open SQL
Standard SQL
Structured Query Language (SQL) is a language for accessing a database management
system. Although it is largely standardized (for example, as ANSI SQL), each vendor adds its
own features. The language can be divided into three parts, as follows:
Standard SQL — Much More Than Open SQL
Structured Query Language (SQL)
●
Largely standardized
●
Three sub-languages
Data Manipulation Language (DML)
●
Statements for reading and changing data in database tables
●
Examples include SELECT, INSERT, UPDATE, DELETE
Data Definition Language (DDL)
●
Statements for creating and administering database tables
●
Examples include CREATE, ALTER, DROP
Data Control Language (DCL)
●
Statements for authorization and transaction control
●
Examples include GRANT, REVOKE, COMMIT, ROLLBACK
© Copyright. All rights reserved.
141
Unit 3: Database Independent Code-to-Data
Database Integration in AS ABAP
The SQL variant known to ABAP programmers is called Open SQL. This Open SQL covers only
a small fraction of the SQL language. In fact, it only covers a small part of the DML sublanguage.
SQL in ABAP (Before 7.40 SP05)
Animation:
For more information on , please view the animation in the lesson Classical Open
SQL and Its Limitations, online in the SAP Learning Hub.
Open SQL
●
Database independent syntax
●
Database independent semantics (= same result)
●
Covers only a small part of standard DML
●
No DDL or DCL statements
ABAP Dictionary
●
Database independent tool (mostly graphical)
●
Create and maintain definitions of database objects (tables, views)
●
Covers only a small part of standard DDL features
And DCL?
●
No access control on DB level. In ABAP systems, the DB only knows one user.
●
No transaction control on DB level. DB commit after each dialogue step.
Open SQL, Native SQL and the Database Interface
Figure 101: Open SQL, Native SQL and the Database Interface
142
© Copyright. All rights reserved.
Lesson: Classical Open SQL and Its Limitations
Animation: Open SQL, Native SQL and the Database Interface
For more information on Open SQL, Native SQL and the Database Interface,
please view the animation in the lesson Classical Open SQL and Its Limitations,
online in the SAP Learning Hub.
The database independence of Open SQL is ensured by the following two layers:
●
●
The database interface (DBI) provides a database independent interface and additional
services, such as automatic client handling or the ABAP table buffer.
The database specific library (DBSL) connects to the respective database and translates
Open SQL statements into the respective native SQL dialect. When using the primary
database connection, the following occurs:
-
-
The ABAP system runs with a single database user (by default, SAP<SID> or SAPR3).
This user has many database privileges.
The ABAP system stores all data in the database schema corresponding to this user.
Figure 103: Example: Translation of Open SQL to Native SQL
Limitations of Classical Open SQL
One of the most important characteristics of Open SQL is its database independence. This is
not restricted to a database-independent syntax which is integrated into the ABAP language.
Open SQL is also semantically independent from the database that is used in a given ABAP
system.
The common syntax and semantics for all databases, is only one reason why Open SQL
covers only a small part of standard DML functionality.
Another reason is the fact that “Keep unnecessary load from the database” has always been
one of the golden SQL performance rules of ABAP. One way of enforcing this rule had been
not to offer too many SQL features that would have allowed developers to push calculationintense logic down to the database.
© Copyright. All rights reserved.
143
Unit 3: Database Independent Code-to-Data
Animation:
For more information on , please view the animation in the lesson Classical Open
SQL and Its Limitations, online in the SAP Learning Hub.
Limitations of Classical Open SQL (before 7.40 SP05)
With respect to standard DML
●
No fixed-values and computed columns
●
No CASE expression
●
No right outer joins
●
No UNIONs
●
No sub-queries in SELECT or FROM clauses
With respect to SAP HANA DML
●
No access to SAP HANA built-in functions, for example, DAYS_BETWEEN( )
●
No access to SAP HANA views and procedures
LESSON SUMMARY
You should now be able to:
●
144
Know the limitations of classical Open SQL
© Copyright. All rights reserved.
Unit 3
Lesson 2
Enhanced Open SQL
LESSON OVERVIEW
In this lesson, you learn about the new features and possibilities with which SAP enhanced
Open SQL starting with ABAP 7.40 SP05. You will see how, step by step, classical Open SQL
overcomes its old limitations in order to better support the code-to-data approach.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP applications
considerably by making use of SAP HANA, installed as a secondary database side-by-side
with the ABAP system.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Describe the motivation for enhanced Open SQL
●
Use the new syntax of Open SQL
●
Use new features of Open SQL in SELECT statements
Motivation for Enhanced Open SQL
Figure 104: What is Open SQL? Why Enhance It?
© Copyright. All rights reserved.
145
Unit 3: Database Independent Code-to-Data
ADBC and Native SQL can be used to get around the limitations of classic Open SQL.
However, working with Native SQL can be quite clumsy and prone to errors. Using Open SQL
would be more desirable in most cases.
Open SQL in the ABAP language is a database abstraction layer with an SQL-like syntax that
defines a common SQL semantics for all databases supported by SAP. It is not a simple
subset of SQL commands. The common semantics ensures that the result of an Open SQL
query is independent of the underlying database.
One of the reasons for using Native SQL was that the SQL-92 standard defines features that
were not previously available in Open SQL. For example, Open SQL lacked expressions and
had only limited JOIN types. ABAP developers may have wondered why SAP does not
minimize these limitations.
As of SAP NetWeaver 7.40 SP05, the scenarios in which Native SQL are necessary are
reduced, because Open SQL has been extended. These extensions are relevant regardless of
the database, but some of them are of particular importance when we think about the
performance guidelines for SAP HANA.
New Syntax of Open SQL
In order to be able to enhance the functional scope of Open SQL, SAP had to adjust the syntax
of Open SQL first.
Figure 105: New Open SQL Syntax in ABAP 7.40 SP05
Animation: New Open SQL Syntax in ABAP 7.40 SP05
For more information on New Open SQL Syntax in ABAP 7.40 SP05, please view
the animation in the lesson Enhanced Open SQL, online in the SAP Learning Hub.
The figure, New Open SQL Syntax in ABAP 7.40 SP05, illustrates the difference between old
and new syntax with an example. The first thing to notice is the comma-separated field list
after key word SELECT. This new syntax is a prerequisite to allow for more sophisticated
expressions in the SELECT clause.
146
© Copyright. All rights reserved.
Lesson: Enhanced Open SQL
Note:
With the new syntax, lists after additions ORDER BY and GROUP BY become
comma-separated too.
The second difference is the “@” symbol for escaping so-called host variables. The ABAP
language is considered the host of the embedded Open SQL, so host variable means ABAP
variable or constant inside the Open SQL statement. Every host variable except literals must
be escaped with a preceding “@” sign at every position in the statement.
Note:
Classical Open SQL syntax is still valid for “old” statements, that is, statements
that only use features that existed before release 7.40 SP05. As soon as a
statement uses a single new feature, the new syntax becomes mandatory.
It is not possible to mix old and new syntax in the same Open SQL statement.
Figure 107: New Open SQL Syntax in ABAP 7.50
Animation: New Open SQL Syntax in ABAP 7.50
For more information on New Open SQL Syntax in ABAP 7.50, please view the
animation in the lesson Enhanced Open SQL, online in the SAP Learning Hub.
With ABAP 7.50, a different order of some of the clauses of Open SQL statements is
supported.
The INTO clause no longer has to precede the WHERE clause, but can follow it. Additions such
as UP TO ... ROWS still have to follow the INTO clause.
The FROM clause can now be the first, followed by the column list starting with the explicit
keyword FIELDS. This does not only increase the readability and supportability of SELECT
statements, but also enables code completion in the ABAP Development Tools (ADT).
© Copyright. All rights reserved.
147
Unit 3: Database Independent Code-to-Data
New Features of Open SQL
Figure 109: New Features in Open SQL
As of release 7.40 SP05, Open SQL supports the use of arithmetic and string expressions, as
well as the CASE conditional expressions shown in the example.
A key point in the introduction of arithmetic expressions in Open SQL is their common
semantics. For example, the SQL standard does not specify the overflow behavior when
adding two integers or two P-type variables. This had to be accomplished in the definition of
the Open SQL semantics for such an operation.
Therefore, not all arithmetic expressions are available for all types of variables. Basic features
like ADDITION, SUBTRACTION, MULTIPLICATION, or the calculation of the absolute value
(ABS) are available for I-types and P-types with and without decimals. The MOD function is
only available for I- and P-types without decimals, CAST is only available for FLOAT typed
columns or host variables, and FLOOR and CEIL can be used for all P-types with decimals
(even mixed with I- and P-types without decimals).
In addition to arithmetic expressions, Open SQL now also features string expressions, and
string concatenation using the && operator.
148
© Copyright. All rights reserved.
Lesson: Enhanced Open SQL
Figure 110: Further Limitations Removed
Animation: Further Limitations Removed
For more information on Further Limitations Removed, please view the
animation in the lesson Enhanced Open SQL, online in the SAP Learning Hub.
RIGHT OUTER JOIN is now available in Open SQL. In addition, the limited support for using
brackets in JOIN expressions with more than two tables has been enhanced. Previously, the
JOIN had to be performed left-to-right, that is, the left-most tables always had to be joined
first. This limitation no longer applies.
New functionality with regard to the ON conditions of JOIN expressions is now also possible,
for example, as follows:
●
●
●
●
The previous restriction that a field of the right table is present in the ON condition has
been dropped.
Operators like BETWEEN or “greater than” or “less than” can be used in the ON condition
now.
Fields of the right table can also be used in the WHERE clause of a LEFT OUTER JOIN
statement.
Client handling in JOINs has been improved: if both sides of a JOIN are client-dependent,
the ON condition is enhanced automatically with a filter on equal clients. Additionally, the
client dependency is propagated to the top of the JOIN tree and applied in the WHERE
clause of the query statement. There is no need to contend with client fields in JOINs any
longer.
Apart from these new features, the following restrictions have been removed:
●
●
The maximum number of tables supported in Open SQL JOIN clauses has been increased
to 50.
The maximum number of sub-queries supported in an Open SQL statement has been
increased from 9 to 50.
© Copyright. All rights reserved.
149
Unit 3: Database Independent Code-to-Data
As usual, further details of the new features can be found on help.sap.com and in the ABAP
Keyword documentation in an SAP NetWeaver 7.40 SP05 system.
Figure 112: New in Open SQL in ABAP 7.5: UNION / UNION ALL
The syntax option to place the INTO clause at the end of the SELECT statement enables
support for forming the union of Open SQL SELECT statement results using UNION or UNION
ALL, as with ANSI SQL. Note that the SELECT statements comprised in the UNION [ALL]
must use explicit column lists, as an asterisk * is not supported. Additionally, the result of
UNION ALL can contain duplicates, whereas UNION implies DISTINCT.
150
© Copyright. All rights reserved.
Unit 3
Exercise 9
Use Features of Enhanced Open SQL
Simulation: Use Features of Enhanced Open SQL
For more information on Use Features of Enhanced Open SQL, please view the
simulation in the lesson Enhanced Open SQL online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program which reads a few columns from the database,
computes a few additional columns, and aggregates and groups the result. You want to use
the new Open SQL to perform these computations in the database.
Template:
Report HA400_NEW_OSQL_T1
Solution:
Report HA400_NEW_OSQL_S1
Task 1: Copy and Understand Templates
In system ZME, which uses Sybase as its primary database, create a copy of report
HA400_NEW_OSQL_T1 in your package (suggested name: ZHA400_##_NEW_OSQL, where
## is your group number). Analyze the source code, activate and execute the program.
1. If you are not still logged on, log on to system ZME on Sybase and start the ABAP
workbench.
2. Create a copy of the report. Place it in your ZHA400_## package and assign it to your
workbench task.
3. Analyze the source code of the get_data_template subroutine.
What data is read and from which database tables?
How is this data aggregated?
4. Activate and execute the program.
© Copyright. All rights reserved.
151
Unit 3: Database Independent Code-to-Data
Task 2: Use New SQL Features to Do the Aggregation in One SELECT Statement
In the get_data_solution subroutine, implement a left outer join on SCARR and SBOOK. Use
SQL CASE and aggregation function SUM( ) to calculate all three sums in one SELECT
Statement.
1. Edit your program. In the get_data_solution subroutine, you find a SELECT statement that
is commented out. Remove the comments and perform a syntax check.
The syntax check asks you to use new Open SQL Syntax. Which part of the statement is
the reason for that?
Which changes are necessary to switch from classic Open SQL to new Open SQL syntax?
2. Make these changes to switch from classic Open SQL to new Open SQL syntax.
3. Optionally, you can change the sequence of clauses. Place the field list after the from
clause and add the introductory key word FIELDS. Move the INTO and CONNECTION
clauses to the very end of the statement.
Note:
The field list after the from clause allows you to use code completion when
editing the field list. The INTO clause at the end makes the target data object
easier to spot.
4. Edit the field list. Use SQL CASE within each of the three SUM( ) functions to make sure
that LOCCURAM is only added if the booking belongs to the respective flight class, that is,
if field CLASS has the right value.
5. Activate and test your program to verify that the data has been read correctly.
152
© Copyright. All rights reserved.
Unit 3
Solution 9
Use Features of Enhanced Open SQL
Simulation: Use Features of Enhanced Open SQL
For more information on Use Features of Enhanced Open SQL, please view the
simulation in the lesson Enhanced Open SQL online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program which reads a few columns from the database,
computes a few additional columns, and aggregates and groups the result. You want to use
the new Open SQL to perform these computations in the database.
Template:
Report HA400_NEW_OSQL_T1
Solution:
Report HA400_NEW_OSQL_S1
Task 1: Copy and Understand Templates
In system ZME, which uses Sybase as its primary database, create a copy of report
HA400_NEW_OSQL_T1 in your package (suggested name: ZHA400_##_NEW_OSQL, where
## is your group number). Analyze the source code, activate and execute the program.
1. If you are not still logged on, log on to system ZME on Sybase and start the ABAP
workbench.
a) Perform this step as before.
2. Create a copy of the report. Place it in your ZHA400_## package and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
3. Analyze the source code of the get_data_template subroutine.
What data is read and from which database tables?
Carrier ID (field CARRID) and carrier name (field CARRNAME) and currency code (Field
CURRCODE) from table SCARR plus the flight class (field CLASS) and the ticket price
(field LOCCURAM) in the local currency of the carrier.
© Copyright. All rights reserved.
153
Unit 3: Database Independent Code-to-Data
How is this data aggregated?
In a nested loop, three sums are calculated per carrier. The total revenue in first class,
business class, and economy class.
4. Activate and execute the program.
a) Complete this step as you learned to do in previous classes.
Task 2: Use New SQL Features to Do the Aggregation in One SELECT Statement
In the get_data_solution subroutine, implement a left outer join on SCARR and SBOOK. Use
SQL CASE and aggregation function SUM( ) to calculate all three sums in one SELECT
Statement.
1. Edit your program. In the get_data_solution subroutine, you find a SELECT statement that
is commented out. Remove the comments and perform a syntax check.
The syntax check asks you to use new Open SQL Syntax. Which part of the statement is
the reason for that?
The field CANCELLED in the WHERE clause. In classic Open SQL fields of the right table of
a left outer join are not allowed in the WHERE clause.
Which changes are necessary to switch from classic Open SQL to new Open SQL syntax?
Column-separated field list after SELECT, column-separated fields after GROUP BY, and
prefix @ before data object ct_carriers.
2. Make these changes to switch from classic Open SQL to new Open SQL syntax.
a) See source code extract from the model solution.
3. Optionally, you can change the sequence of clauses. Place the field list after the from
clause and add the introductory key word FIELDS. Move the INTO and CONNECTION
clauses to the very end of the statement.
Note:
The field list after the from clause allows you to use code completion when
editing the field list. The INTO clause at the end makes the target data object
easier to spot.
a) See source code extract from the model solution.
4. Edit the field list. Use SQL CASE within each of the three SUM( ) functions to make sure
that LOCCURAM is only added if the booking belongs to the respective flight class, that is,
if field CLASS has the right value.
a) See source code extract from the model solution.
5. Activate and test your program to verify that the data has been read correctly.
a) Complete this step as before.
154
© Copyright. All rights reserved.
Lesson: Enhanced Open SQL
b) Verify that your code matches the following solution:
Source code extract from the model solution (Program HA400_NEW_OSQL_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_carriers TYPE ty_t_carriers.
TYPES: BEGIN OF ty_s_scarr,
carrid
TYPE scarr-carrid,
carrname TYPE scarr-carrname,
currcode TYPE scarr-currcode,
END OF ty_s_scarr.
TYPES: BEGIN OF ty_s_sbook,
carrid
TYPE sbook-carrid,
class
TYPE sbook-class,
loccurkey TYPE sbook-loccurkey,
loccuram TYPE sbook-loccuram,
END OF ty_s_sbook.
DATA ls_carrier TYPE ty_s_carrier.
DATA: lt_scarr TYPE SORTED TABLE OF ty_s_scarr
WITH UNIQUE KEY carrid,
ls_scarr TYPE ty_s_scarr.
DATA: lt_sbook TYPE SORTED TABLE OF ty_s_sbook
WITH NON-UNIQUE KEY carrid,
ls_sbook TYPE ty_s_sbook.
* Classic Open SQL
SELECT carrid carrname currcode
FROM scarr
CONNECTION (pv_dbcon)
INTO TABLE lt_scarr.
SELECT carrid class loccurkey loccuram
FROM sbook
CONNECTION (pv_dbcon)
INTO TABLE lt_sbook
WHERE cancelled <> 'X'.
LOOP AT lt_scarr INTO ls_scarr.
CLEAR ls_carrier.
LOOP AT lt_sbook INTO ls_sbook
WHERE carrid = ls_scarr-carrid.
IF ls_sbook-loccurkey <> ls_scarr-currcode.
MESSAGE 'Inconsistent data' TYPE 'A'.
ENDIF.
CASE ls_sbook-class.
WHEN 'F'. "First Class Booking
ls_carrier-revenue_first =
ls_carrier-revenue_first
+ ls_sbook-loccuram.
WHEN 'C'. "Business Class Booking
ls_carrier-revenue_business = ls_carrier-revenue_business
+ ls_sbook-loccuram.
WHEN 'Y'. "Economy Class Booking
ls_carrier-revenue_economy =
ls_carrier-revenue_economy
© Copyright. All rights reserved.
155
Unit 3: Database Independent Code-to-Data
+ ls_sbook-loccuram.
ENDCASE.
ENDLOOP.
MOVE-CORRESPONDING ls_scarr TO ls_carrier.
APPEND ls_carrier TO ct_carriers.
ENDLOOP.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_carriers TYPE ty_t_carriers.
* Use new SQL features like CASE to read all data in one SELECT
statement
*
* Note the possibility to change the sequence of clauses * in Enhanced
Open SQL:
*
- FROM clause before the field list enables code completion
*
(key word FIELD required for this)
*
- INTO clause at the end makes target data object easier to spot
SELECT FROM scarr AS a LEFT OUTER JOIN sbook AS b
ON a~carrid = b~carrid
FIELDS a~carrid,
a~carrname,
a~currcode,
SUM( CASE b~class
WHEN 'F' THEN b~loccuram
ELSE
0
END
) AS revenue_first,
SUM( CASE b~class
WHEN 'C' THEN b~loccuram
ELSE
0
END
) AS revenue_business,
SUM( CASE b~class
WHEN 'Y' THEN b~loccuram
ELSE
0
END
) AS revenue_economy
WHERE b~cancelled <> 'X'
OR b~cancelled IS NULL
GROUP BY a~carrid, a~carrname, a~currcode
ORDER BY a~carrid
INTO TABLE @ct_carriers
CONNECTION (pv_dbcon).
ENDFORM.
156
"
© Copyright. All rights reserved.
Lesson: Enhanced Open SQL
LESSON SUMMARY
You should now be able to:
●
Describe the motivation for enhanced Open SQL
●
Use the new syntax of Open SQL
●
Use new features of Open SQL in SELECT statements
© Copyright. All rights reserved.
157
Unit 3
Lesson 3
The Basics of Core Data Services in ABAP
LESSON OVERVIEW
In this lesson, you learn how to define database views using Core Data Services (CDS) in
ABAP. You also learn to use expressions, joins, aggregations, grouping, and filtering in CDS
views; to use union in CDS views; to use Open SQL to select data based on CDS views; and to
enhance a CDS view.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP applications
considerably by making use of SAP HANA. The ABAP system has been migrated to use SAP
HANA as its primary database already.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Describe the concept of ABAP Core Data Services
●
Use expressions, joins, aggregations, grouping and filtering in CDS views
●
Use Open SQL to select data based on CDS views
The Concept of Core Data Services (CDS)
SAP HANA supports SQL as a means to define, read, and manipulate data. On top of SQL,
many technologies introduce higher-level models to add semantics and ease consumption,
such as Open Data Protocol (OData), the Energy Data Management (EDM) models, the
semantic layer in the Business Intelligence (BI) platform, Java Persistence API (JPA),
enterprise objects in Java, and the business objects frameworks in ABAP. These higher-level
models share many commonalities, but are usually specific to their technology. This prevents
their re-use across stacks and increases effort for application developers. To address this,
SAP introduces a set of domain-specific languages and services, called CDS, for defining and
consuming semantically rich data models.
158
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Figure 114: CDS: Domain-Specific Languages
Animation: CDS: Domain-Specific Languages
For more information on CDS: Domain-Specific Languages, please view the
animation in the lesson The Basics of Core Data Services in ABAP, online in the
SAP Learning Hub.
The CDS consists of the following three sub-languages addressing the different sub-domains
of data modeling and access:
Data Definition Language (DDL)
The DDL part of CDS can be considered an enhancement of SQL that allows you to define
semantically rich database tables and views, often referred to as CDS entities, and userdefined types in the database. This allows you to simplify and harmonize the way you
define and consume your data models. The enhancements include annotations to enrich
the data models with additional (domain-specific) metadata and associations on a
conceptual level, replacing joins with simple path expressions in queries.
Query Language (QL)
Views defined using the CDS DDL can be consumed in ABAP programs using the Open
SQL query language, as well as in other CDS views. Open SQL has been extended to
provide support for CDS entities. In addition, it is possible to query the CDS features
supported by the underlying database before executing the Open SQL statement to
enable alternative implementations.
Data Control Language (DCL)
The DCL is used to define authorizations for CDS entities in a declarative way. The ABAP
CDS authorization concept is a new concept and can be used independently or in
combination with the classic concept. Whereas the classic authorization concept is
based on authorization objects and the authorizations are checked either implicitly (when
transactions are called) or explicitly (using the statement AUTHORITY CHECK), the CDS
authorization concept is based on implicit checks automatically performed by the ABAP
runtime when the CDS entity is accessed using Open SQL.
© Copyright. All rights reserved.
159
Unit 3: Database Independent Code-to-Data
Figure 116: Core Data Services in ABAP
Animation: Core Data Services in ABAP
For more information on Core Data Services in ABAP, please view the animation
in the lesson The Basics of Core Data Services in ABAP, online in the SAP
Learning Hub.
CDS are not only an integral part of SAP HANA, but can also be leveraged in the ABAP stack
and are optimally integrated into the ABAP Dictionary and language. The corresponding new
ABAP Repository object types Data Definition (also known as DDL Source) and Access
Control (also known as DCL Source), for defining enhanced view entities in ABAP, allow you to
push more data-intensive calculations to the database than is possible using classical ABAP
Dictionary views.
You can use ABAP CDS views to read data and calculate additional information while reading
data. ABAP CDS views do not support data modifications.
160
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
CDS Views and Classical Dictionary Views
Figure 118: Benefits of CDS Views Compared to ABAP Dictionary Views
ABAP CDS share views with ABAP Dictionary that are supported on all database systems and
supported by the ABAP stack. However, ABAP CDS views provide the following additional
capabilities:
●
●
●
Enhanced support for combining queries, such as UNION and outer joins.
Support for calculations that use expressions in the column list and for selection, as well as
aggregation and grouping in the data model.
Ability to be nested, which allows for more design for re-use.
© Copyright. All rights reserved.
161
Unit 3: Database Independent Code-to-Data
Figure 119: Advanced View Definition in ABAP 7.4 SP2 and higher
Support for CDS in ABAP begins with ABAP 7.4 SP2, as follows:
●
CDS view definitions support more features than ABAP Dictionary views.
●
CDS leverages the ABAP Dictionary-type system.
●
●
CDS leverages the ABAP infrastructure to ensure Open SQL-like behavior and support for
all database platforms supported by the ABAP stack.
CDS does not support the full SQL-92 standard or SAP HANA-specific features.
With SAP NetWeaver AS ABAP 7.40 SP5, associations between entities add a new conceptual
level. They can be used to replace joins with simple path expressions in queries to ease the
consumption of data models. Associations go beyond the traditional ABAP Dictionary view
and SQL92 capabilities.
The goal of ABAP CDS is to fully support the SQL-92 standard and beyond that additional
features such as associations, entities, Create, Read, Update, Delete (CRUD), and OData
services.
162
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Basic CDS View Definition
Figure 120: Basic CDS View Definition
To create CDS views, do the following:
●
Use the ABAP Development Tools. The ABAP Workbench does not support the new type of
ABAP repository objects called data definitions.
Note:
Data definitions were first introduced under the name of “DDL Sources”.
●
●
In the ABAP project tree, select the package to contain the CDS view and choose the
context menu entry New → Other ABAP Repository Object → Dictionary → Data Definition.
Use the DDL statement DEFINE VIEW and SQL-like syntax to define the view.
Each active ABAP CDS view has a corresponding SQL view. The SQL view is the CDS view’s
representation on the database but it can also be found in ABAP Dictionary as a view
definition. The SQL view in the Dictionary and on the database is generated, updated, and
deleted automatically when activating the data definition.
© Copyright. All rights reserved.
163
Unit 3: Database Independent Code-to-Data
Figure 121: CDS SQL View in the ABAP Dictionary and on the Database
You can display the (native) SQL statement that is sent to the database to create the view as
follows:
●
●
164
In the data definition, place the cursor on the value of the AbapCatalog.sqlViewName
annotation, press F3 or Control to turn the value into a link, and click the link. This opens
the ABAP Dictionary view.
In the menu of the ABAP Dictionary screen, choose Extras → CREATE statement to see the
native SQL statement used by the system to create the corresponding database view.
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Figure 122: Use of Annotations in CDS Views
Annotations allow for the specification of ABAP-specific additional information, such as how
records of the view should be buffered by the ABAP table buffer, or whether the view is clientdependent or not. By default, CDS views are considered client-dependent, and you do not
have to include client fields explicitly in the field list or in the join conditions.
The annotation @AbapCatalog.sqlViewName is mandatory, and specifies the name of the
representation of the CDS View in the ABAP Dictionary and the database.
SQL Features in CDS Views
Figure 123: Select List – Support for Expressions in CDS Views
© Copyright. All rights reserved.
165
Unit 3: Database Independent Code-to-Data
Like enhanced Open SQL, CDS supports various expressions, such as the following:
●
●
●
●
●
●
●
●
The simplest form of expression is a numerical or string literal.
Arithmetic expressions using operators +, -, *, / or the unary -, or using built-in functions
such as CEIL and MOD.
String expressions, including the string concatenation operator &&, or built-in functions,
such as LPAD, CONCAT, REPLACE, and SUBSTRING.
Special built-in functions can be used: COALESCE to replace null values in results,
CURRENCY_CONVERSION, and UNIT_CONVERSION to convert between currencies,
respectively units.
Some built-in functions and the division operator are available only from ABAP 7.40 SP08
onwards.
CAST expressions, with which the data type of values can be converted.
CASE expressions, which can be nested. An alias name is required for the resulting
column, except for nested CASE. The resulting column type is derived from expressions
after the THEN and ELSE clause.
Functions for calculations with dates and timestamps (as of ABAP 7.50)
Figure 124: Support for Joins, WHERE, Aggregations, Grouping, and Filtering in CDS Views
166
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Animation: Support for Joins, WHERE, Aggregations, Grouping, and Filtering in
CDS Views
For more information on Support for Joins, WHERE, Aggregations, Grouping, and
Filtering in CDS Views, please view the animation in the lesson The Basics of
Core Data Services in ABAP, online in the SAP Learning Hub.
Like (Open) SQL, ABAP CDS supports the following:
●
●
●
A WHERE clause in a view definition
INNER joins, LEFT OUTER and RIGHT OUTER joins. The join condition can be specified
after the projection list when using the Open SQL-like syntax, or before the projection list
when using the curly bracket syntax. If joins are used, no asterisk is supported on SELECT
statements.
The calculation of aggregations, grouping records, and filtering groups. The GROUP BY
and HAVING clauses may be familiar from Open SQL or standard SQL aggregations.
Figure 126: Unions
Animation: Unions
For more information on Unions, please view the animation in the lesson The
Basics of Core Data Services in ABAP, online in the SAP Learning Hub.
Using the UNION and UNION ALL keywords, you can define views that merge the results of
two or more queries. This may be known from standard SQL. Similar to standard SQL, the
following occurs:
●
●
Using keyword UNION, the combined result contains no duplicate rows, that is, UNION
implies DISTINCT.
Using keyword UNION ALL, the results are basically combined immediately, and duplicate
rows are not removed.
© Copyright. All rights reserved.
167
Unit 3: Database Independent Code-to-Data
●
Matching columns must be in the same order and of a compatible type.
CDS Views in Open SQL SELECT Statements
Figure 128: CDS Views in ABAP Programming
Animation: CDS Views in ABAP Programming
For more information on CDS Views in ABAP Programming, please view the
animation in the lesson The Basics of Core Data Services in ABAP, online in the
SAP Learning Hub.
To select data from a CDS view, use the CDS View name in the FROM clause of an Open SQL
SELECT statement. If the FROM clause of an Open SQL SELECT statement contains a CDS
view name, the statement has to follow the new Open SQL syntax rules, that is, commaseparated field lists and escape character “@” for ABAP data objects are mandatory.
Note:
Although it is also possible to use the SQL View name, this is not recommended
and became fully deprecated with AS ABAP 7.50.
168
© Copyright. All rights reserved.
Unit 3
Exercise 10
Create a Core Data Services View and Use It in
ABAP
Simulation: Create a Core Data Services View and Use It in ABAP
For more information on Create a Core Data Services View and Use It in ABAP,
please view the simulation in the lesson The Basics of Core Data Services in
ABAP online in the SAP Learning Hub.
Business Example
Your ABAP program contains a considerably complicated SELECT statement. You want to reuse this select statement in other programs. To achieve this, you define a CDS View and use it
in your ABAP program.
Template:
Report HA400_CDS_VIEW_T1
Solution:
Report HA400_CDS_VIEW_S1
Data Definition HA400_CDS_S1 (defining CDS View Ha400_Cds_S1 and SQL View
HA400_CDS_SQL_S1)
Task 1: Copy and Understand the Template
In the system that has SAP HANA as a primary database, create a copy of report
HA400_CDS_VIEW_T1 in your package (suggested name: ZHA400_##_CDS_1, where ## is
your group number). Analyze the source code, activate and execute the program.
Hint:
In this exercise, you have to create and implement the definition of a CDS view.
This new type of repository object can only be edited in ABAP Development
Tools (ADT). The ABAP program you can edit in the classical ABAP workbench.
But you might want to take the opportunity and do the complete exercise in ADT.
1. If you are still logged on to system ZME, log off and log on to the system labelled T8N on
SAP HANA.
2. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
© Copyright. All rights reserved.
169
Unit 3: Database Independent Code-to-Data
Hint:
In ABAP Development Tools, you copy the report via context menu item
Duplicate.
3. Analyze the SELECT statement in subroutine get_data_template.
From which database tables does the SELECT statement read its data?
Which fields are read from these database tables?
How is field COUNT calculated?
How is field DAYS_SUM calculated?
4. Analyze the LOOP ... ENDLOOP in subroutine get_data_template.
What’s the purpose of this LOOP?
Why can’t this average be calculated via aggregate function AVG( )?
5. Activate and execute the program.
Task 2: Create and Implement a Data Definition (DDL Source)
Create a new data definition (suggested name: ZHA400_##_CDS1, where ## stands for your
group number) that defines a CDS view (suggested name: Zha400_##_Cds1) and an SQL
view (suggested name: ZHA400_##_SQL1). Make sure it selects the same data as subroutine
get_data_template of your program.
170
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Note:
In CDS ABAP, you can not use an SQL function (dats_days_between() in our
example) as argument of an aggregate function (AVG( ) in our example). The final
solution will be a CDS view, that reads from another CDS view (view-on-view
approach). In a first step, we implement a CDS view that only calculates the
number of days between booking date and flight date. The aggregation can then
be done by the Open SQL statement.
1. Using ABAP Development Tools for Eclipse, create a new data definition (= DDL Source)
based on template Define View With Join.
2. Within the DDL source, set the name of the SQL view within the sqlViewName annotation.
3. Edit the FROM clause of the generated SELECT statement. Replace
data_source_name with SBOOK as B and joined_data_source_name with
SCUSTOM as C to read data from these two tables
4. In the FROM clause, replace the generated join condition with ON B.customid = C.ID
5. Edit the field list of the generated SELECT statement. Read the same fields, in the same
sequence as in the SELECT statement of subroutine get_data_template. But instead of the
two aggregate functions SUM( ) and COUNT( * ), only calculate the number of days
between booking date and flight date.
Read the following fields:
a) From table SCUSTOM: fields ID, NAME, POSTCODE, CITY, COUNTRY.
b) From table SBOOK: expression dats_days_between( ORDER_DATE, FLDATE). Don’t
forget to provide an alias for the calculated field (suggested name: days_ahead).
Hint:
You can reduce the typing effort by making use of the editor’s code
completion capabilities.
6. After the field list, add a WHERE clause. Exclude all bookings that are cancelled.
7. Why can't you add the ORDER BY addition?
8. Save and activate the data definition.
Task 3: Test the CDS View
Test your CDS View by displaying the data preview.
1. Open the data preview for the CDS View.
Task 4: Use the ABAP CDS View in an Open SQL Statement
In subroutine get_data_solution of your program, implement a select statement from your
CDS View.
© Copyright. All rights reserved.
171
Unit 3: Database Independent Code-to-Data
1. Edit your program (either in SE80 or ADT). In subroutine get_data_solution, implement a
select statement that reads the relevant data from your CDS view .
Hint:
Remember that the CDS view contains neither an ORDER BY clause nor an
aggregation of the calculated number of days.
Note:
If you use the CDS view name (recommended), you have to use the new Open
SQL syntax. If you use the SQL view name (not recommended) you may still
use classical Open SQL Syntax.
2. Activate and test your program to verify that the data has been read correctly.
172
© Copyright. All rights reserved.
Unit 3
Solution 10
Create a Core Data Services View and Use It in
ABAP
Simulation: Create a Core Data Services View and Use It in ABAP
For more information on Create a Core Data Services View and Use It in ABAP,
please view the simulation in the lesson The Basics of Core Data Services in
ABAP online in the SAP Learning Hub.
Business Example
Your ABAP program contains a considerably complicated SELECT statement. You want to reuse this select statement in other programs. To achieve this, you define a CDS View and use it
in your ABAP program.
Template:
Report HA400_CDS_VIEW_T1
Solution:
Report HA400_CDS_VIEW_S1
Data Definition HA400_CDS_S1 (defining CDS View Ha400_Cds_S1 and SQL View
HA400_CDS_SQL_S1)
Task 1: Copy and Understand the Template
In the system that has SAP HANA as a primary database, create a copy of report
HA400_CDS_VIEW_T1 in your package (suggested name: ZHA400_##_CDS_1, where ## is
your group number). Analyze the source code, activate and execute the program.
Hint:
In this exercise, you have to create and implement the definition of a CDS view.
This new type of repository object can only be edited in ABAP Development
Tools (ADT). The ABAP program you can edit in the classical ABAP workbench.
But you might want to take the opportunity and do the complete exercise in ADT.
1. If you are still logged on to system ZME, log off and log on to the system labelled T8N on
SAP HANA.
a) Perform this step as before.
2. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
© Copyright. All rights reserved.
173
Unit 3: Database Independent Code-to-Data
Hint:
In ABAP Development Tools, you copy the report via context menu item
Duplicate.
a) Complete this step as before.
3. Analyze the SELECT statement in subroutine get_data_template.
a) Complete this step as before.
From which database tables does the SELECT statement read its data?
From tables SBOOK and SCUSTOM (inner join)
Which fields are read from these database tables?
Customer number (field ID), customer name (field NAME) and the address data (fields
POSTCODE, CITY, COUNTRY) are read from table SCUSTOM. From table SBOOK come
the booking date (field ORDER_DATE) and flight date (field FLDATE).
How is field COUNT calculated?
Aggregate function COUNT( * ) is used to calculate the total number of bookings per
customer.
How is field DAYS_SUM calculated?
Aggregate function SUM( ) is used to calculate the total number of days between booking
date and flight date per customer. The number of days itself is calculated via SQL function
dats_days_between( ).
4. Analyze the LOOP ... ENDLOOP in subroutine get_data_template.
a) Complete this step as before.
What’s the purpose of this LOOP?
Calculate the average number of days between booking date and flight date per customer.
Why can’t this average be calculated via aggregate function AVG( )?
In Open SQL, aggregate function AVG( ) does not support expressions like SQL function
dats_days_between( ) as argument.
5. Activate and execute the program.
174
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
a) Complete this step as you learned to do in previous classes.
Task 2: Create and Implement a Data Definition (DDL Source)
Create a new data definition (suggested name: ZHA400_##_CDS1, where ## stands for your
group number) that defines a CDS view (suggested name: Zha400_##_Cds1) and an SQL
view (suggested name: ZHA400_##_SQL1). Make sure it selects the same data as subroutine
get_data_template of your program.
Note:
In CDS ABAP, you can not use an SQL function (dats_days_between() in our
example) as argument of an aggregate function (AVG( ) in our example). The final
solution will be a CDS view, that reads from another CDS view (view-on-view
approach). In a first step, we implement a CDS view that only calculates the
number of days between booking date and flight date. The aggregation can then
be done by the Open SQL statement.
1. Using ABAP Development Tools for Eclipse, create a new data definition (= DDL Source)
based on template Define View With Join.
a) In the ABAP perspective of Eclipse, right-click on your package and choose New
→ Other ABAP Repository Object.
b) On the next window, choose Core Data Services→Data Definition.
c) Enter the name of your package, a name, and a short description for the new
repository object and choose Next.
d) Assign the object to your transport request and choose Next.
e) Click on template Define View With Join and choose Finish.
2. Within the DDL source, set the name of the SQL view within the sqlViewName annotation.
a) In the first line of the editor, replace sql_view_name with ZHA400_##_SQL1, where
## stands for your group number.
See source code extract from the model solution.
3. Edit the FROM clause of the generated SELECT statement. Replace
data_source_name with SBOOK as B and joined_data_source_name with
SCUSTOM as C to read data from these two tables
a) See source code extract from the model solution.
4. In the FROM clause, replace the generated join condition with ON B.customid = C.ID
a) See source code extract from the model solution.
5. Edit the field list of the generated SELECT statement. Read the same fields, in the same
sequence as in the SELECT statement of subroutine get_data_template. But instead of the
two aggregate functions SUM( ) and COUNT( * ), only calculate the number of days
between booking date and flight date.
Read the following fields:
a) From table SCUSTOM: fields ID, NAME, POSTCODE, CITY, COUNTRY.
b) From table SBOOK: expression dats_days_between( ORDER_DATE, FLDATE). Don’t
forget to provide an alias for the calculated field (suggested name: days_ahead).
© Copyright. All rights reserved.
175
Unit 3: Database Independent Code-to-Data
Hint:
You can reduce the typing effort by making use of the editor’s code
completion capabilities.
a) Place the cursor between the curly brackets (“{ })” . Then invoke the code-completion
by pressing Ctrl + Space on your keyboard.
b) See source code extract from the model solution.
6. After the field list, add a WHERE clause. Exclude all bookings that are cancelled.
a) See source code extract from the model solution.
7. Why can't you add the ORDER BY addition?
ORDER BY is not supported in CDS View definitions.
8. Save and activate the data definition.
a) Choose Save.
b) Choose Activate.
c) Verify that your code matches the following model solution:
Source Code extract from the Model Solution (Data Definition HA400_CDS_S1)
@AbapCatalog.sqlViewName: 'HA400_CDS_SQL_S1'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Solution: CDS view Booking with Customer'
define view HA400_CDS_S1 as select
from sbook as b inner join scustom as c
on b.customid = c.id
{
c.id,
c.name,
c.postcode,
c.city,
c.country,
dats_days_between( b.order_date, b.fldate ) as days_ahead
}
where b.cancelled <> 'X'
Task 3: Test the CDS View
Test your CDS View by displaying the data preview.
1. Open the data preview for the CDS View.
a) Right-click anywhere in the data definition (DDL Source) and choose the contextual
menu item Open With → Data Preview.
Task 4: Use the ABAP CDS View in an Open SQL Statement
In subroutine get_data_solution of your program, implement a select statement from your
CDS View.
1. Edit your program (either in SE80 or ADT). In subroutine get_data_solution, implement a
select statement that reads the relevant data from your CDS view .
176
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
Hint:
Remember that the CDS view contains neither an ORDER BY clause nor an
aggregation of the calculated number of days.
Note:
If you use the CDS view name (recommended), you have to use the new Open
SQL syntax. If you use the SQL view name (not recommended) you may still
use classical Open SQL Syntax.
a) See source code extract from the model solution.
2. Activate and test your program to verify that the data has been read correctly.
a) Complete this step as before.
b) Verify that your code matches the following solution:
Source Code extract from the Model Solution (Program HA400_CDS_VIEW_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Types for target fields
TYPES: BEGIN OF lty_s_cust,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode TYPE scustom-postcode,
city
TYPE scustom-city,
country TYPE scustom-country,
days_sum TYPE i,
count
TYPE i,
END OF lty_s_cust.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: lt_cust TYPE SORTED TABLE OF lty_s_cust
WITH NON-UNIQUE KEY id,
ls_cust TYPE lty_s_cust.
* Processing
*****************
CLEAR ct_customers.
© Copyright. All rights reserved.
177
Unit 3: Database Independent Code-to-Data
* Note 1: SQL Function dats_days_between( )
*
available in Open SQL as off Re. 7.51
* Note 2: In Open SQL, no expressions are allowed
*
as input for aggregate function AVG( )
SELECT FROM sbook AS b INNER JOIN scustom AS c
ON b~customid = c~id
FIELDS c~id,
c~name,
c~postcode,
c~city,
c~country,
SUM( dats_days_between( b~order_date, b~fldate) )
AS days_sum,
COUNT( * ) AS count
WHERE b~cancelled <> 'X'
GROUP BY c~id, c~name, c~postcode, c~city, c~country
ORDER BY c~id
INTO TABLE @lt_cust.
LOOP AT lt_cust INTO ls_cust.
ls_customer-id
= ls_cust-id.
ls_customer-name
= ls_cust-name.
ls_customer-postcode = ls_cust-postcode.
ls_customer-city
= ls_cust-city.
ls_customer-country = ls_cust-country.
* Note 3: Aggregate function AVG( ) always rounds down
*
ABAP rounds differently by default
*
to achieve identical results we enforce rounding down in ABAP
ls_customer-days_ahead =
round( val = ls_cust-days_sum / ls_cust-count
dec = 4
mode = cl_abap_math=>round_down ).
INSERT ls_customer INTO TABLE ct_customers.
ENDLOOP.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
SELECT FROM ha400_cds_s1
FIELDS id,
name,
postcode,
city,
country,
AVG( days_ahead ) AS days_ahead
GROUP BY id, name, postcode, city, country
ORDER BY id
INTO TABLE @ct_customers.
ENDFORM.
178
"
© Copyright. All rights reserved.
Lesson: The Basics of Core Data Services in ABAP
LESSON SUMMARY
You should now be able to:
●
Describe the concept of ABAP Core Data Services
●
Use expressions, joins, aggregations, grouping and filtering in CDS views
●
Use Open SQL to select data based on CDS views
© Copyright. All rights reserved.
179
Unit 3
Lesson 4
Associations in Core Data Services
LESSON OVERVIEW
In this lesson, you learn how to use associations in Core Data Services (CDS).
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use CDS views with associations
Associations to Express Relationships
Core Data Services (CDS) provide extended support for treating relationships between
entities. Such relationships are often reflected as foreign key relationships in the database,
but they are not treated as first-class citizens in SQL, especially in the Data Manipulation
Language (DML). As a consequence, using them to query data from several tables often
requires writing non-trivial join conditions. This is cumbersome and error-prone for
application developers, and requires considerable effort when joins are to be reused.
Figure 131: CDS Associations: Concept
CDS treat relationships, called associations, as first-class citizens to simplify reading
relationships between entities, using them, and defining CDS views for reuse.
Associations are defined within CDS views using the ASSOCIATION TO syntax, followed by
the target entity and an ON condition specifying how the entities are related. The syntax of the
ON condition is similar to the syntax for JOINs, making it easy to refactor JOINs into
associations. Specifying an alias for the target entity and a cardinality are optional.
180
© Copyright. All rights reserved.
Lesson: Associations in Core Data Services
Associations can be used in all places where column names or tables names can be used.
Ad-Hoc Associations vs. Exposed Associations
Figure 132: CDS Association Types
If the data definition that defines the association uses an individual field of the associated
table or CDS view, we call this an ad-hoc association . Ad-hoc associations are immediately
translated into a JOIN clause in the SQL create statement that is sent to the database.
The benefit of associations becomes much clearer when looking at exposed associations.
Instead of addressing individual fields of the associated table or CDS view, it is also possible to
add the entire association as a single element into the field list. This is called an exposed
association
If an association is exposed, the SQL CREATE statement does not contain the corresponding
JOIN clause, yet. The join is only constructed if the consumer of the view actually uses this
particular exposed association. This can be considered JOIN on demand.
Note:
A view definition can only expose an association if its field list also contains all its
fields that are mentioned in the ON condition. In the example above, this is field
CUSTOMID of table SBOOK.
© Copyright. All rights reserved.
181
Unit 3: Database Independent Code-to-Data
Using Exposed Associations
Figure 133: Using Exposed Associations
Exposed associations are helpful for the following reasons:
●
●
182
The Data Preview in the ABAP Development Tools (ADT) supports navigation along the
association.
CDS views defined on the basis of the view that exposes the association can use any
column of the associated entity. This can simplify defining views on top of other views.
© Copyright. All rights reserved.
Lesson: Associations in Core Data Services
Path Expressions in Open SQL
Figure 134: Consuming Associations in Open SQL
Animation: Consuming Associations in Open SQL
For more information on Consuming Associations in Open SQL, please view the
animation in the lesson Associations in Core Data Services, online in the SAP
Learning Hub.
Beginning with ABAP 7.50, Open SQL supports path expressions to allow consuming
associations in CDS views. Only simple path expressions without filter expressions are
supported so far, but they are supported in all clauses of the SELECT statement, such as the
field list, WHERE clause, ORDER BY clause, and so on.
Association names must be prefixed with a backslash.
© Copyright. All rights reserved.
183
Unit 3: Database Independent Code-to-Data
Filtered Associations
Figure 136: Filtered Associations
Animation: Filtered Associations
For more information on Filtered Associations, please view the animation in the
lesson Associations in Core Data Services, online in the SAP Learning Hub.
A third type of association is the filtered association. These are based on associations of
cardinality to-n and can be used both in the CDS view defining their base association as well
as in CDS views defined on top. To define a filtered association, you add a filter expression in
square brackets to the path expression. The filter expression is a conditional expression with
the following constraints:
●
●
●
The left-hand side of each condition must be a field of the target of the association.
The right-hand side of each condition must be a field of the target of the association, a
literal, or a parameter.
No path or other expressions or functions can be used.
A “1:” preceding the filter expression declares that the filter turns a “to-n” association into a
“to-1” associaition.
184
© Copyright. All rights reserved.
Unit 3
Exercise 11
Use Associations in Core Data Services in
ABAP
Simulation: Use Associations in Core Data Services in ABAP
For more information on Use Associations in Core Data Services in ABAP, please
view the simulation in the lesson Associations in Core Data Services online in the
SAP Learning Hub.
Business Example
You want to read from CDS views that contain associations to other data sources.
Template:
Report HA400_CDS_VIEW_S1
Solution:
Report HA400_CDS_VIEW_S2
Task 1: Copy and Understand Template Program
In system T8N, which has SAP HANA as a primary database, create a copy of your report
ZHA400_##_CDS_1 and place the new program in your package (suggested name:
ZHA400_##_CDS_2, where ## is your group number). If you did not complete the previous
exercise, you can copy from program HA400_CDS_View_S1 instead. Analyze the source
code, activate, and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the source code of subroutine get_data_solution.
3. Activate and execute the program.
Task 2: Analyze the Definition of a CDS View that Contains an Association
In ABAP Development Tools (ADT), open the definition of CDS View
HA400_Booking_With_Association. Analyze the DDL Source and display a data preview.
1. In ABAP Development Tools, open the definition of CDS View
HA400_Booking_With_Association.
2. In the DDL Source, analyze the FROM clause of the SELECT statement and compare it to
the FROM clause in the definition of CDS View HA400_CDS_S1.
© Copyright. All rights reserved.
185
Unit 3: Database Independent Code-to-Data
What difference is there in the FROM clause of the SELECT statement?
3. In the DDL Source, analyze the field list of the SELECT statement and compare it to the
field list in the definition of CDS View HA400_CDS_S1.
What is the meaning of element _customer of the field list?
Why are there no fields NAME, POSTCODE, CITY, COUNTRY?
4. Open the SQL create statement for the SQL view.
Why is there no mention of table SCUSTOM?
5. Open the data preview for CDS View HA400_Booking_With_Association, choose one of the
bookings and display details on the associated customer.
Task 3: Use the CDS View with Association in an Open SQL Statement
In subroutine get_data_solution of your program, read from CDS view
HA400_Booking_With_Association.
1. Edit your program. In subroutine get_data_solution, replace the CDS View in the FROM
clause with CDS view HA400_Booking_With_Association.
Why do you get syntax errors in the field list and the GROUP BY clause?
2. Adjust the field list and the GROUP BY clause to use components of the exposed
association.
Hint:
in Open SQL, the name of an exposed association has to be prefixed with “\”
and the component selector for associations is “-”.
3. Activate and test your program to verify that the data has been read correctly.
186
© Copyright. All rights reserved.
Unit 3
Solution 11
Use Associations in Core Data Services in
ABAP
Simulation: Use Associations in Core Data Services in ABAP
For more information on Use Associations in Core Data Services in ABAP, please
view the simulation in the lesson Associations in Core Data Services online in the
SAP Learning Hub.
Business Example
You want to read from CDS views that contain associations to other data sources.
Template:
Report HA400_CDS_VIEW_S1
Solution:
Report HA400_CDS_VIEW_S2
Task 1: Copy and Understand Template Program
In system T8N, which has SAP HANA as a primary database, create a copy of your report
ZHA400_##_CDS_1 and place the new program in your package (suggested name:
ZHA400_##_CDS_2, where ## is your group number). If you did not complete the previous
exercise, you can copy from program HA400_CDS_View_S1 instead. Analyze the source
code, activate, and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as described in the previous exercise.
2. Analyze the source code of subroutine get_data_solution.
a) Complete this step as described in the previous exercise.
3. Activate and execute the program.
a) Complete this step as described in the previous exercise.
Task 2: Analyze the Definition of a CDS View that Contains an Association
In ABAP Development Tools (ADT), open the definition of CDS View
HA400_Booking_With_Association. Analyze the DDL Source and display a data preview.
1. In ABAP Development Tools, open the definition of CDS View
HA400_Booking_With_Association.
a) Complete this step as described in the previous exercise.
© Copyright. All rights reserved.
187
Unit 3: Database Independent Code-to-Data
2. In the DDL Source, analyze the FROM clause of the SELECT statement and compare it to
the FROM clause in the definition of CDS View HA400_CDS_S1.
a) Complete this step as described in the previous exercise.
What difference is there in the FROM clause of the SELECT statement?
Instead of a join of database tables SBOOK and SCUSTOM, the view selects from
database table SBOOK only. In addition, it defines an association to database table
SCUSTOM.
3. In the DDL Source, analyze the field list of the SELECT statement and compare it to the
field list in the definition of CDS View HA400_CDS_S1.
a) Complete this step as described in the previous exercise.
What is the meaning of element _customer of the field list?
This is the name of the association, defined in the FROM clause. By listing the association
name in the element list, the view exposes the association, which means it makes the
association visible to a consumer of the view.
Why are there no fields NAME, POSTCODE, CITY, COUNTRY?
This information is accessible through the exposed association _Customer. It would be
redundant as well as ineffective to list them.
4. Open the SQL create statement for the SQL view.
a) In the editor window of the data definition (DDL Source), right-click and choose the
contextual menu item Show SQL CREATE statement.
Why is there no mention of table SCUSTOM?
Associations are not evaluated immediately. Table SCUSTOM will be joined to table
SBOOK if — and only if — the consumer of the view actually accesses fields from the
associated table.
5. Open the data preview for CDS View HA400_Booking_With_Association, choose one of the
bookings and display details on the associated customer.
a) Right-click anywhere in the data definition (DDL Source) and choose the contextual
menu item Open With → Data Preview.
b) Right-click one of the data records and choose Follow Association.
c) In the dialog box, choose _customer → scustom[0..1].
Task 3: Use the CDS View with Association in an Open SQL Statement
In subroutine get_data_solution of your program, read from CDS view
HA400_Booking_With_Association.
1. Edit your program. In subroutine get_data_solution, replace the CDS View in the FROM
clause with CDS view HA400_Booking_With_Association.
188
© Copyright. All rights reserved.
Lesson: Associations in Core Data Services
a) See source code extract from the model solution.
Why do you get syntax errors in the field list and the GROUP BY clause?
The new CDS view does not define fields NAME, POSTCODE, CITY, COUNTRY. It exposes
association _Customer, instead.
2. Adjust the field list and the GROUP BY clause to use components of the exposed
association.
Hint:
in Open SQL, the name of an exposed association has to be prefixed with “\”
and the component selector for associations is “-”.
a) See source code extract from the model solution.
3. Activate and test your program to verify that the data has been read correctly.
a) Complete this step as before.
b) Verify that your code matches the following solution:
Source Code extract from the Model Solution (Program HA400_CDS_VIEW_S2)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Types for target fields
TYPES: BEGIN OF lty_s_cust,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode TYPE scustom-postcode,
city
TYPE scustom-city,
country TYPE scustom-country,
days_sum TYPE i,
count
TYPE i,
END OF lty_s_cust.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: lt_cust TYPE SORTED TABLE OF lty_s_cust
WITH NON-UNIQUE KEY id,
ls_cust TYPE lty_s_cust.
* Processing
*****************
CLEAR ct_customers.
© Copyright. All rights reserved.
189
Unit 3: Database Independent Code-to-Data
* Note 1: SQL Function dats_days_between( )
*
available in Open SQL as off Re. 7.51
* Note 2: In Open SQL, no expressions are allowed
*
as input for aggregate function AVG( )
SELECT FROM sbook AS b INNER JOIN scustom AS c
ON b~customid = c~id
FIELDS c~id,
c~name,
c~postcode,
c~city,
c~country,
SUM( dats_days_between( b~order_date, b~fldate) )
AS days_sum,
COUNT( * ) AS count
WHERE b~cancelled <> 'X'
GROUP BY c~id, c~name, c~postcode, c~city, c~country
ORDER BY c~id
INTO TABLE @lt_cust.
LOOP AT lt_cust INTO ls_cust.
ls_customer-id
= ls_cust-id.
ls_customer-name
= ls_cust-name.
ls_customer-postcode = ls_cust-postcode.
ls_customer-city
= ls_cust-city.
ls_customer-country = ls_cust-country.
* Note 3: Aggregate function AVG( ) always rounds down
*
ABAP rounds differently by default
*
to achieve identical results we enforce rounding down in ABAP
ls_customer-days_ahead =
round( val = ls_cust-days_sum / ls_cust-count
dec = 4
mode = cl_abap_math=>round_down ).
INSERT ls_customer INTO TABLE ct_customers.
ENDLOOP.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
* SELECT FROM ha400_booking_with_days
*
FIELDS customid,
*
name,
*
postcode,
*
city,
*
country,
*
AVG( days_ahead ) AS days_ahead
*
GROUP BY customid, name, postcode, city, country
*
ORDER BY customid
*
INTO TABLE @ct_customers.
*
190
© Copyright. All rights reserved.
Lesson: Associations in Core Data Services
* With use of associations
*
SELECT FROM Ha400_Booking_With_Association
FIELDS customid as id,
\_customer-name,
\_customer-postcode,
\_customer-city,
\_customer-country,
AVG( days_ahead ) AS days_ahead
GROUP BY customid as id,
\_customer-name,
\_customer-postcode,
\_customer-city,
\_customer-country
ORDER BY customid
INTO TABLE @ct_customers.
ENDFORM.
© Copyright. All rights reserved.
"
191
Unit 3: Database Independent Code-to-Data
LESSON SUMMARY
You should now be able to:
●
192
Use CDS views with associations
© Copyright. All rights reserved.
Unit 3
Lesson 5
Outlook: More Interesting Features of CDS
LESSON OVERVIEW
In this lesson, you learn how to incorporate authorization checks when querying data from a
Core Data Services (CDS) view using Open SQL.
Business Example
You want to improve the performance of an application using the code-to-data approach with
CDS views in ABAP. The application reads a large number of database records from the CDS
view, and also has to consider if the end user is authorized to see each record retrieved.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain CDS view extensions
●
Define and use CDS views with input parameters
●
Explain authorization checks with CDS
CDS View Extensions
Figure 139: CDS View Extends
© Copyright. All rights reserved.
193
Unit 3: Database Independent Code-to-Data
Animation: CDS View Extends
For more information on CDS View Extends, please view the animation in the
lesson Outlook: More Interesting Features of CDS, online in the SAP Learning
Hub.
As of ABAP 7.40 SP08, you can extend an ABAP CDS view without making modifications. To
enhance a CDS view, do the following:
You can extend a CDS view with literals, additional fields of the base table(s), expressions and
functions.
When displaying the extended CDS view, the editor shows a spiral-like symbol next to the
DEFINE VIEW statement to indicate that one or more extensions exist. Click on the symbol to
display a list of the existing extensions. Click on a list entry to navigate to the definition of the
CDS view extend.
Note:
Before ABAP 7.51 you can not extend CDS Views that contain a GROUP BY clause
or a UNION (ALL).
CDS Views with Input Parameters
So far, results sets based on a Core Data Services (CDS) view could only be filtered using the
WHERE clause of the corresponding query. This requires that the filter criterion is an element
of the view's projection list. However, in some cases, it is desirable to pass filter criteria or
parameterize a query in a different way, for example, if the filter condition cannot be based on
the projection list, or if an expression used within the CDS view is to be parameterized.
This need is addressed by CDS views with input parameters.
194
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
Defining CDS Views with Input Parameters
Figure 141: Defining CDS Views with Input Parameters
The WITH PARAMETERS( )... syntax in the CDS Data Definition Language (DDL) allows for the
definition of a CDS view with a comma-separated list of scalar input parameters, as follows:
●
●
●
●
Each parameter is either typed with a built-in ABAP type, such as abap.dec or abap.char,
or with an ABAP Dictionary data element.
The parameters can be used in the projection list of the CDS view, simply as elements or in
expressions.
The parameters can also be used in the JOIN condition of the FROM clause, in conditions in
the WHERE and the HAVING clauses.
A parameter can be referenced using the syntax $parameter.<parameter name>
or :<parameter name>.
Hint:
As of ABAP 7.50, CDS views with input parameters are supported on all database
management systems supported by the ABAP stack. In ABAP 7.40, however,
CDS views with input parameters were only supported on SAP HANA.
© Copyright. All rights reserved.
195
Unit 3: Database Independent Code-to-Data
Binding Input Parameters of CDS Views to System Fields
Figure 142: Binding Input Parameters of CDS Views to System Fields
Animation: Binding Input Parameters of CDS Views to System Fields
For more information on Binding Input Parameters of CDS Views to System
Fields, please view the animation in the lesson Outlook: More Interesting
Features of CDS, online in the SAP Learning Hub.
As of ABAP 7.50 you can use the annotation @Environment.systemField to bind an input
parameter to one of the ABAP system fields. Currently supported are the system date and
time, the user name, logon language and logon client of the current user. Using this
annotation makes the input parameter optional when the view is accessed in an Open SQL
SELECT.
Note:
When using the view in Data Preview or another CDS view, this annotation has no
effect and the parameter remains mandatory.
Using a CDS View with Input Parameters in a Data Definition
Figure 144: Using a CDS View with Input Parameters in a Data Definition
196
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
Animation: Using a CDS View with Input Parameters in a Data Definition
For more information on Using a CDS View with Input Parameters in a Data
Definition, please view the animation in the lesson Outlook: More Interesting
Features of CDS, online in the SAP Learning Hub.
When accessing a CDS view with input parameters from within another CDS view definition,
the parameter values have to be passed in the FROM clause of the SELECT statement, as a
comma-separated list of parameter name: value pairs, enclosed in parentheses and following
the name of the CDS view used.
Using a CDS View with Input Parameters in Open SQL
Figure 146: Using a CDS View with Input Parameters in Open SQL
CDS views with input parameters can be used in Open SQL queries using a very similar
syntax. Note the slight difference: in Open SQL, the equals sign is used to separate the
parameter names from their values (and spaces matter, as usual in ABAP and Open SQL).
© Copyright. All rights reserved.
197
Unit 3: Database Independent Code-to-Data
198
© Copyright. All rights reserved.
Unit 3
Exercise 12
Optional: Define and Use a CDS View with
Input Parameter
Simulation: Optional: Define and Use a CDS View with Input Parameter
For more information on Optional: Define and Use a CDS View with Input
Parameter, please view the simulation in the lesson Outlook: More Interesting
Features of CDS online in the SAP Learning Hub.
Business Example
You have a program that reads from an existing CDS View. You now want to define your own
CDS view to move the complete aggregation expression into the CDS view.
Template:
ABAP program: HA400_CDS_VIEW_T3
Solution:
ABAP program: HA400_CDS_VIEW_S3
Data definition: HA400_CDS_S3 (Defining CDS View HA400_CDS_S3 and SQL View
HA400_CDS_SQL_S3)
Task 1: Copy and Understand the Template Program
In system T8N, which has SAP HANA as a primary database, create a copy of report
HA400_CDS_VIEW_T3 in your package (suggested name: ZHA400_##_CDS_3, where ## is
your group number). Analyze the source code, activate, and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the source code of subroutine get_data_template.
Which data is read and from which database tables?
What is the purpose of the selection criterion in the WHERE clause?
© Copyright. All rights reserved.
199
Unit 3: Database Independent Code-to-Data
3. Activate and execute the program.
Task 2: Create a New Data Definition (DDL Source)
You want to move the entire data selection of subroutine get_data_template into a CDS view.
To do so, create a new ABAP DDL source (suggested name: ZHA400_##_DDL3) which
defines an SQL view in the ABAP Dictionary (suggested name: ZHA400_##_SQL3). Define
the view in a way that it reads the same data as the SELECT statement of subroutine
get_data_template of your program.
Define an input parameter for the CDS view to support exclusion of bookings on flights after a
given date.
1. Using ABAP Development Tools for Eclipse, create a new ABAP DDL source (= Data
Definition) based on template Define View With Parameters.
2. Within the DDL source, set the name of the SQL view within the sqlViewName annotation.
3. Edit the WITH PARAMETERS addition of the generated DEFINE VIEW statement. Define a
parameter for the flight date up to which bookings should be considered in the
aggregation (suggested name: P_UPTO_DATE). To do so, replace parameter_name with
P_UPTO_DATE. To define the parameter with dictionary type DATS, replace
parameter_type with abap.dats.
4. Edit the FROM clause of the generated SELECT statement. Replace
data_source_name with HA400_Booking_With_Association to read from CDS
view HA400_Booking_With_Association.
5. Edit the field list of the generated SELECT statement. Read the same fields, in the same
sequence as in the SELECT statement of subroutine get_data_template.
Read the following fields:
a) FROM the CDS view itself: CUSTOMID and AVG( days_ahead ).
b) From association _Customer: NAME, POSTCODE, CITY, COUNTRY
Hint:
You can reduce the typing effort by making use of the editor’s code
completion capabilities.
6. After the field list, add a WHERE clause. Exclude all bookings with a flight date after the
value of your input parameter.
Hint:
In CDS syntax, you have to use prefix $parameters. before the parameter
name.
7. After the WHERE clause, add a GROUP BY clause with all fields of the field list except the
aggregate expression.
200
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
Hint:
You can have the editor generate the entire GROUP BY clause by using the
editor’s “Quick Fix” functionality for the respective error message.
8. Why can't you add the ORDER BY addition?
9. Save and activate the data definition.
Task 3: Use Your SQL View in an Open SQL Statement
In subroutine get_data_solution of your program, implement a select statement from your
newly defined view.
1. Edit your program. In subroutine get_data_solution, implement a select statement that
reads the relevant data from your new CDS view. Pass the system date (field sy-datum) as
actual value for the input parameter of the CDS view.
2. Activate and test your program to verify that the data has been read correctly.
Task 4: Optional: Default Value for Input Parameter
Use annotation @Environment.systemField to use the system of AS ABAP as the default value
for your parameter. Then remove the parameter passing from your Open SQL statement.
1. Edit your data definition (DDL source). Between the key word WITH PARAMETERS and
the name of the parameter add the annotation @Environment.systemField followed by the
value #SYSTEM_DATE.
2. Save and activate the data definition.
3. Open the data preview for this view.
Why do you still have to enter a value for the input parameter?
4. Edit your program. In subroutine get_data_solution, remove the parameter passing and
brackets after the name of your CDS view.
5. Activate and test your program to verify that the data has been read correctly.
© Copyright. All rights reserved.
201
Unit 3
Solution 12
Optional: Define and Use a CDS View with
Input Parameter
Simulation: Optional: Define and Use a CDS View with Input Parameter
For more information on Optional: Define and Use a CDS View with Input
Parameter, please view the simulation in the lesson Outlook: More Interesting
Features of CDS online in the SAP Learning Hub.
Business Example
You have a program that reads from an existing CDS View. You now want to define your own
CDS view to move the complete aggregation expression into the CDS view.
Template:
ABAP program: HA400_CDS_VIEW_T3
Solution:
ABAP program: HA400_CDS_VIEW_S3
Data definition: HA400_CDS_S3 (Defining CDS View HA400_CDS_S3 and SQL View
HA400_CDS_SQL_S3)
Task 1: Copy and Understand the Template Program
In system T8N, which has SAP HANA as a primary database, create a copy of report
HA400_CDS_VIEW_T3 in your package (suggested name: ZHA400_##_CDS_3, where ## is
your group number). Analyze the source code, activate, and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as before.
2. Analyze the source code of subroutine get_data_template.
Which data is read and from which database tables?
All data is read from CDS view HA400_Booking_With_Association. Besides some
customer information (fields CUSTOMID, NAME, POSTCODE, CITY, COUNTRY) there is
an aggregation (aggregate function AVG( )) of the number of days between booking date
and flight date (field DAYS_AHEAD).
202
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
What is the purpose of the selection criterion in the WHERE clause?
Bookings on future flights should not be considered.
3. Activate and execute the program.
a) Complete this step as in the previous exercise.
Task 2: Create a New Data Definition (DDL Source)
You want to move the entire data selection of subroutine get_data_template into a CDS view.
To do so, create a new ABAP DDL source (suggested name: ZHA400_##_DDL3) which
defines an SQL view in the ABAP Dictionary (suggested name: ZHA400_##_SQL3). Define
the view in a way that it reads the same data as the SELECT statement of subroutine
get_data_template of your program.
Define an input parameter for the CDS view to support exclusion of bookings on flights after a
given date.
1. Using ABAP Development Tools for Eclipse, create a new ABAP DDL source (= Data
Definition) based on template Define View With Parameters.
a) In the ABAP perspective of Eclipse, right-click your package and choose New → Other
ABAP Repository Object.
b) In the next window, choose Core Data Services → →Data Definition.
c) Enter the name of your package, a name, and a short description for the new object,
and choose Next.
d) Assign the object to your transport request and choose Next.
e) Click on template Define View With Parameters and choose Finish.
2. Within the DDL source, set the name of the SQL view within the sqlViewName annotation.
a) In the first line of the editor, replace sql_view_name with ZHA400_##_SQL3, where
## stands for your group number.
See the source code extract from the model solution.
3. Edit the WITH PARAMETERS addition of the generated DEFINE VIEW statement. Define a
parameter for the flight date up to which bookings should be considered in the
aggregation (suggested name: P_UPTO_DATE). To do so, replace parameter_name with
P_UPTO_DATE. To define the parameter with dictionary type DATS, replace
parameter_type with abap.dats.
a) See the source code extract from the model solution.
4. Edit the FROM clause of the generated SELECT statement. Replace
data_source_name with HA400_Booking_With_Association to read from CDS
view HA400_Booking_With_Association.
a) See the source code extract from the model solution.
5. Edit the field list of the generated SELECT statement. Read the same fields, in the same
sequence as in the SELECT statement of subroutine get_data_template.
Read the following fields:
a) FROM the CDS view itself: CUSTOMID and AVG( days_ahead ).
© Copyright. All rights reserved.
203
Unit 3: Database Independent Code-to-Data
b) From association _Customer: NAME, POSTCODE, CITY, COUNTRY
Hint:
You can reduce the typing effort by making use of the editor’s code
completion capabilities.
a) Place the cursor between the curly brackets (“{ })”. Then invoke the code-completion
by pressing Ctrl + Space on your keyboard.
b) See the source code extract from the model solution.
6. After the field list, add a WHERE clause. Exclude all bookings with a flight date after the
value of your input parameter.
Hint:
In CDS syntax, you have to use prefix $parameters. before the parameter
name.
a) See the source code extract from the model solution.
7. After the WHERE clause, add a GROUP BY clause with all fields of the field list except the
aggregate expression.
Hint:
You can have the editor generate the entire GROUP BY clause by using the
editor’s “Quick Fix” functionality for the respective error message.
a) Place the cursor on the source code line that contains key word SELECT.
b) Press Ctrl + 1 on your keyboard. Alternatively, you can right-click that code line and
choose Quick Fix.
c) Choose Add GROUP BY clause.
d) See the source code extract from the model solution.
8. Why can't you add the ORDER BY addition?
ORDER BY is not supported in CDS view definitions.
9. Save and activate the data definition.
a) Choose Save.
b) Choose Activate.
Task 3: Use Your SQL View in an Open SQL Statement
In subroutine get_data_solution of your program, implement a select statement from your
newly defined view.
1. Edit your program. In subroutine get_data_solution, implement a select statement that
reads the relevant data from your new CDS view. Pass the system date (field sy-datum) as
actual value for the input parameter of the CDS view.
204
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
a) Immediately after the CDS view name (without a space), add ( p_upto_date = sydatum ).
b) See the source code extract from the model solution.
2. Activate and test your program to verify that the data has been read correctly.
a) Complete this step as before.
Task 4: Optional: Default Value for Input Parameter
Use annotation @Environment.systemField to use the system of AS ABAP as the default value
for your parameter. Then remove the parameter passing from your Open SQL statement.
1. Edit your data definition (DDL source). Between the key word WITH PARAMETERS and
the name of the parameter add the annotation @Environment.systemField followed by the
value #SYSTEM_DATE.
a) See the source code extract from the model solution.
2. Save and activate the data definition.
a) Choose Save.
b) Choose Activate.
3. Open the data preview for this view.
a) Right-click anywhere in the data definition (DDL source) and choose the contextual
menu item Open With → Data Preview.
Why do you still have to enter a value for the input parameter?
Because annotation @Environment.systemField is only relevant when accessing the view
from ABAP via Open SQL.
4. Edit your program. In subroutine get_data_solution, remove the parameter passing and
brackets after the name of your CDS view.
a) See commented coding in the source code extract from the model solution.
5. Activate and test your program to verify that the data has been read correctly.
a) Complete this step as before.
b) Verify that your code matches the following solution:
Data Definition HA400_CDS_S3
@AbapCatalog.sqlViewName: 'HA400_CDS_SQL_S3'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'CDS view with input parameter'
define view HA400_CDS_S3
with parameters
// optional: use system date of AS ABAP as
//
default value of this parameter
@Environment.systemField: #SYSTEM_DATE
p_upto_date : abap.dats
as select
from HA400_Booking_With_Association
{
© Copyright. All rights reserved.
205
Unit 3: Database Independent Code-to-Data
customid as id,
_customer.name,
_customer.postcode,
_customer.city,
_customer.country,
}
avg( days_ahead ) as days_ahead
where fldate <= $parameters.p_upto_date
group by
customid,
_customer.name,
_customer.postcode,
_customer.city,
_customer.country
ABAP program HA400_CDS_VIEW_S3
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
SELECT FROM HA400_Booking_With_Association
FIELDS customid AS id,
\_customer-name,
\_customer-postcode,
\_customer-city,
\_customer-country,
AVG( days_ahead ) AS days_ahead
WHERE fldate <= @sy-datum
GROUP BY customid,
\_customer-name,
\_customer-postcode,
\_customer-city,
\_customer-country
ORDER BY customid
INTO TABLE @ct_customers.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
SELECT FROM ha400_cds_s3( p_upto_date = @sy-datum )
FIELDS id,
name,
postcode,
city,
country,
days_ahead
ORDER BY id
INTO TABLE @ct_customers.
* Optional: if parameter is implicitly set to system field sy-datum
206
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
*
*
*
*
*
*
*
*
*
SELECT FROM ha400_cds_s3
FIELDS id,
name,
postcode,
city,
country,
days_ahead
ORDER BY id
INTO TABLE @ct_customers.
ENDFORM.
© Copyright. All rights reserved.
"
207
Unit 3: Database Independent Code-to-Data
Implicit Authorization Checks Through CDS Roles
What if an application logic reads multiple database records, but requires that authorizations
are checked on the level of individual database records? CDS views may seem less useful in
this case. Considering classical AUTHORITY-CHECKs only, the application would have to read
a larger dataset from the database, ignoring authorizations, and then perform the
authorization checks on the application server to reduce the dataset. This would correspond
to a partial code-to-data approach only, giving up some of the benefits of pushing the data
retrieval logic down to the database as much as possible.
Figure 148: Do Authorization Checks Conflict with Code-to-Data?
Fortunately, classical AUTHORITY-CHECKs are not the only option any longer.
208
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
Figure 149: CDS_DCL_DeclareAuthorizationsAndPushChecksToDatabase_Image.ppt
Beginning with ABAP 7.40 SP10, CDS DCL can be used to define authorizations for CDS views
in a declarative way. A new type of ABAP repository object, DCL source, is introduced for this
purpose. Each such access control object allows declaring (that is, modeling) a role based on
a related CDS entity. Conditions specify how the user’s permissions are checked against field
values of the individual records at runtime.
Note:
Access controls only take effect in a direct access to the CDS view, that is when
the CDS view is directly used in an Open SQL SELECT statement or accessed
through SADL. If the CDS view is accessed indirectly, for example via another CDS
view, the access controls for this CDS view are ignored.
The ABAP layer cannot distinguish between non-existent data and data not read
due to lack of permissions.
© Copyright. All rights reserved.
209
Unit 3: Database Independent Code-to-Data
Access Conditions in CDS Roles
Figure 150: Literal and Aspect Conditions
Animation: Literal and Aspect Conditions
For more information on Literal and Aspect Conditions, please view the
animation in the lesson Outlook: More Interesting Features of CDS, online in the
SAP Learning Hub.
The following two types of conditions can be used in a role definition:
Literal conditions
To compare an element of the CDS view with a literal value.
Aspect conditions
Only one aspect, pfcg_auth, is supported. This aspect allows the reuse of authorizations,
based on classical authorization objects and PFCG roles. The left-hand side of a PFCG
condition contains the list of view fields in parentheses. The list on the right-hand side
begins with the name of the authorization object. It continues with the list of
authorization object fields the view elements of the left-hand side are matched against,
optionally followed by a list of authorization object fields to be compared with literal
values.
The two types of conditions can be combined in the same role definition.
Annotations Related to Access Controls
Two annotations are relevant in the context of DCL sources:
210
© Copyright. All rights reserved.
Lesson: Outlook: More Interesting Features of CDS
Figure 152: Most Important Annotations for Access Control Objects
In a DCL source itself, annotation @MappingRule specifies that the role is automatically and
implicitly assigned to all users. Only the value true is supported as of now. Every definition of a
CDS role must currently contain the ABAP annotation MappingRole with the value true.
In a DDL source, that is in a CDS view definition, the annotation
@AccessControl.authorizationCheck specifies if a corresponding DCL role should be defined
and if the access conditions should be checked automatically at runtime. The following values
are supported for the annotation:
CHECK
During the authorization runtime, an authorization check is executed if a DCL role exists
for the entity. If no role exists, there is no check and no protection. The design time issues
a warning when activating the entity if no DCL role exists, although an authorization
check is required. This is the default value for the ABAP implementation.
NOT_REQUIRED
During the authorization runtime, an authorization check is executed if a DCL role exists
for the entity. If no role exists, there is no check and no protection. This is the same
behavior at runtime as for value CHECK. However, the design time issues no warning
when activating the entity, even if no corresponding mapping role is defined yet. This
value should be used when a mapping role is intended and planned to be defined, but no
mapping role exists yet.
NOT_ALLOWED
During the authorization runtime, no authorization check is executed. During the
authorization design time, a warning occurs when activating a role for an entity with this
annotation value.
© Copyright. All rights reserved.
211
Unit 3: Database Independent Code-to-Data
LESSON SUMMARY
You should now be able to:
212
●
Explain CDS view extensions
●
Define and use CDS views with input parameters
●
Explain authorization checks with CDS
© Copyright. All rights reserved.
Unit 3
Learning Assessment
1. Which of the following are tasks of the database interface (DBI) and database-specific
library (DBSL)?
Choose the correct answers.
X
A Translate Open SQL syntax into native SQL syntax
X
B Add client handling to the statement
X
C Check user authorizations
X
D Handle SAP table buffering
X
E Transaction handling
2. New Open SQL syntax is mandatory as of SAP NetWeaver AS ABAP 7.40 SP05.
Determine whether this statement is true or false.
X
True
X
False
3. The Open SQL syntax is a prerequisite for the new Open SQL features.
Determine whether this statement is true or false.
X
True
X
False
4. Classical Open SQL syntax and new Open SQL syntax must not be used in the same ABAP
processing block.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
213
Unit 3: Learning Assessment
5. Which of the following entities can be found in the object list of the ABAP Workbench or
the Project Explorer of ADT?
Choose the correct answers.
X
A Data definition (also known as DDL source)
X
B CDS view
X
C SQL view
6. Which of the following entities corresponds to an object that is created on the database?
Choose the correct answer.
X
A Data definition (aka DDL source)
X
B CDS view
X
C SQL view
7. If you use a CDS view name in the FROM clause of an Open SQL SELECT statement, the
new Open SQL syntax is mandatory.
Determine whether this statement is true or false.
X
True
X
False
8. ASSOCIATION TO is just another way of saying LEFT OUTER JOIN TO.
Determine whether this statement is true or false.
X
True
X
False
9. Which of the following are prerequisites for exposing an association?
Choose the correct answer.
214
X
A The association points to a table, not to another CDS View.
X
B The association has cardinality “to-N.”
X
C All fields mentioned in the ON condition are part of the field list.
X
D The association is the only association in this view definition.
© Copyright. All rights reserved.
Unit 3: Learning Assessment
10. Where can you evaluate an exposed association?
Choose the correct answers.
X
A In the Data Preview of ADT
X
B In the Data Browser (transaction SE16)
X
C In another CDS view
X
D In an Open SQL SELECT statement
11. CDS views that define associations cannot be extended.
Determine whether this statement is true or false.
X
True
X
False
12. An import parameter that is annotated with @Environment.systemField: becomes optional
in the following places:
Choose the correct answer.
X
A In Data Preview in ADT
X
B In the Data Browser (SE16)
X
C In ABAP Open SQL
X
D In the definition of another CDS view
13. An access control (DCL source) defines access restrictions for a given CDS view. These
restrictions are implicitly evaluated when the CDS view is accessed in the following places:
Choose the correct answers.
X
A In Data Preview in ADT
X
B In the Data Browser (SE16)
X
C In ABAP Open SQL
X
D In the definition of another CDS view
© Copyright. All rights reserved.
215
Unit 3: Learning Assessment
216
© Copyright. All rights reserved.
UNIT 4
SAP HANA specific Code-toData
Lesson 1
SAP HANA Native SQL Syntax
219
Lesson 2
ABAP-Managed Database Procedures
Exercise 13: Create and Call an ABAP-Managed Database Procedure
223
233
Lesson 3
ABAP Database Connectivity (ADBC)
Exercise 14: Issue a Native SQL Statement via ADBC
247
251
UNIT OBJECTIVES
●
Know the basics of SAP HANA native SQL syntax
●
Understand ABAP-Managed Database Procedures
●
Create an ABAP-Managed Database Procedure
●
Call an ABAP-Managed Database Procedure in ABAP
●
Debug an ABAP-Managed Database Procedure
●
Know how AMDP enhancement works
●
Understand ABAP Database Connectivity (ADBC)
●
Use ADBC to execute native SQL statements
© Copyright. All rights reserved.
217
Unit 4: SAP HANA specific Code-to-Data
218
© Copyright. All rights reserved.
Unit 4
Lesson 1
SAP HANA Native SQL Syntax
LESSON OVERVIEW
In this lesson, you learn about the main differences between native SQL syntax and Open SQL
syntax and how to write syntactically correct native SQL statements.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Know the basics of SAP HANA native SQL syntax
SAP HANA SQL and Open SQL
For even more sophisticated code pushdown, ABAP developers need to access SAP HANAspecific functionality directly. This inevitably involves the use of SAP HANA’s own native SQL
dialect because such functionality is not accessible through database-independent
techniques such as Open SQL and CDS view definition.
In a first step, we will discuss the common ground and the major differences between Open
SQL syntax and (SAP HANA) native SQL syntax.
Common Ground Between SAP HANA SQL and Open SQL
●
●
Key words are not case-sensitive
Table names and column names are translated to upper case (in SAP HANA SQL: if not
quoted)
In Open SQL, you can only access table names and column names defined in the ABAP
Dictionary. Such table names and column names are always in upper case.
In SAP HANA SQL, you may need to access table names and column names that include
lower case characters. Place those names in double-quotes (“”) to keep SAP HANA from
translating them to upper case.
Important Syntax Differences Between SAP HANA SQL and Open SQL
SAP HANA Native
SQL
Classic Open SQL
Enhanced Open
SQL
Element List Separator
Comma (,)
Blank ( )
Comma (,)
Position of Element List
Before FROM clause
Before FROM
clause
Before or after
FROM clause(key
word FIELDS)
Separator between table
and field name
Period ( . )
Tilde (~)
Tilde (~)
© Copyright. All rights reserved.
219
Unit 4: SAP HANA specific Code-to-Data
SAP HANA Native
SQL
Classic Open SQL
Enhanced Open
SQL
Schema handling
Implicit default
schema (user
schema) or schema
name before table
name
Only default
schema
Only default
schema
Client Handling
No implicit client
handling. Client
needs to be specified
in WHERE-clause and
join conditions.
Implicit client
handling by DB
interface. Explicit
client via addition
CLIENT SPECIFIED.
Implicit client
handling by DB
interface. Explicit
client via addition
USING CLIENT.
Delimitate number of
rows
TOP ...
UP TO … ROWS
UP TO … ROWS
Access to CDS Views
Only SQL view visible Only access to SQL
on database
view supported.
Access to CDS view
possible.
CORRESPONDING
FIELDS
Not supported
Supported
Supported
FOR ALL ENTRIES
Not supported
Supported
Supported
Figure 153: Example 1: Classical Open SQL Syntax and Native SQL Syntax
220
© Copyright. All rights reserved.
Lesson: SAP HANA Native SQL Syntax
Figure 154: Example 2: Joins in Open SQL and Native SQL
Test of SAP HANA SQL Statements in SAP HANA Studio
As there is no syntax check for native SQL statements in ABAP, it can be very difficult to
ensure correct syntax. A convenient solution can be to use the SQL Console view of the SAP
HANA studio.
Figure 155: SQL Console
Animation: SQL Console
For more information on SQL Console, please view the animation in the lesson
SAP HANA Native SQL Syntax, online in the SAP Learning Hub.
You can open the SQL Console as follows:
© Copyright. All rights reserved.
221
Unit 4: SAP HANA specific Code-to-Data
1. Select the SAP HANA system.
2. Choose the Open SQL Console button.
Here you can enter SQL statements (SAP HANA syntax) and execute them.
Figure 157: Enter SQL Statement and Execute
You can test an SQL statement as follows:
1. Enter a statement in the SQL Console.
2. Choose the Execute button.
If the statement is not yet correct, error messages are displayed that can be used to locate
and correct the error.
Caution:
Be careful with statements that change the content of database tables.
LESSON SUMMARY
You should now be able to:
●
222
Know the basics of SAP HANA native SQL syntax
© Copyright. All rights reserved.
Unit 4
Lesson 2
ABAP-Managed Database Procedures
LESSON OVERVIEW
This lesson explains the benefits of and how to develop and use ABAP-Managed Database
Procedures.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP applications
considerably by making use of SAP HANA. The ABAP system is on release 7.4 SP05 or higher
and uses SAP HANA as its primary database. You realize that the performance improvement
you aim for cannot be reached using Open SQL, Core Data Services (CDS), or native SQL.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Understand ABAP-Managed Database Procedures
●
Create an ABAP-Managed Database Procedure
●
Call an ABAP-Managed Database Procedure in ABAP
●
Debug an ABAP-Managed Database Procedure
●
Know how AMDP enhancement works
Motivation for AMDPs
Figure 158: ABAP 7.4 SP05: ABAP-Managed Database Procedures
© Copyright. All rights reserved.
223
Unit 4: SAP HANA specific Code-to-Data
Animation: ABAP 7.4 SP05: ABAP-Managed Database Procedures
For more information on ABAP 7.4 SP05: ABAP-Managed Database Procedures,
please view the animation in the lesson ABAP-Managed Database Procedures,
online in the SAP Learning Hub.
Starting with ABAP 7.4 SP05, SAP offers ABAP-managed database procedures (AMDPs) as
top-down approach to create and call stored procedures on SAP HANA database.
Using the new AMDP technique, editing, activation, transport, and lifecycle management of
database procedures are performed on the ABAP application server.
Using the AMDP framework has the following advantages:
●
SQLScript source code is edited and managed in an ABAP repository object
●
SQLScript syntax check is integrated into the ABAP syntax check
●
SQL Script debugging is integrated into ABAP debugging
●
Stored procedures are automatically created (deployed) on the SAP HANA database
Note:
Using ABAP-managed database procedures is the recommended way of using
SAP HANA database procedures in ABAP applications.
AMDPs Creation
Figure 160: AMDPs: Integration of Database Procedures into ABAP
224
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
ABAP Managed Database Procedures (AMDPs) are created as methods of ABAP classes. But
in contrast to “normal” methods, they are not implemented with ABAP source code but with a
database specific programming language, such as SAP HANA SQL script.
Whether a method is implemented in ABAP or another language is specified with addition BY
DATABASE PROCEDURE in the method implementation part. But the class definition part has
to fulfill some prerequisites before the method can be used as an AMDP method.
Prerequisites in Class Definition
Figure 161: AMDPs: Prerequisites in Class Definition
Classes that are to act as a container for AMDPs have to implement a so-called “marker
interface” IF_AMDP_MARKER_HDB.
AMDP method parameters are allowed to be import, export, or changing parameters.
Returning parameters cannot be used.
All AMDP method parameters have to be passed by value, and must be of either table or
scalar types.
For parameters of table types, the line types have to consist of elementary components,
because nested tables are not supported. ABAP Dictionary structure types are not allowed.
Scalar importing parameters can have default values.
AMDP methods can be defined in the public, protected, or private visibility section of the
class. ABAP classes can contain a mixture of ABAP methods and AMDP methods.
Note:
Although you can define AMDP methods as instance methods, they are always
executed like static methods.
© Copyright. All rights reserved.
225
Unit 4: SAP HANA specific Code-to-Data
Implementing AMDP Methods
Figure 162: Implementation of AMDP Methods
Animation: Implementation of AMDP Methods
For more information on Implementation of AMDP Methods, please view the
animation in the lesson ABAP-Managed Database Procedures, online in the SAP
Learning Hub.
You turn a normal ABAP method into an AMDP method by adding BY DATABASE
PROCEDURE to the METHOD statement (beginning of the method implementation). This is
followed by the database system (for example, HDB) and the implementation language (for
example, SQLScript).
The method body of such a method is implemented using SQLScript source code. Almost the
full SQLScript reference can be used in the method body, except the CE function
CE_COLUMN_TABLE.
If the method implementation uses ABAP objects (ike tables, views, other AMDPs) it is
mandatory to list these objects after addition USING.
Via the addition OPTIONS, the AMDP method can be marked as a READ-ONLY database
procedure. This is optional.
226
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
Figure 164: AMDP Method – SQLScript Example
Some basic characteristics of SAP HANA SQLScript are as follows:
●
●
●
●
●
Statements are ended with semicolon (;).
Comments can be marked by using two dashes (--), but star (*) at position 1 is also
supported.
In SQL-statements, host variables (variables, parameters, constants) are escaped with
double-point (:).
There is no INTO clause for SELECT. Results are retrieved by using SELECT as an
expression on the right-hand side of a value assignment.
Built-in function SESSION_CONTEXT( ) provides values of session variables (like for
example the logon client from the ABAP server.
Note:
Comments in SQLScript can be marked by using two dashes (--), but star (*) at
position 1 is also supported – just like in ABAP.
© Copyright. All rights reserved.
227
Unit 4: SAP HANA specific Code-to-Data
Figure 165: AMDP Method - SQLScript Examples
Temporary data objects, like for example temporary tables to store SELECT-results, you don't
have to declare in advance. In the example, data object lt_customers is declared in-line to
store the result of the query.
All ABAP Dictionary tables or views, and other AMDP methods that will be called in the
procedure body, must be declared with the USING keyword. In the procedure body, these
objects are addressed without the need for the SAP<SID> prefix. AMDP methods called inside
an AMDP body have to be declared with their full names (that is, the class they belong to as
well as the method name, as you can see from the figure). When they are called in the
procedure body, they must be addressed with double quotes and in uppercase. Any objects
outside of the SAP<SID> schema are not ABAP-managed, and therefore are not part of the
USING clause. Developers have to make sure that they are available at runtime.
Editor Support for AMDP Methods
To get full editor support, it is mandatory to use ADT to edit AMDP methods. The classical
ABAP Workbench only supports display of ABAP Managed Database Procedures.
The tool support in ADT includes the following functions:
228
●
Semantic code completion for the ABAP part (BY DATABASE PROCEDURE addition)
●
Syntax check for SQLScript code
●
Syntax highlighting for SQLScript code
●
Debugging of AMDP methods
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
Figure 166: AMDP Methods – Syntax Check in ADT
The syntax check can detect the following types of syntax errors:
●
Database-independent syntax errors: parameters not passed by value, wrong parameter
types, or cyclic method calls
●
SAP HANA-specific syntax errors: Type mapping checks or wrong default values
●
SQLScript errors
With any of these syntax errors, an AMDP class is not syntactically correct.
Note:
The syntax checks depend on the underlying database system. You need an SAP
HANA as primary database to get SQLScript syntax checks.
© Copyright. All rights reserved.
229
Unit 4: SAP HANA specific Code-to-Data
AMDP Use
Figure 167: Calling AMDP Methods
An AMDP method is called like any ABAP method, as follows:
●
●
AMDP methods are executed like static methods, even if they are defined as instance
methods.
When an AMDP is processed, the ABAP kernel calls the corresponding database
procedure in SAP HANA.
AMDP makes sure that a database procedure is available at runtime:
●
The database procedure is created at first use (lazy approach).
●
It exists in the SAP<SID> schema.
●
●
A new version of the database procedure is created each time the source code or
dependent objects change.
Obsolete versions are deleted asynchronously.
Debugging ABAP-Managed Database Procedures in SAP NetWeaver 7.50
When ABAP code using ABAP-managed database procedures does not work as expected, you
may want to debug into the database procedure similarly to how you can debug the ABAP
code itself. With ABAP 7.4 SP05 and SAP HANA Studio version 1.70 or higher, ABAP managed
database procedures can be debugged. The level of integration into the ABAP debugging
process and exact procedure depends on the ABAP release.
230
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
Figure 168: Setting Breakpoints In ABAP-Managed Database Procedures
Animation: Setting Breakpoints In ABAP-Managed Database Procedures
For more information on Setting Breakpoints In ABAP-Managed Database
Procedures, please view the animation in the lesson ABAP-Managed Database
Procedures, online in the SAP Learning Hub.
With ABAP 7.5, an AMDP can be debugged in a fully-integrated way using the ABAP
Development Tools. Simply open the AMDP method in an ABAP editor view and set
breakpoints as usual.
Note:
Breakpoints in AMDPs can only be set in lines in which statements begin, and only
if the procedure really exists on the database. Since the ABAP stack creates the
procedure on the DB on-demand only (the first time the procedure is really
executed), a procedure must have been executed at least once in the system
before you can set a breakpoint in it.
When the program calling the AMDP is executed and the break points are reached, the Debug
view opens.
© Copyright. All rights reserved.
231
Unit 4: SAP HANA specific Code-to-Data
Figure 170: Debugging AMDPs with ABAP 7.5
Animation: Debugging AMDPs with ABAP 7.5
For more information on Debugging AMDPs with ABAP 7.5, please view the
animation in the lesson ABAP-Managed Database Procedures, online in the SAP
Learning Hub.
If breakpoints are set both in usual ABAP code as well as in AMDPs, two debug sessions are
created: an ABAP Debugger session and a Database Server session. The latter is the one used
for the AMDPs. Note that the AMDP debugger is in fact executed on the HANA database and
does not provide all the options to step through the code you are used to from the ABAP
debugger. For example, you can mainly resume execution until the next breakpoint is
reached. You can add breakpoints while debugging, including on ENDMETHOD lines to inspect
the exporting parameters before execution is returned back from the database server to the
ABAP stack.
232
© Copyright. All rights reserved.
Unit 4
Exercise 13
Create and Call an ABAP-Managed Database
Procedure
Simulation: Create and Call an ABAP-Managed Database Procedure
For more information on Create and Call an ABAP-Managed Database
Procedure, please view the simulation in the lesson ABAP-Managed Database
Procedures online in the SAP Learning Hub.
Business Example
You want to implement an ABAP-Managed Database Procedure to push down application
logic onto the HANA database.
Template:
Report HA400_AMDP_T1
Class CL_HA400_AMDP_T1
Solution:
Report HA400_AMDP_S1
Class CL_HA400_AMDP_S1 (including AMDP method early_bird_and_last_minute)
Task 1: Copy and Understand Template Program
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_AMDP_T1 in your package (suggested name: ZHA400_##_AMDP, where ## is your
group number). Analyze the source code, activate and execute the program.
Note:
Be sure to copy the program with all sub-objects, such as screens, GUI status
and GUI title.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the source code of subroutine get_data_template. Pay special attention to the
changing parameters of the routine and how they are filled with data.
What is the main difference between this program and the ones we used before?
© Copyright. All rights reserved.
233
Unit 4: SAP HANA specific Code-to-Data
3. Activate the program and all its subobjects, and execute the program.
Task 2: Copy and Understand Template Class
Create a copy of class CL_HA400_AMDP_T1 in your package (suggested name:
ZCL_HA400_##_AMDP, where ## is your group number) and analyze it.
1. Create a copy of the class. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the definition of the class.
Which components does the class contain?
Task 3: Define and Implement an ABAP-Managed Database Procedure
In your copy of the template class, make the existing static method
early_bird_and_last_minute an ABAP-Managed Database Procedure (AMDP). To do so, adjust
the definition of the class and the method where necessary. Then implement the method with
two SELECT statements similar to those you find in subroutine get_data_template. Finally,
activate and test your class.
Hint:
As soon as a global class contains an AMDP you cannot edit it in a classic ABAP
Workbench anymore. You have to use ABAP Development Tools for Eclipse to
edit your class.
1. Go to the ABAP perspective in Eclipse and open your copy of the template class there. Go
to the implementation of method early_bird_and_last_minute and add the BY DATABASE
PROCEDURE... addition to indicate that the method is an ABAP-managed database
procedure.
2. Which changes are necessary to the class definition and the method definition?
3. Add the marker interface IF_AMDP_MARKER_HDB to your class and add value( ... ) to all
parameters of the method.
4. Edit the method implementation. Write a value assignment to fill output parameter
et_early (assignment operator “=”). On the right-hand side of the assignment, implement
a SELECT statement that is similar to the first SELECT statement in subroutine
get_data_template of your program.
234
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
Hint:
Note the following important syntax differences between SAP HANA SQL and
(enhanced) Open SQL:
●
●
●
●
●
●
●
No FIELDS addition in SAP HANA SQL. Move the field list to before the
FROM clause.
In SQLScript, you cannot access CDS views directly (only the SQL views
are created on the database). Read from the generated SQL view instead.
No implicit client handling in SAP HANA SQL. Add a WHERE clause to
restrict the client.
No system fields sy-nnnnn in SAP HANA SQLScript. Use SAP HANA built
in function session_context( ) with value 'CLIENT' to access the ABAP
session client.
In SAP HANA SQLScript you need to escape host variables with character
“:” instead of character “@”.
In an ORDER BY clause, you specify the sort order with DESC and ASC
instead of DESCENDING and ASCENDING.
No addition UP TO ... ROWS. Use addition TOP ... right after the key word
SELECT.
5. Add another value assignment with output parameter et_late on the left and a second
SELECT statement on the right. The only difference between the two SELECT statements
should be the sort order (ascending instead of descending).
6. Use addition USING ... to make the ABAP Dictionary object HA400_CDS_SQL_S1 (SQL
View) known inside the AMDP source code.
7. Optional: Use addition OPTIONS READ-ONLY to document that the procedure does not
contain any write access to the database.
8. Activate and test the class.
Task 4: Call the ABAP-Managed Database Procedure
In subroutine get_data_solution of your program ZHA400_##_AMDP, use your newly defined
ABAP-Managed Database Procedure to read the data from the database.
1. Edit your program. In subroutine get_data_solution, call the static method that defines the
AMDP.
2. Activate and test your program.
Task 5: Debug the AMDP
In ABAP Development Tools in Eclipse (ADT), set break-points in the AMDP method and
execute the program that calls the method.
1. In the ABAP perspective in Eclipse, navigate to the implementation of method
early_bird_and_last_minute in your class ZCL_HA400_##_AMDP.
2. In the SQLScript code of the AMDP, set two breakpoints, one at each select statement.
© Copyright. All rights reserved.
235
Unit 4: SAP HANA specific Code-to-Data
3. Remain in the ABAP perspective in Eclipse, navigate back to program, and execute the
ABAP report that calls the database procedure.
4. In the Debugger perspective of Eclipse, analyze the content of the AMDP procedure’s
parameters.
5. Resume execution to the next breakpoint in the AMDP method and display the content of
parameter et_late.
6. Resume execution until the application displays the result.
7. Close the application and the Debug perspective.
236
© Copyright. All rights reserved.
Unit 4
Solution 13
Create and Call an ABAP-Managed Database
Procedure
Simulation: Create and Call an ABAP-Managed Database Procedure
For more information on Create and Call an ABAP-Managed Database
Procedure, please view the simulation in the lesson ABAP-Managed Database
Procedures online in the SAP Learning Hub.
Business Example
You want to implement an ABAP-Managed Database Procedure to push down application
logic onto the HANA database.
Template:
Report HA400_AMDP_T1
Class CL_HA400_AMDP_T1
Solution:
Report HA400_AMDP_S1
Class CL_HA400_AMDP_S1 (including AMDP method early_bird_and_last_minute)
Task 1: Copy and Understand Template Program
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_AMDP_T1 in your package (suggested name: ZHA400_##_AMDP, where ## is your
group number). Analyze the source code, activate and execute the program.
Note:
Be sure to copy the program with all sub-objects, such as screens, GUI status
and GUI title.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Analyze the source code of subroutine get_data_template. Pay special attention to the
changing parameters of the routine and how they are filled with data.
a) Complete this step as you learned to do in previous classes.
© Copyright. All rights reserved.
237
Unit 4: SAP HANA specific Code-to-Data
What is the main difference between this program and the ones we used before?
Instead of just one list of all customers, two lists are gathered: one list of customers with
the longest average time between order date and flight date and a list of customers with
the shortest average time between order date and flight date.
3. Activate the program and all its subobjects, and execute the program.
a) Complete this step as you learned to do in previous classes.
Task 2: Copy and Understand Template Class
Create a copy of class CL_HA400_AMDP_T1 in your package (suggested name:
ZCL_HA400_##_AMDP, where ## is your group number) and analyze it.
1. Create a copy of the class. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Analyze the definition of the class.
Which components does the class contain?
Structure type ty_s_customer, table type ty_t_customers, and static method
early_bird_and_last_minute with 4 parameters (iv_number, iv_mandt, et_early and et_late)
Task 3: Define and Implement an ABAP-Managed Database Procedure
In your copy of the template class, make the existing static method
early_bird_and_last_minute an ABAP-Managed Database Procedure (AMDP). To do so, adjust
the definition of the class and the method where necessary. Then implement the method with
two SELECT statements similar to those you find in subroutine get_data_template. Finally,
activate and test your class.
Hint:
As soon as a global class contains an AMDP you cannot edit it in a classic ABAP
Workbench anymore. You have to use ABAP Development Tools for Eclipse to
edit your class.
1. Go to the ABAP perspective in Eclipse and open your copy of the template class there. Go
to the implementation of method early_bird_and_last_minute and add the BY DATABASE
PROCEDURE... addition to indicate that the method is an ABAP-managed database
procedure.
a) Open the ABAP perspective in Eclipse.
b) In the Project navigator on the left, expand your project and your package.
c) Expand the Source Library and double-click your class to open it in the ABAP editor.
d) Edit the source code as usual. For the result see source code extract from the model
solution.
238
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
2. Which changes are necessary to the class definition and the method definition?
The class has to implement interface IF_AMDP_MARKER_HDB and all parameters of the
method have to be passed by value.
3. Add the marker interface IF_AMDP_MARKER_HDB to your class and add value( ... ) to all
parameters of the method.
a) See source code extract from the model solution.
4. Edit the method implementation. Write a value assignment to fill output parameter
et_early (assignment operator “=”). On the right-hand side of the assignment, implement
a SELECT statement that is similar to the first SELECT statement in subroutine
get_data_template of your program.
Hint:
Note the following important syntax differences between SAP HANA SQL and
(enhanced) Open SQL:
●
●
●
●
●
●
●
No FIELDS addition in SAP HANA SQL. Move the field list to before the
FROM clause.
In SQLScript, you cannot access CDS views directly (only the SQL views
are created on the database). Read from the generated SQL view instead.
No implicit client handling in SAP HANA SQL. Add a WHERE clause to
restrict the client.
No system fields sy-nnnnn in SAP HANA SQLScript. Use SAP HANA built
in function session_context( ) with value 'CLIENT' to access the ABAP
session client.
In SAP HANA SQLScript you need to escape host variables with character
“:” instead of character “@”.
In an ORDER BY clause, you specify the sort order with DESC and ASC
instead of DESCENDING and ASCENDING.
No addition UP TO ... ROWS. Use addition TOP ... right after the key word
SELECT.
a) See source code extract from the model solution.
5. Add another value assignment with output parameter et_late on the left and a second
SELECT statement on the right. The only difference between the two SELECT statements
should be the sort order (ascending instead of descending).
a) See source code extract from the model solution.
6. Use addition USING ... to make the ABAP Dictionary object HA400_CDS_SQL_S1 (SQL
View) known inside the AMDP source code.
a) See source code extract from the model solution.
7. Optional: Use addition OPTIONS READ-ONLY to document that the procedure does not
contain any write access to the database.
a) See source code extract from the model solution.
© Copyright. All rights reserved.
239
Unit 4: SAP HANA specific Code-to-Data
8. Activate and test the class.
a) Choose Activate from the toolbar or press Ctrl + F3 on your keyboard.
b) Choose Run As ... → ABAP Application from the toolbar or press F8 on your keyboard.
c) Verify that your code matches the following solution:
Source code extract from model solution (Class CL_HA400_AMDP_S1)
CLASS cl_ha400_amdp_s1 DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_amdp_marker_hdb.
TYPES: BEGIN OF ty_s_customer,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode
TYPE scustom-postcode,
city
TYPE scustom-city,
country
TYPE scustom-country,
days_ahead TYPE ha400_avgnd,
END OF ty_s_customer.
TYPES: ty_t_customers TYPE STANDARD TABLE OF ty_s_customer
WITH NON-UNIQUE KEY id name.
CLASS-METHODS early_bird_and_last_minute
IMPORTING VALUE(iv_number) TYPE i
EXPORTING VALUE(et_early) TYPE ty_t_customers
VALUE(et_late)
TYPE ty_t_customers.
ENDCLASS.
CLASS CL_HA400_AMDP_S1 IMPLEMENTATION.
METHOD early_bird_and_last_minute
BY DATABASE PROCEDURE
FOR HDB LANGUAGE SQLSCRIPT
OPTIONS READ-ONLY
USING HA400_CDS_SQL_S1.
et_early = select top :iv_number
id,
name,
postcode,
city,
country,
avg( days_ahead ) as days_ahead
from HA400_CDS_SQL_S1
where mandt = session_context('CLIENT')
group by id,
name,
postcode,
city,
240
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
country
order by days_ahead DESC;
et_late = select top :iv_number
id,
name,
postcode,
city,
country,
avg( days_ahead ) as days_ahead
from HA400_CDS_SQL_S1
where mandt = session_context('CLIENT')
group by id,
name,
postcode,
city,
country
order by days_ahead ASC;
ENDMETHOD.
ENDCLASS.
Task 4: Call the ABAP-Managed Database Procedure
In subroutine get_data_solution of your program ZHA400_##_AMDP, use your newly defined
ABAP-Managed Database Procedure to read the data from the database.
1. Edit your program. In subroutine get_data_solution, call the static method that defines the
AMDP.
a) See source code extract from the model solution.
2. Activate and test your program.
a) Activate and execute the program as you have learned in other classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_AMDP_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template USING
pv_number TYPE i
CHANGING ct_cust_early TYPE ty_t_customers
ct_cust_late TYPE ty_t_customers.
* early bookers
SELECT from ha400_booking_with_days
fields customid as id,
name,
postcode,
city,
country,
avg( days_ahead ) as days_ahead
GROUP BY customid,
name,
© Copyright. All rights reserved.
241
Unit 4: SAP HANA specific Code-to-Data
postcode,
city,
country
ORDER BY days_ahead DESCENDING
INTO TABLE @ct_cust_early
UP TO @pv_number ROWS .
* late bookers
SELECT FROM ha400_booking_with_days
FIELDS customid as id,
name,
postcode,
city,
country,
avg( days_ahead ) as days_ahead
GROUP BY customid,
name,
postcode,
city,
country
ORDER BY days_ahead ASCENDING
INTO TABLE @ct_cust_late
UP TO @pv_number ROWS .
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution USING
pv_number TYPE i
CHANGING ct_cust_early TYPE ty_t_customers
ct_cust_late TYPE ty_t_customers.
* Call an AMDP here
cl_ha400_amdp_s1=>early_bird_and_last_minute(
EXPORTING
iv_number = pv_number
IMPORTING
et_early = ct_cust_early
et_late
= ct_cust_late ).
ENDFORM.
"
Task 5: Debug the AMDP
In ABAP Development Tools in Eclipse (ADT), set break-points in the AMDP method and
execute the program that calls the method.
1. In the ABAP perspective in Eclipse, navigate to the implementation of method
early_bird_and_last_minute in your class ZCL_HA400_##_AMDP.
a) Perform this step as before.
2. In the SQLScript code of the AMDP, set two breakpoints, one at each select statement.
a) In each of the two lines with the select statements, double-click the grey bar to the left
of the code.
242
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
3. Remain in the ABAP perspective in Eclipse, navigate back to program, and execute the
ABAP report that calls the database procedure.
a) Execute the program by pressing F8 on your keyboard.
b) On the selection screen, select Solution only to make sure the AMDP is called.
c) When prompted, confirm the switch to the Debugger perspective.
4. In the Debugger perspective of Eclipse, analyze the content of the AMDP procedure’s
parameters.
a) On the right, you find a window labelled Variables with a list of the data objects.
What is the content of the import parameters?
Import parameter iv_number contains the user input from the selection screen. Import
parameter iv_mandt contains the current logon client.
What is the content of the export parameters?
The export parameters of the AMDP, et_late and et_early contain no data yet.
5. Resume execution to the next breakpoint in the AMDP method and display the content of
parameter et_late.
a) Press F8 on your keyboard or choose Resume.
b) In the variable list, right-click parameter et_late and choose Show in Data Preview.
6. Resume execution until the application displays the result.
a) Press F8 on your keybaord or choose Resume.
7. Close the application and the Debug perspective.
a) Close the tab with the embedded SAP GUI window showing the results.
b) In the list of open perspectives, right-click Debug and choose Close.
© Copyright. All rights reserved.
243
Unit 4: SAP HANA specific Code-to-Data
AMDP Enhancement
Figure 173: AMDP BAdI Concept
Animation: AMDP BAdI Concept
For more information on AMDP BAdI Concept, please view the animation in the
lesson ABAP-Managed Database Procedures, online in the SAP Learning Hub.
Similar to regular ABAP code, AMDP can be enhanced if the original software provider
foresees this. To allow for the enhancement of AMDP, the following must apply:
●
244
The software provider has created an Enhancement Spot and a Business Add-In (BAdI)
definition.
●
The BAdI definition is marked as AMDP BAdI.
●
The software provider has provided a fallback class (mandatory for an AMDP BAdI).
●
The AMDP method of the software provider calls the AMDP method of the BAdi definition.
© Copyright. All rights reserved.
Lesson: ABAP-Managed Database Procedures
Figure 175: AMDP BAdI Calls and Implementation
The AMDP method that calls the AMDP BAdI, has to declare its use with the USING clause.
As long as there is active BAdI implementation, the system executes the implementation in
the fallback class when the AMDP BAdI is called. As soon as there is an active BAdI
implementation, the SQLScript coding from the implementation class is executed, instead.
Hint:
If an AMDP BAdI allows for multiple use, each implementation has to merge its
own results with the results of potential co-existing implementations. This can be
done, for example, with a UNION (ALL) clause.
© Copyright. All rights reserved.
245
Unit 4: SAP HANA specific Code-to-Data
LESSON SUMMARY
You should now be able to:
246
●
Understand ABAP-Managed Database Procedures
●
Create an ABAP-Managed Database Procedure
●
Call an ABAP-Managed Database Procedure in ABAP
●
Debug an ABAP-Managed Database Procedure
●
Know how AMDP enhancement works
© Copyright. All rights reserved.
Unit 4
Lesson 3
ABAP Database Connectivity (ADBC)
LESSON OVERVIEW
In this lesson, you learn about ABAP Database Connectivity (ADBC) and use it to execute
native SQL statements.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Understand ABAP Database Connectivity (ADBC)
●
Use ADBC to execute native SQL statements
Basic Features of ADBC
Figure 176: Basic Features of ADBC
Animation: BasicFeaturesofADBC_Ani.mp4
For more information on BasicFeaturesofADBC_Ani.mp4, please view the
animation in the lesson ABAP Database Connectivity (ADBC), online in the SAP
Learning Hub.
We recommend using the ADBC API, for short ADBC, for native SQL calls in ABAP. As an API,
it allows for the determination of where native SQL calls are used and supports exception
handling. It is flexible, object-oriented, and not difficult to use, as only two or three main
classes are relevant in most cases.
© Copyright. All rights reserved.
247
Unit 4: SAP HANA specific Code-to-Data
Usage of ADBC
Logical Sequence for Reading Data with ADBC
1. Choose database connection (only when accessing secondary DB): Call method
get_connection() of class CL_SQL_CONNECTION.
2. Create a statement object: Instantiation of class CL_SQL_STATEMENT.
3. Fill string variable with SQL syntax: Use either CONCATENATE or string templates/string
expressions.
4. Issue native SQL call: Call method execute_query() of class CL_SQL_STATEMENT.
5. Assign target variable for result set: Call method set_param() or set_param_table() of
class CL_SQL_RESULT_SET.
6. Retrieve result set: Call method next_package() of class CL_SQL_RESULT_SET.
7. Close result and release resources: Method close() of class CL_SQL_RESULT_SET.
The logical sequence to issue a native SQL query using ADBC is shown above. Some steps
can be combined in practice when chaining method calls in ABAP or when using string
expressions or string templates. In addition, the first step, getting a database connection, is
necessary only when using a secondary database connection for the native SQL call. A typical
piece of code using ADBC and classical string concatenation to construct the native SQL
string is shown in the figure Coding Example: ABAP Database Connectivity (ADBC).
Figure 178: Coding Example: ABAP Database Connectivity (ADBC)
248
© Copyright. All rights reserved.
Lesson: ABAP Database Connectivity (ADBC)
Figure 179: Important Points when Using ADBC
Animation: Important Points when Using ADBC
For more information on Important Points when Using ADBC, please view the
animation in the lesson ABAP Database Connectivity (ADBC), online in the SAP
Learning Hub.
When using native SQL, you should be aware of several pitfalls, such as the following:
●
●
The syntax of a native SQL string is not checked by the ABAP compiler. Handle exception
CX_SQL_EXCEPTION to be able to analyze messages returned by the database if the native
SQL string contains an error. This may be especially helpful because the syntax of native
SQL differs from the syntax of Open SQL.
Native SQL calls bypass the ABAP database interface. As a consequence, the following
occurs:
-
-
The ABAP table buffer is bypassed. This can make some native SQL calls slower than
Open SQL statements. In addition, changing data via native SQL is not recommended
because the ABAP table buffer gets out of sync.
WHERE conditions, JOIN conditions, and so on, have to include the client field explicitly.
© Copyright. All rights reserved.
249
Unit 4: SAP HANA specific Code-to-Data
250
© Copyright. All rights reserved.
Unit 4
Exercise 14
Issue a Native SQL Statement via ADBC
Simulation: Issue a Native SQL Statement via ADBC
For more information on Issue a Native SQL Statement via ADBC, please view
the simulation in the lesson ABAP Database Connectivity (ADBC) online in the
SAP Learning Hub.
Business Example
You run an ABAP program on an application server that is connected to a SAP HANA
database. You want to access SAP HANA-specific functionality that is not available via Open
SQL or CDS. In a first step, you replace an Open SQL statement with a native SQL statement.
Template:
Report HA400_NATIVE_SQL_T1
Solution:
Report HA400_NATIVE_SQL_S1
Task 1: Copy and Understand the Template
In system T8N, which has SAP HANA as its primary database, create a copy of report
HA400_NATIVE_SQL_T1 in your package ZHA400_## (suggested name:
ZHA400_##_NATIVE_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze subroutine get_data_template. Uncomment the alternative Open SQL SELECT
statement at the end of the subroutine and perform a syntax check
Why do you get an error message from the syntax check?
3. Remove or comment out the alternative SQL statement. Then activate and execute the
program.
Task 2: Use ADBC for Native SQL-SELECT with a Join
Edit your program. In subroutine get_data_solution, use ADBC to issue a native SQL SELECT
that reads from DB tables SCUSTOM and SBOOK. Make sure you read exactly the same data
as subroutine get_data_template. Make use of the fact that SAP HANA native SQL supports
expressions and functions as argument of aggregate function AVG( ).
© Copyright. All rights reserved.
251
Unit 4: SAP HANA specific Code-to-Data
Hint:
In the template program, subroutine get_data_solution already contains two
suggestions for how to fill a string variable with the required native SQL
statement. Uncomment one of these statements if you don’t want to spend too
much time trying to get the native SQL syntax right.
1. In subroutine get_data_solution, create an instance of class CL_SQL_CONNECTION by
calling static method get_connection.
Note:
This step is only needed in case you want to send the native SQL statement to
a secondary database. We do this step here for the sake of completeness.
2. Create an instance of class CL_SQL_STATEMENT, handing over the instance of
CL_SQL_CONNECTION to the constructor.
Hint:
As of SAP Netweaver 7.02, you may chain this method and the previous one,
thus omitting the reference variable for the connection object.
3. Define a string variable (suggested name: lv_sql) and fill it with the native SQL syntax that
corresponds to the alternative Open SQL statement in subroutine get_data_solution. Use
either a classical CONCATENATE statement or the more modern string-expression with
string templates.
4. Create an instance of CL_SQL_RESULT_SET by executing the query.
Hint:
Use public instance method execute_query of class CL_SQL_STATEMENT.
5. Define a reference variable of type REF TO DATA, let it point to the target data object and
hand this reference over to the instance of CL_SQL_RESULT_SET.
Hint:
Use method set_param_table of class CL_SQL_RESULT_SET.
6. Retrieve the result and close the query.
Hint:
Use methods next_package and close of class CL_SQL_RESULT_SET.
252
© Copyright. All rights reserved.
Lesson: ABAP Database Connectivity (ADBC)
7. Implement suitable exception handling for all class-based exceptions that might be raised
by the called ADBC methods.
8. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
© Copyright. All rights reserved.
253
Unit 4
Solution 14
Issue a Native SQL Statement via ADBC
Simulation: Issue a Native SQL Statement via ADBC
For more information on Issue a Native SQL Statement via ADBC, please view
the simulation in the lesson ABAP Database Connectivity (ADBC) online in the
SAP Learning Hub.
Business Example
You run an ABAP program on an application server that is connected to a SAP HANA
database. You want to access SAP HANA-specific functionality that is not available via Open
SQL or CDS. In a first step, you replace an Open SQL statement with a native SQL statement.
Template:
Report HA400_NATIVE_SQL_T1
Solution:
Report HA400_NATIVE_SQL_S1
Task 1: Copy and Understand the Template
In system T8N, which has SAP HANA as its primary database, create a copy of report
HA400_NATIVE_SQL_T1 in your package ZHA400_## (suggested name:
ZHA400_##_NATIVE_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Analyze subroutine get_data_template. Uncomment the alternative Open SQL SELECT
statement at the end of the subroutine and perform a syntax check
a) Complete this step as you learned to do in previous classes.
Why do you get an error message from the syntax check?
Because the argument of aggregate function AVG( ) is an SQL expression (an SQL
function, in our case). This is not supported in Open SQL.
3. Remove or comment out the alternative SQL statement. Then activate and execute the
program.
a) Complete this step as you learned to do in previous classes.
Task 2: Use ADBC for Native SQL-SELECT with a Join
Edit your program. In subroutine get_data_solution, use ADBC to issue a native SQL SELECT
that reads from DB tables SCUSTOM and SBOOK. Make sure you read exactly the same data
254
© Copyright. All rights reserved.
Lesson: ABAP Database Connectivity (ADBC)
as subroutine get_data_template. Make use of the fact that SAP HANA native SQL supports
expressions and functions as argument of aggregate function AVG( ).
Hint:
In the template program, subroutine get_data_solution already contains two
suggestions for how to fill a string variable with the required native SQL
statement. Uncomment one of these statements if you don’t want to spend too
much time trying to get the native SQL syntax right.
1. In subroutine get_data_solution, create an instance of class CL_SQL_CONNECTION by
calling static method get_connection.
Note:
This step is only needed in case you want to send the native SQL statement to
a secondary database. We do this step here for the sake of completeness.
a) See source code extract from model solution.
2. Create an instance of class CL_SQL_STATEMENT, handing over the instance of
CL_SQL_CONNECTION to the constructor.
Hint:
As of SAP Netweaver 7.02, you may chain this method and the previous one,
thus omitting the reference variable for the connection object.
a) See source code extract from model solution.
3. Define a string variable (suggested name: lv_sql) and fill it with the native SQL syntax that
corresponds to the alternative Open SQL statement in subroutine get_data_solution. Use
either a classical CONCATENATE statement or the more modern string-expression with
string templates.
a) See source code extract from model solution.
4. Create an instance of CL_SQL_RESULT_SET by executing the query.
Hint:
Use public instance method execute_query of class CL_SQL_STATEMENT.
a) See source code extract from model solution.
5. Define a reference variable of type REF TO DATA, let it point to the target data object and
hand this reference over to the instance of CL_SQL_RESULT_SET.
Hint:
Use method set_param_table of class CL_SQL_RESULT_SET.
a) See source code extract from model solution.
© Copyright. All rights reserved.
255
Unit 4: SAP HANA specific Code-to-Data
6. Retrieve the result and close the query.
Hint:
Use methods next_package and close of class CL_SQL_RESULT_SET.
a) See source code extract from model solution.
7. Implement suitable exception handling for all class-based exceptions that might be raised
by the called ADBC methods.
a) See source code extract from model solution.
8. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_NATIVE_SQL_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* Types for target fields
TYPES: BEGIN OF lty_s_cust,
id
TYPE scustom-id,
name
TYPE scustom-name,
postcode TYPE scustom-postcode,
city
TYPE scustom-city,
country TYPE scustom-country,
days_sum TYPE i,
count
TYPE i,
END OF lty_s_cust.
* Work Area for Result
DATA ls_customer LIKE LINE OF ct_customers.
* Targets for Select
DATA: lt_cust TYPE SORTED TABLE OF lty_s_cust
WITH NON-UNIQUE KEY id,
ls_cust TYPE lty_s_cust.
* Processing
*****************
CLEAR ct_customers.
SELECT FROM sbook AS b INNER JOIN scustom AS c
ON b~customid = c~id
FIELDS c~id,
c~name,
256
© Copyright. All rights reserved.
Lesson: ABAP Database Connectivity (ADBC)
c~postcode,
c~city,
c~country,
SUM( dats_days_between( b~order_date, b~fldate )
) AS days_sum,
COUNT( * ) AS count
WHERE b~cancelled <> 'X'
GROUP BY c~id, c~name, c~postcode, c~city, c~country
ORDER BY c~id
INTO TABLE @lt_cust.
LOOP AT lt_cust INTO ls_cust.
ls_customer-id
= ls_cust-id.
ls_customer-name
= ls_cust-name.
ls_customer-postcode = ls_cust-postcode.
ls_customer-city
= ls_cust-city.
ls_customer-country = ls_cust-country.
ls_customer-days_ahead =
round( val = ls_cust-days_sum / ls_cust-count
dec = 4
mode = cl_abap_math=>round_down ).
INSERT ls_customer INTO TABLE ct_customers.
ENDLOOP.
* Direct calculation of Average doesn't work in Open SQL because
* aggregation over function dats_days_between( ) is not supported
*
* SELECT FROM sbook AS b INNER JOIN scustom AS c
*
ON b~customid = c~id
*
FIELDS c~id,
*
c~name,
*
c~postcode,
*
c~city,
*
c~country
*
AVG( DATS_DAYS_BETWEEN( b~order_date, b~fldate )
) as days_ahead
*
WHERE b~cancelled <> 'X'
*
GROUP BY c~id, c~name, c~postcode, c~city, c~country
*
ORDER BY c~id
*
INTO TABLE @ct_customers.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
* ADBC Objects and Variables
DATA: lo_con
TYPE REF TO cl_sql_connection,
lv_sql
TYPE string,
lo_sql
TYPE REF TO cl_sql_statement,
lo_result TYPE REF TO cl_sql_result_set,
lr_data
TYPE REF TO data.
* Exception Handling
DATA: lx_sql_exc TYPE REF TO cx_sql_exception.
© Copyright. All rights reserved.
257
Unit 4: SAP HANA specific Code-to-Data
* Processing
****************************
CLEAR ct_customers.
TRY.
* 1. Get DB Connection (optional for accessing primary database)
lo_con = cl_sql_connection=>get_connection( c_primdb ).
* 2. Create statement object
CREATE OBJECT lo_sql
EXPORTING
con_ref = lo_con.
* 3. assemble SQL statement
CONCATENATE
`SELECT `
`C.ID, `
`C.NAME, `
`C.POSTCODE, `
`C.CITY, `
`C.COUNTRY, `
`AVG( DAYS_BETWEEN( B.ORDER_DATE, B.FLDATE )) AS days_ahead `
`FROM SBOOK AS B INNER JOIN SCUSTOM AS C `
`ON B.MANDT = C.MANDT `
`AND B.CUSTOMID = C.ID `
`WHERE B.CANCELLED <> 'X' `
`AND C.MANDT = `
`'`
sy-mandt
`'`
`GROUP BY C.ID, C.NAME, C.POSTCODE, C.CITY, C.COUNTRY `
`ORDER BY C.ID `
INTO lv_sql.
* Alternative Use string templates and string expressions
*
lv_sql = |SELECT |
&&
*
|C.ID, |
&&
*
|C.NAME, |
&&
*
|C.POSTCODE,|
&&
*
|C.CITY, |
&&
*
|C.COUNTRY, |
&&
*
|AVG( DAYS_BETWEEN( B.ORDER_DATE, B.FLDATE ) | &&
*
|
) AS days_ahead |
&&
*
|FROM SBOOK AS B INNER JOIN SCUSTOM AS C | &&
*
|ON B.MANDT = C.MANDT | &&
*
|AND B.CUSTOMID = C.ID | &&
*
|WHERE C.MANDT = '{ sy-mandt }' | &&
*
|AND B.CANCELLED <> 'X' | &&
*
|GROUP BY C.ID, C.NAME, C.POSTCODE, | &&
*
|C.CITY, C.COUNTRY | &&
*
|ORDER BY C.ID |.
* 4. Execute Query
lo_result = lo_sql->execute_query( lv_sql ).
* 5. Assign target variable
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
258
© Copyright. All rights reserved.
Lesson: ABAP Database Connectivity (ADBC)
* 6. Read result into internal Table
lo_result->next_package( ).
* 7. Close connection
lo_result->close( ).
* Exception handling
CATCH cx_sql_exception INTO lx_sql_exc."Excpt. Class for SQL Error
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
© Copyright. All rights reserved.
"
259
Unit 4: SAP HANA specific Code-to-Data
LESSON SUMMARY
You should now be able to:
260
●
Understand ABAP Database Connectivity (ADBC)
●
Use ADBC to execute native SQL statements
© Copyright. All rights reserved.
Unit 4
Learning Assessment
1. Which of the following are common ground between SAP HANA syntax and Open SQL
syntax (as of ABAP 7.40 SP05)?
Choose the correct answers.
X
A Key words are not case-sensitive
X
B Table names have to be upper-case
X
C Identical client handling
X
D Comma-separated field lists
X
E Field list after FROM clause is supported
2. In SAP HANA SQL, it is mandatory to specify a schema before the table name.
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following are supported types for parameters of AMDP methods?
Choose the correct answers.
X
A Numeric or character-like scalar types
X
B Structure types with only scalar components
X
C Table types with only scalar columns
X
D Nested table types without secondary keys
4. All ABAP objects used within the body of an AMDP method have to be listed after the
USING addition.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
261
Unit 4: Learning Assessment
5. Any AMDP method shipped by SAP can be extended using the AMDP BAdI technique.
Determine whether this statement is true or false.
X
True
X
False
6. What can you do in ADT (ABAP in Eclipse) but not in the classical ABAP Workbench?
Choose the correct answers.
X
A Display an AMDP method implementation
X
B Edit an AMDP method implementation
X
C Test an AMDP method implementation
X
D Debug an AMDP method implementation
7. When executing a native SQL query via ABAP Database Connectivity (ADBC), which of the
following steps is optional?
Choose the correct answer.
X
A Create an instance of CL_SQL_CONNECTION.
X
B Create an instance of CL_SQL_STATEMENT.
X
C Create an instance of CL_SQL_RESULT_SET.
X
D None, all three are mandatory.
8. What happens if you forget to call method close( ) at the end of your query?
Choose the correct answer.
262
X
A You don’t forget a result.
X
B An exception is raised.
X
C DB resources remain blocked.
X
D Nothing.
© Copyright. All rights reserved.
UNIT 5
Consuming SAP HANA Objects
in ABAP
Lesson 1
Working with SAP HANA Objects in SAP HANA Studio
265
Lesson 2
Consuming SAP HANA Objects with Native SQL
Exercise 15: Access an SAP HANA View via Native SQL
271
275
Lesson 3
Using Proxy Objects to Consume SAP HANA Objects
Exercise 16: Create an External View for SAP HANA View and Use it in an Open SQL
SELECT
UNIT OBJECTIVES
●
Analyze and test SAP HANA objects
●
Read from SAP HANA views with native SQL
●
Call SAP HANA stored procedures with native SQL
●
Define and use external views
●
Understand Database Procedure Proxies
© Copyright. All rights reserved.
263
285
291
Unit 5: Consuming SAP HANA Objects in ABAP
264
© Copyright. All rights reserved.
Unit 5
Lesson 1
Working with SAP HANA Objects in SAP HANA
Studio
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Analyze and test SAP HANA objects
Definition of SAP HANA Views
Figure 182: Open Definition and Data Preview
© Copyright. All rights reserved.
265
Unit 5: Consuming SAP HANA Objects in ABAP
Data Preview for SAP HANA Views
Figure 183: Preview of Raw Data
Figure 184: Analysis of Distinct Values
266
© Copyright. All rights reserved.
Lesson: Working with SAP HANA Objects in SAP HANA Studio
Figure 185: Graphical Analysis
Analyzing SAP HANA Procedures
Figure 186: Parameters of a Procedure
© Copyright. All rights reserved.
267
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 187: Parameter Details
Figure 188: Source Code of Procedure
268
© Copyright. All rights reserved.
Lesson: Working with SAP HANA Objects in SAP HANA Studio
Testing SAP HANA Procedures
Figure 189: Test Procedures – Open SQL Console
Animation: Test Procedures – Open SQL Console
For more information on Test Procedures – Open SQL Console, please view the
animation in the lesson Working with SAP HANA Objects in SAP HANA Studio,
online in the SAP Learning Hub.
To open the SQL Console, do the following:
1. Select the SAP HANA system.
2. Choose the Open SQL Console button.
Figure 191: Test Procedures – Enter Procedure Call in SQL Console
To test a procedure, do the following:
1. Enter a call statement in the SQL Console.
2. Specify values for parameters (import parameters first, “null” for output parameters).
3. Choose Execute.
© Copyright. All rights reserved.
269
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 192: Test Procedures – See Result
The result is displayed on several Result tabs (one tab per output parameter).
LESSON SUMMARY
You should now be able to:
●
270
Analyze and test SAP HANA objects
© Copyright. All rights reserved.
Unit 5
Lesson 2
Consuming SAP HANA Objects with Native
SQL
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Read from SAP HANA views with native SQL
●
Call SAP HANA stored procedures with native SQL
SAP HANA Views Without Input Parameters
Figure 193: Consuming SAP HANA Views – Logical Picture
© Copyright. All rights reserved.
271
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 194: Consuming HANA Views Native SQL Syntax
SAP HANA Views with Input Parameters
Figure 195: Consuming SAP HANA Views with Input Parameters – Logical View
Input Parameters in SAP HANA Views – The Facts
●
272
An Analytical View or Calculation View may have input parameters that can be used for the
following:
© Copyright. All rights reserved.
Lesson: Consuming SAP HANA Objects with Native SQL
-
Setting a filter on a column or columns
-
Specifying a reference currency or unit of measurement
-
Passing other values to be used in calculations
●
Parameters can be optional, but may be mandatory
●
Parameters can have a default value, but will not necessarily have one
●
You pass parameter values to the SAP HANA view immediately after the view name in the
FROM clause
Figure 196: Consuming SAP HANA Views with Input Parameters – Native SQL Syntax
© Copyright. All rights reserved.
273
Unit 5: Consuming SAP HANA Objects in ABAP
274
© Copyright. All rights reserved.
Unit 5
Exercise 15
Access an SAP HANA View via Native SQL
Simulation: Access an SAP HANA View via Native SQL
For more information on Access an SAP HANA View via Native SQL, please view
the simulation in the lesson Consuming SAP HANA Objects with Native SQL
online in the SAP Learning Hub.
Business Example
You make use of SAP HANA to improve the performance of an ABAP program. You realize
that a large part of the computation is still performed in the ABAP system. You know that your
SAP HANA system already contains a modelled SAP HANA view performing the same
computation. You want to make use of it to further improve the performance of your ABAP
program.
Template:
Report HA400_HANA_VIEW_T1
Solution:
Report HA400_HANA_VIEW_S1
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_HANA_VIEW_T1 in your package ZHA400_## (suggested name:
ZHA400_##_HVIEW_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Activate and execute the program.
Task 2: Use a SAP HANA View in a Native SQL Select
Edit your ABAP program. Copy the source code of subroutine get_data_template to
subroutine get_data_solution. In subroutine get_data_solution, implement a native SQL
SELECT that fills internal table ct_customers from view CA_DAYS_AHEAD.
Hint:
The view is located in SAP HANA content package ha400.primdb.
1. Copy the source code of subroutine get_data_template to subroutine get_data_solution.
2. In subroutine get_data_solution, change the native SQL statement. In the FROM-clause,
replace the join of tables SCUSTOM and SBOOK with the view you just found. Remember
© Copyright. All rights reserved.
275
Unit 5: Consuming SAP HANA Objects in ABAP
to state the view's name with it's complete path, such as <package name>.<subpackage
name>. ... ::<view name>
Note:
Alternatively, you can address the view in Schema _SYS_BIC directly, such as
with path _SYS_BIC<package name>.<subpackage name>. ... /<view name>.
Caution:
Names on SAP HANA are case sensitive. But everything not included in
inverted commas will be translated to upper case.
3. Adjust the field list, GROUP BY clause and ORDER BY clause of your SQL statement. Make
the field names correspond to the field names in the view. In the aggregation function
AVG( ), replace SAP HANA function days_ahead( ) with view field DAYS_AHEAD.
4. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
276
© Copyright. All rights reserved.
Unit 5
Solution 15
Access an SAP HANA View via Native SQL
Simulation: Access an SAP HANA View via Native SQL
For more information on Access an SAP HANA View via Native SQL, please view
the simulation in the lesson Consuming SAP HANA Objects with Native SQL
online in the SAP Learning Hub.
Business Example
You make use of SAP HANA to improve the performance of an ABAP program. You realize
that a large part of the computation is still performed in the ABAP system. You know that your
SAP HANA system already contains a modelled SAP HANA view performing the same
computation. You want to make use of it to further improve the performance of your ABAP
program.
Template:
Report HA400_HANA_VIEW_T1
Solution:
Report HA400_HANA_VIEW_S1
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_HANA_VIEW_T1 in your package ZHA400_## (suggested name:
ZHA400_##_HVIEW_1, where ## is your group number). Activate and execute the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned to do in previous classes.
2. Activate and execute the program.
a) Complete this step as you learned to do in previous classes.
Task 2: Use a SAP HANA View in a Native SQL Select
Edit your ABAP program. Copy the source code of subroutine get_data_template to
subroutine get_data_solution. In subroutine get_data_solution, implement a native SQL
SELECT that fills internal table ct_customers from view CA_DAYS_AHEAD.
Hint:
The view is located in SAP HANA content package ha400.primdb.
1. Copy the source code of subroutine get_data_template to subroutine get_data_solution.
© Copyright. All rights reserved.
277
Unit 5: Consuming SAP HANA Objects in ABAP
a) Use Copy & Paste function of the ABAP Editor.
2. In subroutine get_data_solution, change the native SQL statement. In the FROM-clause,
replace the join of tables SCUSTOM and SBOOK with the view you just found. Remember
to state the view's name with it's complete path, such as <package name>.<subpackage
name>. ... ::<view name>
Note:
Alternatively, you can address the view in Schema _SYS_BIC directly, such as
with path _SYS_BIC<package name>.<subpackage name>. ... /<view name>.
Caution:
Names on SAP HANA are case sensitive. But everything not included in
inverted commas will be translated to upper case.
a) See source code extract from model solution.
3. Adjust the field list, GROUP BY clause and ORDER BY clause of your SQL statement. Make
the field names correspond to the field names in the view. In the aggregation function
AVG( ), replace SAP HANA function days_ahead( ) with view field DAYS_AHEAD.
a) See source code extract from model solution.
4. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_HANA_VIEW_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* ADBC Objects and Variables
DATA: lo_con
TYPE REF TO cl_sql_connection,
lv_sql
TYPE string,
lo_sql
TYPE REF TO cl_sql_statement,
lo_result TYPE REF TO cl_sql_result_set,
lr_data
TYPE REF TO data.
* Exception Handling
DATA: lx_sql_exc TYPE REF TO cx_sql_exception.
* Processing
****************************
CLEAR ct_customers.
TRY.
* 1. Get DB Connection (optional for accessing primary database)
lo_con = cl_sql_connection=>get_connection( c_primdb ).
278
© Copyright. All rights reserved.
Lesson: Consuming SAP HANA Objects with Native SQL
* 2. Create statement object
CREATE OBJECT lo_sql
EXPORTING
con_ref = lo_con.
* 3. assemble SQL statement
lv_sql =
|SELECT |
&&
|C.ID, |
&&
|C.NAME, |
&&
|C.POSTCODE,|
&&
|C.CITY, |
&&
|C.COUNTRY, |
&&
|AVG( DAYS_BETWEEN( B.ORDER_DATE, B.FLDATE ) ) AS days_ahead | &&
|FROM SBOOK AS B INNER JOIN SCUSTOM AS C | &&
|ON B.MANDT = C.MANDT | &&
|AND B.CUSTOMID = C.ID | &&
|WHERE C.MANDT = '{ sy-mandt }' | &&
|AND B.CANCELLED <> 'X' | &&
|GROUP BY C.MANDT, C.ID, C.NAME, | &&
|
C.POSTCODE, C.CITY, C.COUNTRY | &&
|ORDER BY C.MANDT, C.ID |.
* 4. Execute Query
lo_result = lo_sql->execute_query( lv_sql ).
* 5. Assign target variable
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
* 6. Read result into internal Table
lo_result->next_package( ).
* 7. Close connection
lo_result->close( ).
* Exception handling
CATCH cx_sql_exception INTO lx_sql_exc. "Excpt. Class for SQL Error
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* ADBC Objects and Variables
DATA: lo_sql
TYPE REF TO cl_sql_statement,
lo_result TYPE REF TO cl_sql_result_set,
lv_sql
TYPE string,
lr_data
TYPE REF TO data.
* Exception Handling
DATA:
lx_sql_exc TYPE REF TO cx_sql_exception.
* Processing
****************************
© Copyright. All rights reserved.
279
Unit 5: Consuming SAP HANA Objects in ABAP
CLEAR ct_customers.
TRY.
* Create statement object
CREATE OBJECT lo_sql
*
EXPORTING
*
con_ref =
.
* assemble SQL statement
lv_sql =
|SELECT ID, NAME, POSTCODE, CITY, COUNTRY, | &&
|AVG(DAYS_AHEAD) AS DAYS_AHEAD | &&
|FROM "ha400.primdb::CA_DAYS_AHEAD" | &&
|WHERE MANDT = '{ sy-mandt }' | &&
|GROUP BY MANDT, ID, NAME, POSTCODE, CITY, COUNTRY | &&
|ORDER BY MANDT, ID |.
* older solution: access the runtime object directly
*
(always in schema _SYS_BIC)
*
lv_sql =
*
|SELECT ID, NAME, POSTCODE, CITY, COUNTRY, | &&
*
|AVG(DAYS_AHEAD) AS DAYS_AHEAD | &&
*
|FROM _SYS_BIC."ha400.primdb/CA_DAYS_AHEAD" | &&
*
|WHERE MANDT = '{ sy-mandt }' | &&
*
|GROUP BY MANDT, ID, NAME, POSTCODE, CITY, COUNTRY | &&
*
|ORDER BY MANDT, ID |.
*
* Execute Query
lo_result = lo_sql->execute_query( lv_sql ).
* Assign target variable
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
* Read result into internal Table
lo_result->next_package( ).
* Close connection
lo_result->close( ).
* Exception handling
CATCH cx_sql_exception INTO lx_sql_exc. "Excpt. Class for SQL Error
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
280
"
© Copyright. All rights reserved.
Lesson: Consuming SAP HANA Objects with Native SQL
Calling SAP HANA Database Procedures
Figure 198: Calling SAP HANA Procedures with Overview
Figure 199: Calling SAP HANA Procedures – Retrieve One Result Set
© Copyright. All rights reserved.
281
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 200: Calling HANA Procedures with Overview Native SQL Syntax
Figure 201: Coding Example: Calling SAP HANA Procedure with Overview
282
© Copyright. All rights reserved.
Lesson: Consuming SAP HANA Objects with Native SQL
Figure 202: Coding Example: Retrieving Result from Overview
© Copyright. All rights reserved.
283
Unit 5: Consuming SAP HANA Objects in ABAP
LESSON SUMMARY
You should now be able to:
284
●
Read from SAP HANA views with native SQL
●
Call SAP HANA stored procedures with native SQL
© Copyright. All rights reserved.
Unit 5
Lesson 3
Using Proxy Objects to Consume SAP HANA
Objects
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Define and use external views
●
Understand Database Procedure Proxies
External Views
As of SAP NetWeaver 7.4, a new repository object type called an “external view” is available in
the ABAP Dictionary.
Figure 203: What Is an External View?
External views can be created in an ABAP system using SAP HANA as the primary database.
An external view represents an SAP HANA view on the ABAP side, as proxy for an SAP HANA
view in the ABAP Dictionary. It makes the view and its field list visible to the ABAP stack and
allows for access to the SAP HANA view via Open SQL and for the performance of syntax
checks.
External views have many things in common with database views created in the ABAP
Dictionary. Both can be used as data types in ABAP programs and in the FROM clause of
Open SQL SELECT statements.
© Copyright. All rights reserved.
285
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 204: Reminder: Database View in ABAP Dictionary
While Dictionary views completely define their corresponding objects on the database,
external views are just proxies for the SAP HANA views they represent and, for example, do
not contain the information about the underlying tables and join conditions.
Figure 205: New: External View in ABAP Dictionary
In short, one could say that the database view on the database follows the definition of the
Dictionary object. The external view only provides a thin wrapper of a database view to the
ABAP world.
286
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
Creation of External Views in ABAP Development Tools (ADT)
Figure 206: Create External View New ABAP Repository Object
Animation: Create External View New ABAP Repository Object
For more information on Create External View New ABAP Repository Object,
please view the animation in the lesson Using Proxy Objects to Consume SAP
HANA Objects, online in the SAP Learning Hub.
To create an external view, you have to use the ADT. External views are not supported by the
ABAP Workbench.
In the ABAP project, open the context menu and choose New → Other or New → Other ABAP
Repository Object. Open the folder ABAP Dictionary and select Dictionary View. Specify the
following:
●
The ABAP package to which the external view is to belong
●
The ABAP name and description
●
Choose External View
●
The full name, including the SAP HANA content package name, of the SAP HANA column
view for which the external view is to be created
© Copyright. All rights reserved.
287
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 208: Create External View – Adjust Dictionary Types
Adjust the mapping from the SAP HANA types used in the SAP HANA column view to the
ABAP types used in the ABAP representation.
Data Type Mapping Between SAP HANA and ABAP Dictionary
Figure 209: Mapping of HANA Types and Dictionary Types
288
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
External Views in Open SQL SELECT Statements
Figure 210: Using External View in ABAP
Once the external view is created and activated, you can declare local variables and internal
ABAP tables using it as a structured data type, and you can retrieve data from the view using
regular Open SQL SELECT statements.
Problems When Using External Views
Animation:
For more information on , please view the animation in the lesson Using Proxy
Objects to Consume SAP HANA Objects, online in the SAP Learning Hub.
No Data Elements for View Components
●
Only technical information. No labels, documentation, and so on.
●
Avoid using external views as data type for UI fields.
Danger of Runtime Errors
●
●
●
Changes to SAP HANA view interface require manual synchronization of external
view.
Syntax check only ensures existence of external view not existence of stored
procedure.
Runtime errors occur if the SAP HANA view does not exist, does not match external
view interface, or if database is not SAP HANA.
Traceability Issues
●
The SAP HANA studio will not tell you which ABAP external views refer to a particular
SAP HANA view.
© Copyright. All rights reserved.
289
Unit 5: Consuming SAP HANA Objects in ABAP
290
© Copyright. All rights reserved.
Unit 5
Exercise 16
Create an External View for SAP HANA View
and Use it in an Open SQL SELECT
Simulation: Create an External View for SAP HANA View and Use it in an Open
SQL SELECT
For more information on Create an External View for SAP HANA View and Use it
in an Open SQL SELECT, please view the simulation in the lesson Using Proxy
Objects to Consume SAP HANA Objects online in the SAP Learning Hub.
Business Example
You have an ABAP program that consumes an SAP HANA view using native SQL, because the
program was developed before the ABAP system was migrated to SAP HANA. Since the
ABAP system is migrated now, you want to simplify the ABAP report by making use of an
external dictionary view for the SAP HANA view.
Template:
Report HA400_EXT_VIEW_T1
Solution:
Report HA400_EXT_VIEW_S1
External View HA400_DAYSAHEAD
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_EXT_VIEW_T1 in your package ZHA400_## (suggested name:
ZHA400_##_EXT_VIEW, where ## is your group number). Activate and execute the
program.
Hint:
In this exercise you have to create and edit an external view. This new type of
repository object can only be edited in ABAP Development Tools (ADT). You can
do everything else in the classical ABAP workbench but you might want to take
the opportunity and do the complete exercise in ADT
1. Create a copy of the report HA400_EXT_VIEW_T1 and all its subobjects. Place it in your
package ZHA400_## and assign it to your workbench task.
2. Activate the report and all its sub-objects and execute the program.
© Copyright. All rights reserved.
291
Unit 5: Consuming SAP HANA Objects in ABAP
Task 2: Create an External View
In the system that has SAP HANA as its primary database, create a new external view
(suggested name: ZHA400_##_DAYS, where ## is your group number). Make the view a
representation of the SAP HANA view CA_DAYS_AHEAD in SAP HANA content package
ha400.primdb. Adjust the suggested dictionary types to match the dictionary types used in
your program.
1. In your package, create a new view as External View and let it point to the SAP HANA view.
2. Open the definition of the external view. Use the dropdown lists in column DDIC Type to
adjust the suggested type where necessary.
Hint:
Have a look at the definition of transparent tables SCUSTOM and SBOOK and
at the local structure type ty_s_customer and navigate into the relevant data
elements.
3. Save and activate the external view.
Task 3: Use the External View in an Open SQL Select
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, replace the native SQL SELECT that fills
internal table ct_customers directly without any further processing. Select from the view you
just found and implement the aggregation (calculation of average) in the SELECT statement.
1. Copy the source code of subroutine get_data_template to subroutine get_data_solution
2. In subroutine get_data_solution, remove or comment out all declarations and method calls
related to the use of ADBC.
3. Implement an Open SQL SELECT-statement that has your newly created external view in
the FROM-clause. Use the native SQL statement in subroutine get_data_template as a
template.
4. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
292
© Copyright. All rights reserved.
Unit 5
Solution 16
Create an External View for SAP HANA View
and Use it in an Open SQL SELECT
Simulation: Create an External View for SAP HANA View and Use it in an Open
SQL SELECT
For more information on Create an External View for SAP HANA View and Use it
in an Open SQL SELECT, please view the simulation in the lesson Using Proxy
Objects to Consume SAP HANA Objects online in the SAP Learning Hub.
Business Example
You have an ABAP program that consumes an SAP HANA view using native SQL, because the
program was developed before the ABAP system was migrated to SAP HANA. Since the
ABAP system is migrated now, you want to simplify the ABAP report by making use of an
external dictionary view for the SAP HANA view.
Template:
Report HA400_EXT_VIEW_T1
Solution:
Report HA400_EXT_VIEW_S1
External View HA400_DAYSAHEAD
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_EXT_VIEW_T1 in your package ZHA400_## (suggested name:
ZHA400_##_EXT_VIEW, where ## is your group number). Activate and execute the
program.
Hint:
In this exercise you have to create and edit an external view. This new type of
repository object can only be edited in ABAP Development Tools (ADT). You can
do everything else in the classical ABAP workbench but you might want to take
the opportunity and do the complete exercise in ADT
1. Create a copy of the report HA400_EXT_VIEW_T1 and all its subobjects. Place it in your
package ZHA400_## and assign it to your workbench task.
a) Complete this step as you learned to do in previous classes.
2. Activate the report and all its sub-objects and execute the program.
a) Complete this step as you learned to do in previous classes.
© Copyright. All rights reserved.
293
Unit 5: Consuming SAP HANA Objects in ABAP
Task 2: Create an External View
In the system that has SAP HANA as its primary database, create a new external view
(suggested name: ZHA400_##_DAYS, where ## is your group number). Make the view a
representation of the SAP HANA view CA_DAYS_AHEAD in SAP HANA content package
ha400.primdb. Adjust the suggested dictionary types to match the dictionary types used in
your program.
1. In your package, create a new view as External View and let it point to the SAP HANA view.
a) Right-click the ABAP project in Eclipse and choose New → ABAP Repository Object.
Expand node Dictionary and double-click Dictionary View.
b) Enter the name of your package, the name of the new view, and a description.
c) Select option External View.
d) Enter the full name of the view, ha400.primdb.CA_DAYS_AHEAD, or the first letters of
the view name CA_DAYS_... and use code completion (Ctrl + Space) to choose the
correct view. Then press Enter.
e) Confirm the transport request and choose Finish.
2. Open the definition of the external view. Use the dropdown lists in column DDIC Type to
adjust the suggested type where necessary.
Hint:
Have a look at the definition of transparent tables SCUSTOM and SBOOK and
at the local structure type ty_s_customer and navigate into the relevant data
elements.
a) Double-click the newly created external view in the Project Explorer.
b) Adjust the ABAP Dictionary types as follows:
DDIC NAME
DDIC Type
MANDT
CLNT
CARRID
CHAR
CONNID
NUMC
FLDATE
DATS
BOOKID
NUMC
ID
NUMC
NAME
CHAR
POSTCODE
CHAR
CITY
CHAR
COUNTRY
CHAR
DAYS_AHEAD
INT4
3. Save and activate the external view.
294
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
a) Choose Save and Activate.
Task 3: Use the External View in an Open SQL Select
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, replace the native SQL SELECT that fills
internal table ct_customers directly without any further processing. Select from the view you
just found and implement the aggregation (calculation of average) in the SELECT statement.
1. Copy the source code of subroutine get_data_template to subroutine get_data_solution
a) Use the Copy & Paste function of the ABAP Editor.
2. In subroutine get_data_solution, remove or comment out all declarations and method calls
related to the use of ADBC.
a) See source code extract from model solution.
3. Implement an Open SQL SELECT-statement that has your newly created external view in
the FROM-clause. Use the native SQL statement in subroutine get_data_template as a
template.
a) See source code extract from model solution.
4. Activate and test your program. Make sure the two subroutines deliver exactly the same
data.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_EXT_VIEW_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template CHANGING ct_customers TYPE ty_t_customers.
* Declarations
****************
* ADBC Objects and Variables
DATA: lo_con
TYPE REF TO cl_sql_connection,
lo_sql
TYPE REF TO cl_sql_statement,
lo_result TYPE REF TO cl_sql_result_set,
lv_sql
TYPE string,
lr_data
TYPE REF TO data.
* Exception Handling
DATA:
lx_sql_exc TYPE REF TO cx_sql_exception.
* Processing
****************************
CLEAR ct_customers.
TRY.
* 1. Get secondary DB Connection
lo_con = cl_sql_connection=>get_connection( co_hanadb ).
* 2. Create statement object
© Copyright. All rights reserved.
295
Unit 5: Consuming SAP HANA Objects in ABAP
CREATE OBJECT lo_sql
EXPORTING
con_ref = lo_con.
* 3. assemble SQL statement
lv_sql = |SELECT ID, NAME, POSTCODE, CITY, COUNTRY, | &&
|AVG(DAYS_AHEAD) AS DAYS_AHEAD | &&
|FROM _SYS_BIC."ha400.primdb/CA_DAYS_AHEAD"
| &&
|WHERE MANDT = { sy-mandt } | &&
|GROUP BY MANDT, ID, NAME, POSTCODE, CITY, COUNTRY
| &&
|ORDER BY MANDT, ID |.
* 4. Execute Query
lo_result = lo_sql->execute_query( lv_sql ).
* 5. Assign target variable
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
* 6. Read result into internal Table
lo_result->next_package( ).
* 7. Close connection
lo_result->close( ).
* Exception handling
CATCH cx_sql_exception INTO lx_sql_exc. "Excpt. Class for
SQL Error
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution CHANGING ct_customers TYPE ty_t_customers.
SELECT id name postcode city country AVG( days_ahead ) AS days_ahead
FROM ha400_daysahead
INTO TABLE ct_customers
GROUP BY id name postcode city country
ORDER BY id.
ENDFORM.
296
"
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
Database Procedure Proxies
Figure 212: Using Stored Procedures in ABAP 7.40 SP02 – SP04
Animation: Using Stored Procedures in ABAP 7.40 SP02 – SP04
For more information on Using Stored Procedures in ABAP 7.40 SP02 – SP04,
please view the animation in the lesson Using Proxy Objects to Consume SAP
HANA Objects, online in the SAP Learning Hub.
ABAP-Managed Database Procedures (ADMPs) are only supported starting with ABAP 7.4
SP05. But ABAP release 7.40 supports another, now outdated, way to simplify the bottom-up
approach of consuming SAP HANA database procedures: a dedicated ABAP Dictionary object
type called Database Procedure Proxy.
© Copyright. All rights reserved.
297
Unit 5: Consuming SAP HANA Objects in ABAP
How Do Database Procedure Proxies Work?
Figure 214: Database Procedure Proxy in ABAP Dictionary
Database Procedure Proxies are a new type of ABAP Dictionary object introduced with ABAP
7.40. They represent, inside the ABAP system, a database procedure that exists outside and
independent of an ABAP system.
They have import and export parameters that are mapped to the parameters of the
procedure.
A Database Procedure Proxy allows you to call the database procedure it represents without
using native SQL. A new ABAP statement CALL DATABASE PROCEDURE is introduced for
this purpose.
298
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
Database Procedure Proxies in ABAP Development Tools (ADT)
Figure 215: Create Database Procedure Proxy_Using ABAP Development Tools
Animation: Create Database Procedure Proxy_Using ABAP Development Tools
For more information on Create Database Procedure Proxy_Using ABAP
Development Tools, please view the animation in the lesson Using Proxy Objects
to Consume SAP HANA Objects, online in the SAP Learning Hub.
To create a Database Procedure Proxy, you have to use ADT. Database Procedure Proxies are
not supported by the ABAP Workbench.
In the ABAP project, open the context menu and choose New → Other or New → Other ABAP
Repository Object. Open the Dictionary folder and select Database Procedure Proxy. Specify
the following:
●
The ABAP package to which the proxy is to belong
●
The ABAP name of the database procedure proxy and its description
●
●
The name of an ABAP OO interface to be created. This interface holds the definition of the
database procedure proxy parameters with their types, mapped to ABAP Dictionary types.
The full name, including the SAP HANA content package name, of the database procedure
for which a proxy is to be created
© Copyright. All rights reserved.
299
Unit 5: Consuming SAP HANA Objects in ABAP
Figure 217: Create Database Procedure Proxy – Adjust Types
Adjust the mapping from the SAP HANA types used in the original database procedure
interface to the ABAP types used in the ABAP representation.
Data Type Mapping Between SAP HANA and ABAP Dictionary
Figure 218: Mapping of HANA Types and ABAP Builtin Types
300
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
Calling Database Procedure Proxies in ABAP
Figure 219: Using Database Procedure Proxies
To call a stored procedure using a Database Procedure Proxy, use the new statement CALL
DATABASE PROCEDURE. The syntax is similar to function calls. For the importing and
exporting parameters, use ABAP variables typed with the types defined in the ABAP OO
interface generated for the procedure proxy.
Problems When Using Database Procedure Proxies
Animation:
For more information on , please view the animation in the lesson Using Proxy
Objects to Consume SAP HANA Objects, online in the SAP Learning Hub.
No Optional Parameters
●
All parameters of procedure proxy are mandatory.
Potential Runtime Errors
●
●
●
Changes to the interface of the stored procedure require manual synchronization of
the procedure proxy.
Syntax check only ensures existence of procedure proxy, not existence of the stored
procedure.
Runtime errors occur if SAP HANA procedure does not exist, does not match proxy
interface, or if database is not SAP HANA.
Traceability Issues
© Copyright. All rights reserved.
301
Unit 5: Consuming SAP HANA Objects in ABAP
●
The SAP HANA studio will not tell you which database procedure proxies refer to a
particular SAP HANA stored procedure.
No Extensibility Mechanism
●
302
There is no extensibility mechanism for database procedure proxies (like for AMDPs).
© Copyright. All rights reserved.
Lesson: Using Proxy Objects to Consume SAP HANA Objects
LESSON SUMMARY
You should now be able to:
●
Define and use external views
●
Understand Database Procedure Proxies
© Copyright. All rights reserved.
303
Unit 5: Consuming SAP HANA Objects in ABAP
304
© Copyright. All rights reserved.
Unit 5
Learning Assessment
1. The search function in the toolbar of SAP HANA studio searches in SAP HANA content
and in the SAP HANA catalog.
Determine whether this statement is true or false.
X
True
X
False
2. You can use Data Preview in SAP HANA studio to test SAP HANA views and SAP HANA
stored procedures.
Determine whether this statement is true or false.
X
True
X
False
3. You want to access SAP HANA view CA_BOOKINGS_COUNT in package ha400.primdb via
a native SQL query. Which of the following are correct ways of specifying package path
and object name in the FROM clause?
Choose the correct answers.
X
A FROM _SYS_BIC.“ha400.primdb.::CA_BOOKINGS_COUNT”
X
B FROM “ha400.primdb::CA_BOOKINGS_COUNT”
X
C FROM _SYS_BIC.“ha400.primdb/CA_BOOKINGS_COUNT”
X
D FROM “ha400.primdb/CA_BOOKINGS_COUNT”
© Copyright. All rights reserved.
305
Unit 5: Learning Assessment
4. You execute the following native SQL query on SAP HANA: CALL
"ha400.primdb::SP_PROCEDURE"( '10', null, null ) WITH OVERVIEW Which
of the following results do you expect?
Choose the correct answer.
X
A Two table-like results
X
B Two scalar results
X
C One scalar result
X
D One table-like result
5. Which of the following object types in ABAP repository are proxy objects for SAP HANA
artefacts?
Choose the correct answers.
X
A Procedure Proxy
X
B Database View
X
C SQL View
X
D External View
6. Which of the following are advantages of using proxy objects for SAP HANA artefacts?
Choose the correct answer.
X
A No native SQL required to access the SAP HANA object
X
B Automatic synchronization of proxy object definition
X
C Automatic transport of SAP HANA artefacts in ABAP transport request
X
D No need for SAP HANA database to define the proxy objects
7. When creating a proxy object for an SAP HANA view, it is possible to specify data
elements for the view fields.
Determine whether this statement is true or false.
306
X
True
X
False
© Copyright. All rights reserved.
UNIT 6
Advanced Topics
Lesson 1
Transporting SAP HANA Objects with ABAP Transport Requests
309
Lesson 2
Using SAP HANA Full Text Search
Exercise 17: Implement a Fuzzy Search
Exercise 18: Implement a Value Help with Fuzzy Search
321
329
337
Lesson 3
ABAP List Viewer with Integrated Database Access (ALV IDA)
Exercise 19: Use ALV with Integrated Data Access for a CDS View
346
357
UNIT OBJECTIVES
●
Know the techniques for ABAP transport of SAP HANA objects
●
Understand SAP HANA Transport Container (HTC)
●
Use SAP HANA Transport for ABAP (HTA)
●
Use SAP HANA full-text search
●
Enable proposal search and fulltext search in a dictionary search help
●
Describe SAP HANA linguistic search
●
Understand the vasics of SAP List Viewer with Integrated Data Access (ALV with IDA)
●
Describe the differences between ALV with IDA and classical ALV
●
Display data with ALV with IDA
●
Use select options in the data retrieval of ALV with IDA
●
Supply values for input parameters of views
© Copyright. All rights reserved.
307
Unit 6: Advanced Topics
308
© Copyright. All rights reserved.
Unit 6
Lesson 1
Transporting SAP HANA Objects with ABAP
Transport Requests
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Know the techniques for ABAP transport of SAP HANA objects
●
Understand SAP HANA Transport Container (HTC)
●
Use SAP HANA Transport for ABAP (HTA)
ABAP Transport of HANA Objects - Overview
Figure 220: Transport of SAP HANA Content - Delivery Units
One way to transport SAP HANA content is via a delivery unit (DU).
Each delivery unit must have a unique name and one or more content packages can be
assigned to the same delivery unit. When you create a new delivery unit, a vendor name is
automatically derived from the system settings and linked to the delivery unit. The SAP
vendor name is sap.com.
© Copyright. All rights reserved.
309
Unit 6: Advanced Topics
Figure 221: First Approach: Manual Synchronization of ABAP Transport and Delivery Unit
As soon as ABAP repository objects depend on SAP HANA objects, it becomes important to
synchronize the transport of SAP HANA content with the ABAP transport. Otherwise you risk
syntax errors or even runtime errors in the target system.
The usual means for transporting SAP HANA objects is the delivery unit. This approach has
two major problems:
●
●
310
The import of the delivery unit into the target system has to be synchronized manually. If it
is imported too early or too late or not at all, there will be inconsistencies in the target
system.
A delivery unit always transports complete SAP HANA content packages. It is not possible
to transport individual objects and packages - for example only those that are new or were
changed since the last transport.
© Copyright. All rights reserved.
Lesson: Transporting SAP HANA Objects with ABAP Transport Requests
Figure 222: Approach as of Release 7.31: HANA Transport Container (HTC)
Animation: Approach as of Release 7.31: HANA Transport Container (HTC)
For more information on Approach as of Release 7.31: HANA Transport
Container (HTC), please view the animation in the lesson Transporting SAP
HANA Objects with ABAP Transport Requests , online in the SAP Learning Hub.
In release 7.31, SAP introduced the SAP HANA Transport Container (HTC). This new ABAP
repository object functions as a proxy object for an SAP HANA delivery unit. If an HTC is
included in the object list of an ABAP transport request, the corresponding delivery unit is
linked to the transport request too.
This allows you to synchronize the import of an ABAP transport request and the import of a
delivery unit into the target system.
Note:
The problem that there is no transport of individual SAP HANA objects remains. A
delivery unit always contains a set of complete content packages - whether the
objects were changed or not.
© Copyright. All rights reserved.
311
Unit 6: Advanced Topics
Figure 224: Approach as of Release 7.40 SP11: SAP HANA Transport for ABAP (HTA)
Animation: Approach as of Release 7.40 SP11: SAP HANA Transport for ABAP
(HTA)
For more information on Approach as of Release 7.40 SP11: SAP HANA
Transport for ABAP (HTA), please view the animation in the lesson Transporting
SAP HANA Objects with ABAP Transport Requests , online in the SAP Learning
Hub.
As of release 7.40 SP11, SAP offers the SAP HANA Transport for ABAP (HTA). The HTA
framework allows you to include individual SAP HANA objects to your ABAP transport
request. Of course it is also possible to transport a complete SAP HANA package with all
contained objects and subpackages.
Note:
If you use HTA you can transport SAP HANA content without defining Delivery
Units.
312
© Copyright. All rights reserved.
Lesson: Transporting SAP HANA Objects with ABAP Transport Requests
HTC and HTA - Important Differences
Figure 226: HTC and HTA - Important Differences
Note:
If you are using HTC, you can continue to use it in a transition period. SAP
recommends, however, that you use HTA for transports of mixed ABAP and SAP
HANA content from Release 7.40 SP11.
SAP HANA Transport Container
Animation: SAP HANA Transport Container – The Principle
For more information on SAP HANA Transport Container – The Principle, please
view the animation in the lesson Transporting SAP HANA Objects with ABAP
Transport Requests , online in the SAP Learning Hub.
SAP HANA Transport Container is an ABAP repository object introduced with SAP NetWeaver
7.31 that allows for the transport of SAP HANA content with an ABAP transport request,
provided the ABAP system uses SAP HANA as its primary database. Basically, it points to,
and represents, a delivery unit.
© Copyright. All rights reserved.
313
Unit 6: Advanced Topics
Figure 228: SAP HANA Transport Container – The Principle
Usage of SAP HANA Transport Containers
If you want to create or maintain an SAP HANA Transport Container (HTC),you have to use
the ABAP Development Tools (ADT) as follows:
●
●
In the context menu of the ABAP project or of an ABAP package, select New → [Other]
ABAP Repository Object.
Choose Others → HANA Transport Container.
Hint:
You can use the filter field to quickly find the correct repository object type.
●
Specify the ABAP package and the name of the SAP HANA delivery unit for which you want
to create the transport container. Note that the HTC name is automatically derived from
the name of the delivery unit.
When you create a SAP HANA Transport Container, you take a snapshot of the full contents of
the corresponding SAP HANA delivery unit and store a copy of it in the ABAP transport
request.
314
© Copyright. All rights reserved.
Lesson: Transporting SAP HANA Objects with ABAP Transport Requests
Figure 229: HANA Transport Container Snapshots
Animation: HANA Transport Container Snapshots
For more information on HANA Transport Container Snapshots, please view the
animation in the lesson Transporting SAP HANA Objects with ABAP Transport
Requests , online in the SAP Learning Hub.
The snapshot is not updated automatically each time the contents of the delivery unit in SAP
HANA changes. The snapshot stored in the SAP HTC has to be kept in sync manually. To do
so, open the SAP HTC and choose Take Snapshot and Save.
As with most ABAP repository objects, you have to activate the SAP HTC before you can
transport it. The SAP HTC is inactive after you create it and each time you edit it, if you take a
new snapshot.
© Copyright. All rights reserved.
315
Unit 6: Advanced Topics
Figure 231: HANA Transport Container Unpacking in Target System
When transported and imported into a target ABAP system, the snapshot is unpacked, and
the SAP HANA content is deployed into the SAP HANA database and activated, provided the
following apply:
●
●
316
The importing ABAP system runs on SAP HANA as the primary database.
The software component to which the SAP HTC belongs is configured for automatic SAP
HTC deployment in the importing ABAP system, which means that it is listed in table
SNHI_DUP_PREWORK.
© Copyright. All rights reserved.
Lesson: Transporting SAP HANA Objects with ABAP Transport Requests
HANA Transport for ABAP (HTA)
Figure 232: HANA Transport for ABAP - Transaction SCTS_HTA
Use transaction SCTS_HTA to add SAP HANA content to an ABAP Workbench request.
First select an SAP HANA content package to get a list of the objects inside this package.
Choose Include subpackages if you want to see the objects in subpackages too.
The list provides a status icon for each package and object. A yellow triangle indicates that an
object is new or has been changed since last synchronization. A green rectangle shows that
this SAP HANA object is in sync. This means that it either has been transported or is already
included in the transport request and has not changed since then.
Choose either complete packages or individual objects to be synchronized. As a result, the
selected SAP HANA content is added to your transport request.
© Copyright. All rights reserved.
317
Unit 6: Advanced Topics
Figure 233: HANA Transport for ABAP - Objects in Workbench Request
Animation: HANA Transport for ABAP - Objects in Workbench Request
For more information on HANA Transport for ABAP - Objects in Workbench
Request, please view the animation in the lesson Transporting SAP HANA
Objects with ABAP Transport Requests , online in the SAP Learning Hub.
In the transport request, three different types of objects can appear:
●
FULL PACKAGE (R3TR HOTA):
A complete package with all containing elements gets transported.
●
PACKAGE METADATA (LIMU HOTP):
A package gets transported but only with selected content or without any content at all.
●
SINGLE OBJECT (LIMU HOTO):
A single view or procedure gets transported.
Note:
It is not possible to transport a single object without the metadata of the
containing package. If you choose to transport a single object for which the
containing package has not yet been transported, the tool automatically adds the
package metadata to the transport request, as well.
318
© Copyright. All rights reserved.
Lesson: Transporting SAP HANA Objects with ABAP Transport Requests
Note:
The OBJECT NAME in the transport request is the package path plus object name
in SAP HANA content. If the package path exceeds a length of 40 characters, it
gets truncated. This can make it difficult to identify the objects in the transport
request. To avoid this, SAP recommends short package names and paths (shorter
than 40 characters).
Figure 235: HANA Transport for ABAP - Deployment of imported Objects to SAP HANA DB
Animation: HANA Transport for ABAP - Deployment of imported Objects to SAP
HANA DB
For more information on HANA Transport for ABAP - Deployment of imported
Objects to SAP HANA DB, please view the animation in the lesson Transporting
SAP HANA Objects with ABAP Transport Requests , online in the SAP Learning
Hub.
The following are the two options:
●
Option 1: Implicit deployment during import (default)
Prerequisite: Deployment mode of SAP HANA package is “A”
●
Option 2: Manual Deployment (TA SCTS_HTA_DEPLOY)
This may become necessary if the following are true:
-
-
Deployment mode of SAP HANA package is “P” (which means “requires prework
before deployment”).
Errors occurred during implicit deployment.
If an ABAP transport request contains HTA entries, the SAP HANA objects must be copied
from the application server to the database when the transport request is imported onto the
application server.
© Copyright. All rights reserved.
319
Unit 6: Advanced Topics
This is called deployment of the SAP HANA objects and it is done automatically as part of the
import of the transport request.
If this is not wanted (for example, because additional prework and checks are required on the
database), you can inhibit implicit deployment by setting the deployment mode of an SAP
HANA package to “P”.
Note:
You find the dialog for setting the deployment mode of a package in transaction
SCTS_HTA using the menu path Utilities → Set Deployment Mode.
For packages with deployment mode “P” and for the case of wrong or incomplete
deployments, you can use transaction SCTS_HTA_DEPLOY to execute or repeat a
deployment manually.
LESSON SUMMARY
You should now be able to:
320
●
Know the techniques for ABAP transport of SAP HANA objects
●
Understand SAP HANA Transport Container (HTC)
●
Use SAP HANA Transport for ABAP (HTA)
© Copyright. All rights reserved.
Unit 6
Lesson 2
Using SAP HANA Full Text Search
LESSON OVERVIEW
In this lesson, you learn the prerequisites for using full text search in SAP HANA, how to
configure a particular table column for full text search, and how to use the contains() and
score() functions in the SELECT statement to control the “Fuzzy” logic of full text search.
You also learn how you can enable automatic value proposals, called type-ahead, for input
fields on SAP GUI screens.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP applications
considerably by making use of SAP HANA. The ABAP system has been migrated to use SAP
HANA as its primary database. In particular, your company wants you to improve the usability
of searches in string-like database columns.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use SAP HANA full-text search
●
Enable proposal search and fulltext search in a dictionary search help
●
Describe SAP HANA linguistic search
Fuzzy Search: Motivation and Prerequisites
Searching for particular strings in the database is often difficult for any kind of search other
than simple key values. Different ways of writing names, non-standardized abbreviations, and
the mere distinction between upper and lowercase letters render precise searching with the
equals operator ineffective.
© Copyright. All rights reserved.
321
Unit 6: Advanced Topics
Figure 237: Fuzzy Search – Sometimes Equals Is Not Enough
The search with equals returns none of the listed table entries in the figure, Fuzzy Search –
Sometimes Equals is Not Enough. This is a frequent problem with names of people and
companies – many names have a significant number of spelling variants, especially if they
have been transcribed into Latin script from a different system. The names of companies
often contain their legal form. The company name SAP Deutschland AG & Co KG is
particularly difficult to find, as it is not clear if it is SAP Deutschland or SAP Germany.
Figure 238: Fuzzy Search – Sometimes LIKE Is Not Enough
322
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
The LIKE operator provides us with a partial solution to the problem. However, it can still lead
to unsatisfactory results because matching table entries have to contain the exact search
term enclosed in wildcards. If you do not have a meaningful and 100% correct snippet of a
word or phrase, the result set can either be full of irrelevant hits (the snippet is too small to be
properly selective) or empty (the snippet did not completely match any of the records at all).
In our example, you will see that we have increased our hit ratio from 0 to one third.
Given the increasing amounts of unstructured data that are now being stored in databases,
both as text and as binary content, we need an effective way to search that provides us with a
degree of error-tolerance. It must be possible to find information even if there are slight
misspellings or many different ways of spelling a particular name. We even require searches
that identify the words going and went as related. All of this is possible using SAP HANA full
text search, supporting the options fuzzy (error-tolerant) search or linguistic (languagespecific) search.
Figure 239: Fuzzy Search – An Error-Tolerant Search
A fuzzy search for the name Schwartz finds not only the precise match, but also further
reasonable matches. A reasonable match would be the name Schwartz, followed by other
words in the same field, but also variations on the name itself – perhaps without the letter t at
the end. To do this, SAP HANA uses an algorithm that calculates the closeness of the match
to the original search string and represents it as a score between 0 and 1, where 1 is a perfect
match. In the fuzzy search itself, you can specify the lower threshold, below which hits are no
longer displayed, or you can use the default setting of 0.8.
© Copyright. All rights reserved.
323
Unit 6: Advanced Topics
Figure 240: Prerequisites For Fuzzy Search
Animation: Prerequisites For Fuzzy Search
For more information on Prerequisites For Fuzzy Search, please view the
animation in the lesson Using SAP HANA Full Text Search, online in the SAP
Learning Hub.
To use to fuzzy search with good performance (and to use all other SAP HANA text search
features), full text indexes are required for the relevant table and columns.
To create a full-text index, the table in question must be column-stored. The most common
data type for which you will want to create such an index is NVARCHAR.
324
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
Creation of a Full-Text Index for Fuzzy Search
Figure 242: Creating the Index
The full-text index is a hidden column attached to the table that SAP HANA uses to perform
the search. SAP HANA can keep full-text indexes up to date either synchronously or
asynchronously. Asynchronous means that the index is only updated after a certain time
elapsed. Synchronous means that the index is updated immediately when inserting, updating,
or deleting a record, which also means that the insert, update, and delete statement
execution takes longer.
Hint:
Each full-text index that you create increases the footprint of the table in
memory. As an example, the database table SCUSTOM (around 4000 entries)
requires approximately 25% more memory when the NAME column (type C
length 25) is fully indexed.
The index update mode also affects the index creation. Activating a full text index
with synchronous update mode for a table containing many entries already may
take a while.
© Copyright. All rights reserved.
325
Unit 6: Advanced Topics
Figure 243: Creating the Index in an ABAP 7.4 System
The most common data type for which you will want to create a full text index is NVARCHAR
(CHAR, STRING or SSTRING in ABAP). In this case, you can create the full text index as
follows:
●
●
In an ABAP release 7.4 SP03 or higher using SAP HANA as its primary database, you can
create the full text index using the ABAP Dictionary. Create an index as usual. Then choose
menu item Goto → Full Text Index. Select Full Text Index. Choose Fuzzy Search on if you
create the index to enable fuzzy search.
When using SAP HANA as a secondary database, you cannot create a full-text index in the
ABAP Dictionary, but must create it in the SAP HANA studio or using native SQL. To use
the SAP HANA studio, open the table definition in the SAP HANA studio. On the Indexes
tab, create a new index of type Full-Text. In the pane below, you then select whether the
index should be updated synchronously or asynchronously. Select the column that you
want to index, and select the Fuzzy Search checkbox. You then need to deploy the index by
choosing Execute.
Once the index has been created in the database, you can use it to perform a fuzzy search in
the SELECT statement.
Fuzzy Search Usage
You implement a fuzzy search using the CONTAINS() function in the WHERE clause of your
SELECT statement.
326
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
Figure 244: The CONTAINS() Function
Animation: The CONTAINS() Function
For more information on The CONTAINS() Function, please view the animation in
the lesson Using SAP HANA Full Text Search, online in the SAP Learning Hub.
The arguments of the function are the name of the column in which you want to search, the
search string itself, and the search type FUZZY. The search type itself may also take an
argument – a decimal value between 0 and 1 denoting the minimum tolerance allowed.
FUZZY(1.0) would be an exact search. If you omit the argument, the default threshold of 0.8 is
used. The results are returned in the order in which they are found in the database, and not in
ranked order with the best match first.
Note:
The fuzzy search (and later the linguistic search) is only available in native SQL.
A further function that can be useful in the fuzzy search is SCORE().
© Copyright. All rights reserved.
327
Unit 6: Advanced Topics
Figure 246: The SCORE() Function
Animation: The SCORE() Function
For more information on The SCORE() Function, please view the animation in the
lesson Using SAP HANA Full Text Search, online in the SAP Learning Hub.
SCORE() is the ranking of each result in the result set. You can select the value into the result
set to display on the screen, or use it in the background in the ORDER BY clause to ensure that
the best hits appear at the top of the list.
328
© Copyright. All rights reserved.
Unit 6
Exercise 17
Implement a Fuzzy Search
Simulation: Implement a Fuzzy Search
For more information on Implement a Fuzzy Search, please view the simulation
in the lesson Using SAP HANA Full Text Search online in the SAP Learning Hub.
Business Example
You have an ABAP program that takes a fragment of a customer name as input and lists all
customers whose names contain this fragment. You want to improve the usability of the
program so that users do not have to spell the fragment fully correctly, by making use of SAP
HANA fuzzy search.
Template:
Report HA400_FUZZY_T1
Solution:
Report HA400_FUZZY_S1
Task 1: Copy and Analyze Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_FUZZY_T1 in your package ZHA400_## (suggested name ZHA400_##_FUZZY_1,
where ## is your group number).
1. Create a copy of report HA400_FUZZY_T1 and all its sub-objects. Place it in your package
ZHA400_## and assign it to your workbench task.
2. Activate the program and execute it using the default values. How many data records are
displayed?
3. Use the search string *Maier* to display records from table SCUSTOM using transaction
SE16. How does this entry differ from the search string in the program?
How could you change the SQL statement in your program to include the wildcard? Can
you use this technique to match a random combination of upper and lowercase letters?
© Copyright. All rights reserved.
329
Unit 6: Advanced Topics
Task 2: Check Prerequisites for Fuzzy Search
You want to implement a fuzzy search on table SCUSTOM. Analyze the table definition and
make sure the prerequisites are met.
1.
What kind of index must the table SCUSTOM have in order for you to
implement a fuzzy search?
Choose the correct answers.
X
A Extension index
X
B Full-text index
X
C Unique index
X
D Hashed index
To view the answer, please complete this question in the lesson Using SAP
HANA Full Text Search, online in the SAP Learning Hub.
2. Examine the indexes for table SCUSTOM defined for SAP HANA databases. Check which
column(s) it is defined on, and if it is a full-text index.
3. The index is called __________(1) and indexes the column SCUSTOM-__________(2). A fulltext index is switched ___________(3). The update mode for the index is set to
__________(4).
Task 3: Use a Fuzzy Search to Implement a User-Friendly Search
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, modify the native SQL statement so that it
implements a fuzzy search.
1. Find the definition of the native SQL SELECT statement. In the WHERE clause, remove the
selection with LIKE and replace it with a CONTAINS() function and the search type
FUZZY.
2. Activate the report with all its subobjects and test the program. Enter various search
terms and compare the result of the two subroutines.
330
© Copyright. All rights reserved.
Unit 6
Solution 17
Implement a Fuzzy Search
Simulation: Implement a Fuzzy Search
For more information on Implement a Fuzzy Search, please view the simulation
in the lesson Using SAP HANA Full Text Search online in the SAP Learning Hub.
Business Example
You have an ABAP program that takes a fragment of a customer name as input and lists all
customers whose names contain this fragment. You want to improve the usability of the
program so that users do not have to spell the fragment fully correctly, by making use of SAP
HANA fuzzy search.
Template:
Report HA400_FUZZY_T1
Solution:
Report HA400_FUZZY_S1
Task 1: Copy and Analyze Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_FUZZY_T1 in your package ZHA400_## (suggested name ZHA400_##_FUZZY_1,
where ## is your group number).
1. Create a copy of report HA400_FUZZY_T1 and all its sub-objects. Place it in your package
ZHA400_## and assign it to your workbench task.
a) Complete this step as you learned to do in previous classes.
2. Activate the program and execute it using the default values. How many data records are
displayed?
a) Complete this step as you learned before. No data is displayed.
3. Use the search string *Maier* to display records from table SCUSTOM using transaction
SE16. How does this entry differ from the search string in the program?
The first letter is in upper-case and there are two wildcard characters.
© Copyright. All rights reserved.
331
Unit 6: Advanced Topics
How could you change the SQL statement in your program to include the wildcard? Can
you use this technique to match a random combination of upper and lowercase letters?
For the wildcard, you can use LIKE '%Maier%'. However, this would not match a search
pattern containing all uppercase or all lowercase letters.
Task 2: Check Prerequisites for Fuzzy Search
You want to implement a fuzzy search on table SCUSTOM. Analyze the table definition and
make sure the prerequisites are met.
1.
What kind of index must the table SCUSTOM have in order for you to
implement a fuzzy search?
Choose the correct answers.
X
A Extension index
X
B Full-text index
X
C Unique index
X
D Hashed index
To view the answer, please complete this question in the lesson Using SAP
HANA Full Text Search, online in the SAP Learning Hub.
2. Examine the indexes for table SCUSTOM defined for SAP HANA databases. Check which
column(s) it is defined on, and if it is a full-text index.
a) Either in ABAP Workbench (Transaction SE80) or in ABAP Development Tools, open
the definition of the table in the ABAP Dictionary. When using the ABAP Development
Tools, you can use Open ABAP Development Object (Ctrl + Shift + A on your
keyboard), for example.
b) Choose Indexes.
c) Look at the list of indexes. Double-click the index with a name in the DB index name
column, respectively with value I in the Inclusion/Exclusion column.
The Display Index screen shows which columns and database systems it is created on.
d) Choose Goto → Full Text Index.
3. The index is called __________(1) and indexes the column SCUSTOM-__________(2). A fulltext index is switched ___________(3). The update mode for the index is set to
__________(4).
(1) FTN, (2) NAME, (3) on, (4) asynchronous
Task 3: Use a Fuzzy Search to Implement a User-Friendly Search
Edit your program. Copy the source code of subroutine get_data_template to subroutine
get_data_solution. In subroutine get_data_solution, modify the native SQL statement so that it
implements a fuzzy search.
332
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
1. Find the definition of the native SQL SELECT statement. In the WHERE clause, remove the
selection with LIKE and replace it with a CONTAINS() function and the search type
FUZZY.
a) See the source code extract from the model solution.
2. Activate the report with all its subobjects and test the program. Enter various search
terms and compare the result of the two subroutines.
a) Perform this step as before.
b) Verify that your code matches the following solution:
Source Code Extract from Model Solution (Program HA400_FUZZY_S1)
*&--------------------------------------------------------------------*
*&
Form get_data_template
*&--------------------------------------------------------------------*
FORM get_data_template USING pv_name TYPE scustom-name
CHANGING ct_customers TYPE ty_t_customers.
* ADBC Objects and Variables
DATA: lo_con
TYPE REF TO cl_sql_connection,
lo_sql
TYPE REF TO cl_sql_statement,
lo_result TYPE REF TO cl_sql_result_set,
lv_sql
TYPE string,
lr_data
TYPE REF TO data.
* Exception Handling
DATA:
lx_sql_exc TYPE REF TO cx_sql_exception.
TRY.
CREATE OBJECT lo_sql.
lv_sql = |SELECT ID, NAME, POSTCODE, CITY, COUNTRY | &&
|FROM SCUSTOM | &&
|WHERE MANDT = { sy-mandt } | &&
|AND NAME LIKE '%{ pv_name }%' |.
lo_result = lo_sql->execute_query( lv_sql ).
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
lo_result->next_package( ).
lo_result->close( ).
CATCH cx_sql_exception INTO lx_sql_exc.
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
"
*&--------------------------------------------------------------------*
*&
Form get_data_solution
*&--------------------------------------------------------------------*
FORM get_data_solution USING pv_name TYPE scustom-name
CHANGING ct_customers TYPE ty_t_customers.
* ADBC Objects and Variables
DATA: lo_con
TYPE REF TO cl_sql_connection,
© Copyright. All rights reserved.
333
Unit 6: Advanced Topics
lo_sql
lo_result
lv_sql
lr_data
TYPE REF TO cl_sql_statement,
TYPE REF TO cl_sql_result_set,
TYPE string,
TYPE REF TO data.
* Exception Handling
DATA:
lx_sql_exc TYPE REF TO cx_sql_exception.
TRY.
CREATE OBJECT lo_sql.
lv_sql = |SELECT ID, NAME, POSTCODE, CITY, COUNTRY | &&
|FROM SCUSTOM | &&
|WHERE MANDT = { sy-mandt } | &&
|AND CONTAINS("NAME", '{ pv_name }' , FUZZY) |.
lo_result = lo_sql->execute_query( lv_sql ).
GET REFERENCE OF ct_customers INTO lr_data.
lo_result->set_param_table( lr_data ).
lo_result->next_package( ).
lo_result->close( ).
CATCH cx_sql_exception INTO lx_sql_exc.
MESSAGE lx_sql_exc TYPE 'E'.
ENDTRY.
ENDFORM.
334
"
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
Proposal Search and Fulltext Search
Figure 249: Search Helps with Proposal Search and Fulltext Search
Starting with ABAP 7.4 SP03, ABAP Dictionary search helps can be enhanced to support
proposal search. If this is enabled for an input field on a screen, the system automatically
proposes matching values when an end user starts entering a few characters. You can easily
identify input fields with proposal search: the system displays a magnifying glass in them.
Note:
If the cursor is already placed in the input field, the usual value help button may
shadow the magnifying glass.
Proposal search is available on all database systems supported by ABAP. However, it
provides most value if combined with a (fuzzy) fulltext search. Fulltext search is currently only
supported on SAP HANA databases.
A prerequisite for enabling proposal search is a system based on ABAP 7.4 SP05 or higher
and SAP GUI 7.30 Patch Level 05 or higher. In addition, no PROCESS ON VALUE-HELP event
must exists that overrides the search help attached to the field.
A prerequisite for enabling fulltext search is a SAP HANA database and an elementary search
help based on a column-store table or a CDS view.
© Copyright. All rights reserved.
335
Unit 6: Advanced Topics
Figure 250: EnablingTypeAheadWithFuzzySearchforSAPGUI_Image.ppt
To enable proposal search for an input field on a screen, first identify the ABAP Dictionary
search help attached to the field. To do so, you can use the field help, navigate to the
Technical Information and on to the Dictionary. If you find a collective search help attached,
navigate to the first suitable elementary search help contained in the collective search help.
Adjust the elementary search help, as follows:
●
●
●
Switch on Proposal Search for Input Fields to enable proposal search. This works on all
database systems, and leads to proposals based on the existing values of the field itself
and an exact search using a LIKE query with wildcards.
Switch on Multi-Column Fulltext Search (Database-Specific) to make value proposals
based on a fuzzy search.
Adjust the Accuracy Value for Error-Tolerant Full Text Search if necessary.
Note:
In ABAP systems before 7.4 SP06, you have to enable proposal search explicitly in
the screen. This is done by calling method
cl_dsh_dynpro_properties=>enable_type_ahead(...) in a PBO module
of the screen, or by adding attribute typeahead with value X directly to the
custom properties of the input field.
336
© Copyright. All rights reserved.
Unit 6
Exercise 18
Implement a Value Help with Fuzzy Search
Simulation: Implement a Value Help with Fuzzy Search
For more information on Implement a Value Help with Fuzzy Search, please view
the simulation in the lesson Using SAP HANA Full Text Search online in the SAP
Learning Hub.
Business Example
You have a report which takes a customer ID as input and lists how many flights the given
customer booked for each carrier. You want to improve the usability of the report by enabling
a type-ahead value help for the customer ID input field.
Template Objects:
Search Help: HA400_CUST_T1
Structure: HA400_S_CUST_T1
Report: HA400_FUZZY_T2
Solution Objects:
Search Help: HA400_CUST_S1
Structure: HA400_s_CUST_S1
Report: HA400_FUZZY_S2
Task 1: Copy and Analyze the Template Program
In system T8N, which uses SAP HANA as its primary database, create a copy of template
report HA400_FUZZY_T2 (suggested name: ZHA400_##_FUZZY_2). Activate and test your
copy. Analyze the coding and find the object that defines the value help on the selection
screen.
1. Create a copy of report HA400_FUZZY_T2. Place it in your package ZHA400_## and
assign it to your workbench task.
2. Activate and test your copy.
Is there a value help (often referred to as F4 help) for the input field?
3. Analyze your copy. Where does the value help come from?
© Copyright. All rights reserved.
337
Unit 6: Advanced Topics
The input help comes from search help ___________(1) that is assigned to component
___________(2) of structure ___________(3).
Task 2: Copy Search Help and Structure and Use the Copies in Your Program
Copy the search help and the structure. Use these copies in your program so that the value
help for the input field is defined by your own search help.
1. Create a copy of search help HA400_CUST_T1 (suggested name: ZHA400_##_CUST),
place it in your package ZHA400_## and assign it to your workbench task.
2. Activate the search help.
3. Create a copy of structure HA400_S_CUST_T1 (suggested name: ZHA400_S_##_CUST),
place it in your package ZHA400_## and assign it to your workbench task.
4. Open your copy of structure HA400_S_CUST_T1. Instead of search help
HA400_CUST_S1, assign your own search help to component ID.
5. Activate the structure.
6. Edit your program. In the definition of the input field, replace structure
HA400_S_CUST_T1 with your own structure. As a result the value help for the input field is
now defined by your own search help.
Task 3: Adjust the Search Help to Make it Support Proposal Search and Fuzzy Search
Adjust the definition of your search help to make it support proposal search and fuzzy search.
Activate it and check the result by executing your program again.
1. Adjust the definition of your search help ZHA400_##_CUST to make it support proposal
search.
2. Execute your program and check the impact on the value help.
3. Adjust the definition of your search help ZHA400_##_CUST again, this time to make it
support fuzzy search.
4. Execute your program once more and check the impact on the value help.
338
© Copyright. All rights reserved.
Unit 6
Solution 18
Implement a Value Help with Fuzzy Search
Simulation: Implement a Value Help with Fuzzy Search
For more information on Implement a Value Help with Fuzzy Search, please view
the simulation in the lesson Using SAP HANA Full Text Search online in the SAP
Learning Hub.
Business Example
You have a report which takes a customer ID as input and lists how many flights the given
customer booked for each carrier. You want to improve the usability of the report by enabling
a type-ahead value help for the customer ID input field.
Template Objects:
Search Help: HA400_CUST_T1
Structure: HA400_S_CUST_T1
Report: HA400_FUZZY_T2
Solution Objects:
Search Help: HA400_CUST_S1
Structure: HA400_s_CUST_S1
Report: HA400_FUZZY_S2
Task 1: Copy and Analyze the Template Program
In system T8N, which uses SAP HANA as its primary database, create a copy of template
report HA400_FUZZY_T2 (suggested name: ZHA400_##_FUZZY_2). Activate and test your
copy. Analyze the coding and find the object that defines the value help on the selection
screen.
1. Create a copy of report HA400_FUZZY_T2. Place it in your package ZHA400_## and
assign it to your workbench task.
a) Complete this step as before.
2. Activate and test your copy.
a) Perform this step as you learned to do in previous classes.
Is there a value help (often referred to as F4 help) for the input field?
Yes
3. Analyze your copy. Where does the value help come from?
a) Look for the definition of the parameter (statement PARAMETERS).
© Copyright. All rights reserved.
339
Unit 6: Advanced Topics
b) Navigate to the data-type (HA400_S_CUST_T1–ID).
c) In the definition of structure HA400_S_CUST_T1, look for the search help assigned to
component ID.
The input help comes from search help ___________(1) that is assigned to component
___________(2) of structure ___________(3).
(1) HA400_CUST_T1, (2) ID, (3) HA400_S_CUST_T1.
Task 2: Copy Search Help and Structure and Use the Copies in Your Program
Copy the search help and the structure. Use these copies in your program so that the value
help for the input field is defined by your own search help.
1. Create a copy of search help HA400_CUST_T1 (suggested name: ZHA400_##_CUST),
place it in your package ZHA400_## and assign it to your workbench task.
a) Perform this step as you learned to do in previous classes.
2. Activate the search help.
a) Perform this step as you learned to do in previous classes.
3. Create a copy of structure HA400_S_CUST_T1 (suggested name: ZHA400_S_##_CUST),
place it in your package ZHA400_## and assign it to your workbench task.
a) Perform this step as you learned to do in previous classes.
4. Open your copy of structure HA400_S_CUST_T1. Instead of search help
HA400_CUST_S1, assign your own search help to component ID.
a) Perform this step as you learned to do in previous classes.
5. Activate the structure.
a) Perform this step as you learned to do in previous classes.
6. Edit your program. In the definition of the input field, replace structure
HA400_S_CUST_T1 with your own structure. As a result the value help for the input field is
now defined by your own search help.
a) PARAMETERS pa_cus TYPE ZHA400_S_##_CUST-ID.
Task 3: Adjust the Search Help to Make it Support Proposal Search and Fuzzy Search
Adjust the definition of your search help to make it support proposal search and fuzzy search.
Activate it and check the result by executing your program again.
1. Adjust the definition of your search help ZHA400_##_CUST to make it support proposal
search.
a) Open the search help and switch to change mode.
b) In the Enhanced Options frame, select the Proposal Search for Input Fields indicator.
c) Activate the search help.
2. Execute your program and check the impact on the value help.
a) Execute your program.
b) Place the cursor inside the input field and start typing a customer name.
340
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
3. Adjust the definition of your search help ZHA400_##_CUST again, this time to make it
support fuzzy search.
a) Open the search help and switch to change mode.
b) In the Enhanced Options frame, select the Multi-Column Fulltext Seach (DatabaseSpecific) indicator.
c) Activate the search help.
4. Execute your program once more and check the impact on the value help.
a) Execute your program.
b) Place the cursor inside the input field and start typing a customer name.
© Copyright. All rights reserved.
341
Unit 6: Advanced Topics
Linguistic Search
Figure 252: Linguistic Search
While the fuzzy search is very useful for entities such as names, it is sometimes more useful
to perform a linguistic search, for example, when you want a string such as go to be
considered more closely related to going or even went (linguistic variants) than to goat. For
this case, you can index a column according to linguistic criteria. Words are then separated
and reduced to their stems, or basic forms.
Creation of Full-Text Index for Linguistic Search
In an ABAP 7.4 system using SAP HANA as its primary database, you can create a full text
index for linguistic search as explained before, and set TextAnalysis to on in the index
definition.
In all other cases, you have to create the full text index using SAP HANA studio or native SQL.
When indexing a record for linguistic search, you must specify the language of the record
(unless everything should be interpreted as in English). The definition of the index therefore
contains a reference column containing a 2-character ISO language key.
Caution:
When creating a full text index for linguistic search in the SAP HANA studio or
using native SQL, you cannot refer to the single-character SAP language codes.
To convert a single-character SAP language code into the corresponding 2character ISO code, you can use the function module
CONVERT_SAP_LANG_TO_ISO_LANG.
342
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
Figure 253: Configuring the Linguistic Search
When creating the full-text index for linguistic search, you must also specify the level of
linguistic analysis. This ranges from the separation of the string into its individual words,
through stemming, which is the process of reducing a word such as going or went to its stem
go, to a full linguistic analysis in which the individual parts of speech are tagged. For these
analyses to work properly, Fast Preprocessing must be switched off in the index definition.
Fast preprocessing is switched on by default when creating a full text index using the SAP
HANA studio.
Figure 254: Text Analysis Options
© Copyright. All rights reserved.
343
Unit 6: Advanced Topics
Linguistic Search Usage
Figure 255: Using the Linguistic Search
Animation: Using the Linguistic Search
For more information on Using the Linguistic Search, please view the animation
in the lesson Using SAP HANA Full Text Search, online in the SAP Learning Hub.
Like the fuzzy search, the linguistic search is only available in native SQL. To use the linguistic
analysis in the SELECT statement, you again use the CONTAINS() function, but this time with
the search type LINGUISTIC. Following the search type, you should use the LANGUAGE
argument to specify the language – once again as a two-character code. If you fail to do so, or
specify an invalid language-code, the search will be performed according to the linguistic
properties of English.
344
© Copyright. All rights reserved.
Lesson: Using SAP HANA Full Text Search
LESSON SUMMARY
You should now be able to:
●
Use SAP HANA full-text search
●
Enable proposal search and fulltext search in a dictionary search help
●
Describe SAP HANA linguistic search
© Copyright. All rights reserved.
345
Unit 6
Lesson 3
ABAP List Viewer with Integrated Database
Access (ALV IDA)
LESSON OVERVIEW
In this lesson, you learn the benefits of SAP List Viewer with Integrated Data Access (ALV with
IDA), which is optimized for SAP HANA, and to describe the differences between ALV with IDA
and classical ALV. You also learn to display data in ALV with IDA, use select options in the data
retrieval of ALV with IDA, and supply values for input parameters of the external view.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Understand the vasics of SAP List Viewer with Integrated Data Access (ALV with IDA)
●
Describe the differences between ALV with IDA and classical ALV
●
Display data with ALV with IDA
●
Use select options in the data retrieval of ALV with IDA
●
Supply values for input parameters of views
SAP ABAP List Viewer (ALV) with Integrated Data Access
We already know that in-memory databases like SAP HANA can lead to significant
performance improvements when processing large quantities of data. Users should benefit
from the required data being displayed more quickly, and the ability to manipulate their view
of that data in different ways.
Sometimes you have user interfaces producing larger lists of objects, for example a UI listing
all open invoices. Generating such lists can be time-consuming, especially if they include
calculated columns, and end users may also need patience when working interactively with
the lists to group or sort entries or include aggregates.
This leads to the question: how can the user experience be improved?
In order to make this possible, SAP has designed a special version of the ALV, the SAP List
Viewer with Integrated Data Access (ALV with IDA). This variation of the ALV is optimized for
use with SAP HANA.
Basic Principles and Advantages
What is SAP List Viewer with Integrated Data Access (ALV with IDA)?
346
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
●
●
Basic principles:
-
Only retrieve, from the database, data which is to be displayed on the screen
-
Use database services where possible – ALV features pushed down to the database
-
Data described declaratively instead of passing big internal tables
Advantages:
-
Retrieval of results is much faster
-
Better performance and reduced memory consumption
-
Improved user experience
How ALV Works
Figure 257: ALV Optimized for SAP HANA
The SAP List Viewer with Integrated Data Access (ALV with IDA) offers ABAP developers the
option to take advantage of SAP HANA, without having to present the user with a new or
different interface. Using the ALV with IDA, it is possible to display huge amounts of data, with
the expected sorting and grouping functions that users are familiar with, but without big
performance issues. Other functions that have been used in the ALV for a long time, such as
the ability to aggregate data, are still available in the ALV with IDA. From the perspective of
the user, the familiar ALV functions are therefore enhanced by the advantages of using SAP
HANA.
The ALV with IDA is based on the following principles:
●
Only select the data in the database that is supposed to be displayed. That is, apply data
filtering, even paging, in the database, so that only a small data set is returned to the ABAP
stack and passed through, more or less unchanged, to the UI.
© Copyright. All rights reserved.
347
Unit 6: Advanced Topics
●
In addition, all calculations such as aggregating and grouping data, or adding columns
whose values are computed from the other columns, should be performed in the database.
The latter can be achieved by using CDS-based views.
The figure, Classical ALV, illustrates how these principles are quite different from how
classical ALV works.
In order to ensure that only the data to be displayed is retrieved from the database, it is
necessary to specify the constraints or conditions that should be used to restrict the data
before it is selected. This is made possible by using dedicated methods that allow you to
declare these constraints in the form of parameters, for example, classical ABAP ranges.
However, more complex conditions can also be expressed.
As a result, the data is retrieved much faster on SAP HANA, and you also need far less
memory on the ABAP stack.
Figure 258: Classical ALV How Does it Work
Animation: Classical ALV How Does it Work
For more information on Classical ALV How Does it Work, please view the
animation in the lesson ABAP List Viewer with Integrated Database Access (ALV
IDA), online in the SAP Learning Hub.
The figure, Classical ALV, shows the approach to displaying data using the classical ALV. The
steps shown provide an example of what the ABAP application would typically do, as follows:
1. The application performs authorization checks and extracts relevant data from the
database into an internal table.
2. Business data, such as calculated fields, can then be added to the internal table contents.
3. UI information (icons, links, and so on) may also be added.
348
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
4. The internal table is passed to the ALV services, which then manipulate the data according
to user requirements.
5. The required data is displayed on the screen.
End User Perspective
Figure 260: ALV for HANA End User Perspective
The ALV with IDA will look and feel familiar to end users who have worked with the classical
ALV, but there are some small differences in functionality and behavior.
© Copyright. All rights reserved.
349
Unit 6: Advanced Topics
Figure 261: Feature Availability in ALV with IDA
Figure 262: Feature Availability in ALV for SAP HANA II
350
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
Technical Differences Between ALV with IDA and Classical ALV
Figure 263: Classical ALV Problems
For an end user, working with large amounts of data in a classical ALV can be cumbersome
and time-consuming. The issue is that it is optimized for the old paradigm and constraints,
where the database is considered the bottleneck. Behind the scenes, the classical ALV
requires all data to be first loaded into an internal table in order to display it, and typically this
is larger than what is actually displayed to the user in the end. This initial load can lead to very
long waiting times for the end user, or even short dumps due to memory consumption. Due to
these issues, the user may restrict the amount of data beforehand, leading to incomplete data
sets.
Once the data is loaded, all processing takes place in the ABAP stack on the internal table, for
example, sorting the data set, filtering the data set, grouping, aggregating, or adding
calculated columns. Even paging through the result set happens in the ABAP stack. All of
these processing steps can take a long time, and again consume a large amount of memory
when dealing with large amounts of data.
Clearly, the way in which the classical ALV works contradicts how you can benefit most from
SAP HANA, namely by performing the data-intensive calculation close to the data, in the
database. This is the reason for the new variant of the SAP List Viewer.
© Copyright. All rights reserved.
351
Unit 6: Advanced Topics
Figure 264: The New Approach ALV Optimized for HANA
Animation: The New Approach ALV Optimized for HANA
For more information on The New Approach ALV Optimized for HANA, please
view the animation in the lesson ABAP List Viewer with Integrated Database
Access (ALV IDA), online in the SAP Learning Hub.
The ALV with IDA, optimized for HANA, is significantly different to the classical ALV.
Authority checks, table functions, and other processes that were previously carried out by the
application are now performed by the database. The application only has to pass the details to
the new ALV API (IDA – Integrated Data Access); for example, a WHERE clause can be sent to
the database by calling relevant methods.
Additional UI information is still handled by the application.
The amount of data is severely restricted by the database before it is displayed on the UI, and
there is no longer a need to store the displayed data inside an internal table.
Package SALV_IDA_TEST contains sample programs using the ALV with IDA.
352
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
Instantiation of ALV with IDA
Figure 266: Coding Example Instantiation of ALV Optimized for HANA
The example in the figure, Coding Example: Instantiation of ALV with IDA, shows how you can
instantiate ALV IDA. Two different factory methods exist, depending on the data source the
ALV instance should read data from. Use method CREATE for database tables, database
views and external views. Use method CREATE_FOR_CDS_VIEW to specify a CDS view.
Note that, rather than passing an internal table containing the data to be displayed, only the
name of the database table (or external view/CDS view) needs to be supplied via the import
parameter.
© Copyright. All rights reserved.
353
Unit 6: Advanced Topics
Display of ALV with IDA
Figure 267: Display of ALV with IDA
There are two different ways to invoke the display of ALV with IDA.
You can use import parameter IO_GUI_CONTAINER of the CREATE-methods to link the ALV
with IDA instance to a container control. In that case, you have to create an instance of the
container control class BEFORE you instantiate the ALV with IDA class. To invoke the display,
you have to call the DISPLAY method of the ALV with IDA instance once.
ALV with IDA also offers a stand-alone display. In this case you don't have to instantiate a
container control. Simply call method FULLSCREEN( ) of your ALV with IDA instance and
method DISPLAY of the instance this method returns.
Select Options
For large amounts of data, it is important that a user has the option to restrict the amount of
data that is displayed using a selection screen.
The data retrieval (using selection options) and display are done by ALV with IDA. The
selection made by the user is transferred to the list using method set_select_options. Use
method add_ranges_for_name of class CL_SALV_RANGE_TAB_COLLECTOR to convert the
selection of the user to the format that is needed for the method set_select_options.
354
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
Figure 268: Select Options
Views with Input Parameters
ALV with IDA can work with CDS views that have input parameters. In order for the ABAP
application to supply values for these input parameters, they must be passed to the ALV as
name-value pairs by calling the method SET_VIEW_PARAMETERS.
Figure 269: ALV Using External View with Parameters
© Copyright. All rights reserved.
355
Unit 6: Advanced Topics
Using Fuzzy Search
You may want to provide a selection screen in the ABAP application that provides the user
with the ability to enter a search term for which they wish to perform a fuzzy search. The ALV
API provides methods to do this, as shown in the figure, Fuzzy Search Functionality in ALV
with IDA.
Figure 270: Fuzzy Search Functionality in ALV with IDA
This type of search was not possible with the classical ALV.
356
© Copyright. All rights reserved.
Unit 6
Exercise 19
Use ALV with Integrated Data Access for a
CDS View
Simulation: Use ALV with Integrated Data Access for a CDS View
For more information on Use ALV with Integrated Data Access for a CDS View,
please view the simulation in the lesson ABAP List Viewer with Integrated
Database Access (ALV IDA) online in the SAP Learning Hub.
Business Example
You are asked to develop a report listing, for a range of customers to be specified on the
selection screen, how many days on average each customer books flights in advance. You
have a program that retrieves this information based on a CDS view. Now you want to
improve the user experience by making use of the SAP List Viewer with Integrated Data
Access (ALV with IDA).
Template:
Report HA400_ALV_IDA_T1
Solution:
Report HA400_ALV_IDA_S1
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of program
HA400_ALV_IDA_T1 in your package ZHA400_## (suggested name: ZHA400_##_ALV,
where ## is your group number). Activate the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the source code of subroutine display_alv_classic.
Where is the data retrieved and where does it come from?
© Copyright. All rights reserved.
357
Unit 6: Advanced Topics
Which ABAP data objects are used in the SELECT statements and for what purpose?
3. Activate the program and test it with default settings.
Task 2: Use the ALV with IDA to Display the Data
Edit your program. Implement the display_alv_ida subroutine so that the data from CDS view
HA400_CDS_S3 is displayed in the new ALV with integrated data access. Make sure you
provide an actual value for the import parameter and to restrict the data to be displayed
based on the user input.
1. In the display_alv_ida subroutine, declare a reference variable of type ref to
IF_SALV_GUI_TABLE_IDA and use it to receive the object from the factory method
CREATE_FOR_CDS_VIEW of class CL_SALV_GUI_TABLE_IDA, which creates and returns
an instance of the ALV with IDA class. Supply the name of the CDS view (HA400_CDS_S3)
for parameter IV_TABLE_NAME.
2. Call method SET_VIEW_PARAMETERS for the ALV instance, to provide the current date
for parameter P_UPTO_DATE of the view. To do this, populate an internal table of type
if_salv_gui_types_ida=>yt_parameter with an appropriate entry and then pass this
internal table to the method.
3. Make the select options in data objects pt_range_id and pt_rang_name known to the ALV
with IDA instance. In a first step, declare a reference variable of type ref to
CL_SALV_RANGE_TAB_COLLECTOR, and then create an instance of this class.
4. Call the method ADD_RANGES_FOR_NAME for the above object, once for each selectoption on the selection screen. Assign the respective range table to parameter
IT_RANGES, and the field name to parameter IV_NAME.
5. Call method GET_COLLECTED_RANGES which exports an internal table of type
if_salv_service_types=>yt_named_ranges that contains a combination of the various
select-options.
6. Call method SET_SELECT_OPTIONS for the ALV with IDA instance to pass the internal
table from the previous step to parameter IT_RANGES.
7. Call functional method FULLSCREEN for the ALV with IDA instance, which returns a
reference of type IF_SALV_GUI_FULLSCREEN_IDA. For this new object, call method
DISPLAY.
8. Activate and test your program.
358
© Copyright. All rights reserved.
Unit 6
Solution 19
Use ALV with Integrated Data Access for a
CDS View
Simulation: Use ALV with Integrated Data Access for a CDS View
For more information on Use ALV with Integrated Data Access for a CDS View,
please view the simulation in the lesson ABAP List Viewer with Integrated
Database Access (ALV IDA) online in the SAP Learning Hub.
Business Example
You are asked to develop a report listing, for a range of customers to be specified on the
selection screen, how many days on average each customer books flights in advance. You
have a program that retrieves this information based on a CDS view. Now you want to
improve the user experience by making use of the SAP List Viewer with Integrated Data
Access (ALV with IDA).
Template:
Report HA400_ALV_IDA_T1
Solution:
Report HA400_ALV_IDA_S1
Task 1: Copy and Understand Templates
In system T8N, which uses SAP HANA as its primary database, create a copy of program
HA400_ALV_IDA_T1 in your package ZHA400_## (suggested name: ZHA400_##_ALV,
where ## is your group number). Activate the program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned before.
2. Analyze the source code of subroutine display_alv_classic.
a) Open the source code in the editor.
Where is the data retrieved and where does it come from?
The data is retrieved in a SELECT statement from CDS view HA400_CDS_S3.
© Copyright. All rights reserved.
359
Unit 6: Advanced Topics
Which ABAP data objects are used in the SELECT statements and for what purpose?
Internal table lt_customers is used as target for the read data. Range tables pt_range_id
and pt_range_name are used as selction criteria in the WHERE clause. System field sydatum is used as actual parameter for the CDS view’s input parameter p_upto_date.
3. Activate the program and test it with default settings.
a) Complete this step as before.
Task 2: Use the ALV with IDA to Display the Data
Edit your program. Implement the display_alv_ida subroutine so that the data from CDS view
HA400_CDS_S3 is displayed in the new ALV with integrated data access. Make sure you
provide an actual value for the import parameter and to restrict the data to be displayed
based on the user input.
1. In the display_alv_ida subroutine, declare a reference variable of type ref to
IF_SALV_GUI_TABLE_IDA and use it to receive the object from the factory method
CREATE_FOR_CDS_VIEW of class CL_SALV_GUI_TABLE_IDA, which creates and returns
an instance of the ALV with IDA class. Supply the name of the CDS view (HA400_CDS_S3)
for parameter IV_TABLE_NAME.
a) See source code extract from model solution.
2. Call method SET_VIEW_PARAMETERS for the ALV instance, to provide the current date
for parameter P_UPTO_DATE of the view. To do this, populate an internal table of type
if_salv_gui_types_ida=>yt_parameter with an appropriate entry and then pass this
internal table to the method.
a) See source code extract from model solution.
3. Make the select options in data objects pt_range_id and pt_rang_name known to the ALV
with IDA instance. In a first step, declare a reference variable of type ref to
CL_SALV_RANGE_TAB_COLLECTOR, and then create an instance of this class.
a) See source code extract from model solution.
4. Call the method ADD_RANGES_FOR_NAME for the above object, once for each selectoption on the selection screen. Assign the respective range table to parameter
IT_RANGES, and the field name to parameter IV_NAME.
a) See source code extract from model solution.
5. Call method GET_COLLECTED_RANGES which exports an internal table of type
if_salv_service_types=>yt_named_ranges that contains a combination of the various
select-options.
a) See source code extract from model solution.
6. Call method SET_SELECT_OPTIONS for the ALV with IDA instance to pass the internal
table from the previous step to parameter IT_RANGES.
a) See source code extract from model solution.
7. Call functional method FULLSCREEN for the ALV with IDA instance, which returns a
reference of type IF_SALV_GUI_FULLSCREEN_IDA. For this new object, call method
DISPLAY.
a) See source code extract from model solution.
8. Activate and test your program.
360
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
a) Perform this step as before.
b) Verify that your code matches the following solution:
Source code extract from model solution (Program HA400_ALV_IDA_S1)
*&-------------------------------------------------------------------*
*&
Form display_alv_ida
*&-------------------------------------------------------------------*
FORM display_alv_ida USING pt_range_id
LIKE so_id[]
pt_range_name LIKE so_name[].
* control specific:
DATA: lo_salv TYPE REF TO if_salv_gui_table_ida.
DATA:
lo_range_collector TYPE REF TO cl_salv_range_tab_collector,
lt_named_ranges
TYPE if_salv_service_types=>yt_named_ranges.
DATA: lo_fcat TYPE REF TO if_salv_gui_field_catalog_ida,
lo_exc TYPE REF TO cx_salv_ida_contract_violation.
DATA: lt_params TYPE if_salv_gui_types_ida=>yt_parameter,
ls_param LIKE LINE OF lt_params.
* Create ALV Instance
*---------------------*
lo_salv = cl_salv_gui_table_ida=>create_for_cds_view(
iv_cds_view_name = 'HA400_CDS_S3'
).
* Set Input Parameter
*---------------------*
ls_param-name = 'P_UPTO_DATE'.
ls_param-value = sy-datum.
APPEND ls_param TO lt_params.
lo_salv->set_view_parameters( lt_params ).
* Alternative: Based on expression VALUE (> AS ABAP 7.40)
*lo_salv->set_view_parameters( value #(
*
( name = 'P_UPTO_DATE'
*
value = sy-datum
*
)
*
)
*
).
* Transform Ranges to one Range Table
*-------------------------------------*
CREATE OBJECT lo_range_collector.
lo_range_collector->add_ranges_for_name(
iv_name
= 'ID'
it_ranges = pt_range_id ).
lo_range_collector->add_ranges_for_name(
iv_name
= 'NAME'
it_ranges = pt_range_name ).
lo_range_collector->get_collected_ranges(
IMPORTING
© Copyright. All rights reserved.
361
Unit 6: Advanced Topics
et_named_ranges = lt_named_ranges ).
* Set Select Options
*--------------------*
lo_salv->set_select_options( it_ranges = lt_named_ranges ).
* Invoke fullscreen display
*---------------------------*
lo_salv->fullscreen( )->display( ).
ENDFORM.
362
"display_solution
© Copyright. All rights reserved.
Lesson: ABAP List Viewer with Integrated Database Access (ALV IDA)
LESSON SUMMARY
You should now be able to:
●
Understand the vasics of SAP List Viewer with Integrated Data Access (ALV with IDA)
●
Describe the differences between ALV with IDA and classical ALV
●
Display data with ALV with IDA
●
Use select options in the data retrieval of ALV with IDA
●
Supply values for input parameters of views
© Copyright. All rights reserved.
363
Unit 6: Advanced Topics
364
© Copyright. All rights reserved.
Unit 6
Learning Assessment
1. To include SAP HANA content into an ABAP transport request, SAP recommends using an
SAP HANA Transport Container (HTC) instead of the SAP HANA Transport for ABAP
(HTA) technique.
Determine whether this statement is true or false.
X
True
X
False
2. You want to perform an SAP HANA full-text search on column COL of database table TAB.
Which of the following conditions have to be fulfilled?
Choose the correct answers.
X
A Table TAB is located in column store.
X
B Column COL is of type TEXT or SHORTTEXT.
X
C A full text index exists for column COL of table TAB.
X
D The application server release is 7.40 SP05 or higher.
3. Proposal search (= type ahead search) is supported on all database systems.
Determine whether this statement is true or false.
X
True
X
False
4. ABAP List Viewer with Integrated Data Access (ALV with IDA) is only supported for SAP
HANA database.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
365
Unit 6: Learning Assessment
5. Which of the following ABAP repository objects can be the data source for ALV with IDA?
Choose the correct answers.
X
A Transparent table
X
B Database view
X
C CDS view
X
D External view
6. Which of the following features are NOT supported by ALV with IDA?
Choose the correct answer.
366
X
A Personalization
X
B Editing values
X
C Excel export
X
D Double-click
© Copyright. All rights reserved.
UNIT 7
Case Study: Optimize a Report
on Flight Customer Revenue
Lesson 1
Optimizing a Report with CDS View and ALV IDA
Exercise 20: Case Study Part 1: Code Push Down with ABAP Core Data Services
Exercise 21: Case Study Part 2: Use ALV Optimized for SAP HANA
368
369
377
UNIT OBJECTIVES
●
Optimizing a report with CDS view and ALV with IDA
© Copyright. All rights reserved.
367
Unit 7
Lesson 1
Optimizing a Report with CDS View and ALV
IDA
LESSON OVERVIEW
In this lesson, you learn how to optimize a classical report for SAP HANA.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
368
Optimizing a report with CDS view and ALV with IDA
© Copyright. All rights reserved.
Unit 7
Exercise 20
Case Study Part 1: Code Push Down with ABAP
Core Data Services
Simulation: Case Study Part 1: Code Push Down with ABAP Core Data Services
For more information on Case Study Part 1: Code Push Down with ABAP Core
Data Services, please view the simulation in the lesson Optimizing a Report with
CDS View and ALV IDA online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program that determines, for a set of customers to be
entered, the total amount (in your local currency) each customer spends for flights. As a first
step, you want to push the currency conversion into the database, making use of an ABAP
CDS view yet to be developed.
Template:
Report HA400_CASE_STUDY_T1
Solution:
DDL Source HA400_BOOKING_W_CONV_AMOUNT
Report HA400_CASE_STUDY_S1
Task 1: Copy and Analyze Template
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_CASE_STUDY_T1 in your package ZHA400_## (suggested name:
ZHA400_##_CSTUDY_1, where ## is your group number). Activate, analyze, and execute the
program.
Hint:
Remember that there is no SAP GUI editor for repository object DDL source. You
have to develop at least your CDS view in ABAP Development Tools (ADT). The
rest of the exercise you can still do in the classical ABAP Workbench. But you
might want to take the opportunity and perform this complete exercise in
Eclipse.
1. Create a copy of the report and all its subobjects. Place it in your package ZHA400_##
and assign it to your workbench task.
© Copyright. All rights reserved.
369
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
Hint:
To copy the report using the ABAP Development Tools, use the contextual
menu item Duplicate.
2. Analyze the source code of subroutine get_data.
3. Which database tables occur in the FROM clause of the select statement? Which data are
read from them?
4. What is calculated in the loop over the customer's flight bookings? How is this done?
5. Activate the program with all its subobjects and execute the program.
Task 2: Create an ABAP CDS View
Using the ABAP Development Tools in Eclipse, create a data definition (= DDL source) that
defines an ABAP CDS view which contains the complete calculation logic found in subroutine
get_data. Make use of the fact that ABAP CDS supports string expressions and currency
conversions. Define the view with an import parameter for the target currency of the
conversion.
1. Go to the ABAP perspective in Eclipse. In the Project Explorer, go to your package
ZHA400–## on System T8N.
2. In your package ZHA400–##, create a new data definition (suggested name:
ZHA400_##_BOOKING_W_CONVAM).
3. Within the data definition, adjust annotation @ABAPCatalog.sqlViewName to specify the
name of the SQL view.
4. After the with parameters addition, define an input parameter for the target currency of
the currency conversion (suggested name: p_target_curr). Use code completion to choose
the appropriate type for currency codes.
5. Edit the from clause of the SELECT statement. Add all tables, joins and join conditions you
find in the SELECT statement in subroutine get_data.
Hint:
Remember that, inside a DDL source, you use session variable
$session.system_language instead of system field sy-langu.
6. Within the curly brackets ({ }), edit the field list. Provide exactly the fields defined in local
structure type ty_s_booking of the ABAP program. Use SQL function concat_with_space( )
to concatenate ID and NAME into view field CUSTOMER. Use SQL function
currency_conversion( ) to convert the content of field FORCURAM into the target currency
370
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
and return it via view field CONVAM. Return the input parameter value as view field
CURRENCY.
7. Use annotations @EndUserText.label to add descriptions for the calculated fields. Use
annotations @Semantics.currencyCode and @Semantics.amount.currencyCode to
establish the connection between view fields CONVAM and CURRENCY.
8. Save and activate your DDL source.
Note:
You can ignore the syntax warning that tells you that search help SCUSTOM
is not inherited.
Task 3: Use the CDS View to Optimize the Data Retrieval of the Program
Edit your program ZHA400_##_CSTUDY_1. Replace subroutine get_data with a new
subroutine get_data_cds. Optimize the data retrieval in this new subroutine by performing just
one SELECT from your CDS view.
Hint:
Remember that you need to use the new syntax of Open SQL if you want to
select from the CDS entity.
1. Copy subroutine get_data to a new subroutine get_data_cds.
2. Comment out the call of subroutines get_data and replace it with a call of the new
subroutine.
3. In subroutine get_data_cds, implement an Open SQL SELECT that reads data from the
CDS view you just created. Let the SELECT read into data object ct_bookings directly.
Make sure you provide a value for the input parameter of the CDS view.
4. Activate and test your program.
© Copyright. All rights reserved.
371
Unit 7
Solution 20
Case Study Part 1: Code Push Down with ABAP
Core Data Services
Simulation: Case Study Part 1: Code Push Down with ABAP Core Data Services
For more information on Case Study Part 1: Code Push Down with ABAP Core
Data Services, please view the simulation in the lesson Optimizing a Report with
CDS View and ALV IDA online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program that determines, for a set of customers to be
entered, the total amount (in your local currency) each customer spends for flights. As a first
step, you want to push the currency conversion into the database, making use of an ABAP
CDS view yet to be developed.
Template:
Report HA400_CASE_STUDY_T1
Solution:
DDL Source HA400_BOOKING_W_CONV_AMOUNT
Report HA400_CASE_STUDY_S1
Task 1: Copy and Analyze Template
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_CASE_STUDY_T1 in your package ZHA400_## (suggested name:
ZHA400_##_CSTUDY_1, where ## is your group number). Activate, analyze, and execute the
program.
Hint:
Remember that there is no SAP GUI editor for repository object DDL source. You
have to develop at least your CDS view in ABAP Development Tools (ADT). The
rest of the exercise you can still do in the classical ABAP Workbench. But you
might want to take the opportunity and perform this complete exercise in
Eclipse.
1. Create a copy of the report and all its subobjects. Place it in your package ZHA400_##
and assign it to your workbench task.
372
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
Hint:
To copy the report using the ABAP Development Tools, use the contextual
menu item Duplicate.
a) Complete this step as you learned before.
2. Analyze the source code of subroutine get_data.
a) Complete this step as you learned before.
3. Which database tables occur in the FROM clause of the select statement? Which data are
read from them?
Table SCUSTOM (Customer name and address data), table T005T (country name), table
SBOOK (Booking details), table SPFLI (Departure City and Arrival City).
4. What is calculated in the loop over the customer's flight bookings? How is this done?
The customer’s ID and NAME are concatenated into a single field CUSTOMER. This is
done in a string expression using operator &&. The payment in local currency is converted
to the currency provided in USING-parameter pv_taget_currency. This is done via function
module CONVERT_TO_LOCAL_CURRENCY.
5. Activate the program with all its subobjects and execute the program.
a) Complete this step as you learned to do in previous classes.
Task 2: Create an ABAP CDS View
Using the ABAP Development Tools in Eclipse, create a data definition (= DDL source) that
defines an ABAP CDS view which contains the complete calculation logic found in subroutine
get_data. Make use of the fact that ABAP CDS supports string expressions and currency
conversions. Define the view with an import parameter for the target currency of the
conversion.
1. Go to the ABAP perspective in Eclipse. In the Project Explorer, go to your package
ZHA400–## on System T8N.
a) Log on to the ABAP project on system T8N, if you are not already logged on.
b) Expand the project and open the Favorite Packages folder.
c) Expand your package ZHA400–##, which you added as a favorite package in a
previous exercise.
2. In your package ZHA400–##, create a new data definition (suggested name:
ZHA400_##_BOOKING_W_CONVAM).
a) Right-click the package and choose New → Other ABAP Repository Object.
b) In the tree below, choose Core Data Services → Data Definition and choose Next.
c) Enter the name of your package, a name, and a short description for the new object,
and choose Next.
d) Assign the object to your transport request and choose Next.
© Copyright. All rights reserved.
373
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
e) Choose Use the selected template, choose Define View with Parameters and choose
Finished.
3. Within the data definition, adjust annotation @ABAPCatalog.sqlViewName to specify the
name of the SQL view.
a) In the first line of the editor, look for statement @AbapCatalog.sqlViewName:
b) After the colon, enter a name for the SQL view in single quotes (suggested name:
ZHA400_##_BOOK).
See the source code extract from the model solution.
4. After the with parameters addition, define an input parameter for the target currency of
the currency conversion (suggested name: p_target_curr). Use code completion to choose
the appropriate type for currency codes.
a) See the source code extract from the model solution.
5. Edit the from clause of the SELECT statement. Add all tables, joins and join conditions you
find in the SELECT statement in subroutine get_data.
Hint:
Remember that, inside a DDL source, you use session variable
$session.system_language instead of system field sy-langu.
a) See the source code extract from the model solution.
6. Within the curly brackets ({ }), edit the field list. Provide exactly the fields defined in local
structure type ty_s_booking of the ABAP program. Use SQL function concat_with_space( )
to concatenate ID and NAME into view field CUSTOMER. Use SQL function
currency_conversion( ) to convert the content of field FORCURAM into the target currency
and return it via view field CONVAM. Return the input parameter value as view field
CURRENCY.
a) See the source code extract from the model solution.
7. Use annotations @EndUserText.label to add descriptions for the calculated fields. Use
annotations @Semantics.currencyCode and @Semantics.amount.currencyCode to
establish the connection between view fields CONVAM and CURRENCY.
a) See the source code extract from the model solution.
8. Save and activate your DDL source.
Note:
You can ignore the syntax warning that tells you that search help SCUSTOM
is not inherited.
a) Choose Save.
b) Choose Activate.
Task 3: Use the CDS View to Optimize the Data Retrieval of the Program
Edit your program ZHA400_##_CSTUDY_1. Replace subroutine get_data with a new
subroutine get_data_cds. Optimize the data retrieval in this new subroutine by performing just
one SELECT from your CDS view.
374
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
Hint:
Remember that you need to use the new syntax of Open SQL if you want to
select from the CDS entity.
1. Copy subroutine get_data to a new subroutine get_data_cds.
a) Perform this step as you learned to do in previous classes.
2. Comment out the call of subroutines get_data and replace it with a call of the new
subroutine.
a) Perform this step as you learned to do in previous classes.
3. In subroutine get_data_cds, implement an Open SQL SELECT that reads data from the
CDS view you just created. Let the SELECT read into data object ct_bookings directly.
Make sure you provide a value for the input parameter of the CDS view.
a) See the source code extract from the model solution.
4. Activate and test your program.
a) Complete this step as you learned to do in previous classes.
b) Verify that your code matches the following solution:
Source Code Extract: DDL Source
@AbapCatalog.sqlViewName: 'HA400_BOOK_CONV'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'HA400 CDS View for Case Study'
define view Ha400_Booking_W_Conv_Amount
with parameters p_target_curr:abap.cuky
as select from scustom as c
inner join t005t as t
on c.country = t.land1
and t.spras = $session.system_language
inner join sbook as b
on c.id = b.customid
and b.cancelled <> 'X'
inner join spfli as p
on b.carrid = p.carrid
and b.connid = p.connid
{
c.id,
c.name,
@EndUserText.label: 'Flight Customer'
concat_with_space(c.id, c.name, 1) as customer,
c.city,
t.landx as country,
b.carrid,
b.connid,
b.fldate,
p.cityfrom,
p.cityto,
@EndUserText.label: 'Booking Price (Converted)'
@Semantics.amount.currencyCode: 'CONVAM_CURRENCY'
currency_conversion(
amount => b.forcuram,
source_currency => b.forcurkey,
target_currency => $parameters.p_target_curr,
exchange_rate_date => b.order_date,
© Copyright. All rights reserved.
375
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
error_handling => 'FAIL_ON_ERROR' ) as
convam,
@EndUserText.label: 'Currency'
@Semantics.currencyCode: true
$parameters.p_target_curr as convam_currency
}
Source Code Extract: Subroutine get_data_cds
FORM get_data
USING pt_range_id
pt_range_name
pv_target_currency
CHANGING ct_bookings
LIKE so_id[]
LIKE so_name[]
TYPE s_curr
TYPE ty_t_bookings.
* Processing
*****************
CLEAR ct_bookings.
SELECT country, city, customer, carrid, connid, fldate,
cityfrom, cityto, convam, convam_currency
FROM ha400_booking_w_conv_amount( p_target_curr =
@pv_target_currency )
INTO TABLE @ct_bookings
WHERE
id IN @pt_range_id
AND name IN @pt_range_name.
ENDFORM.
376
© Copyright. All rights reserved.
Unit 7
Exercise 21
Case Study Part 2: Use ALV Optimized for SAP
HANA
Simulation: Case Study Part 2: Use ALV Optimized for SAP HANA
For more information on Case Study Part 2: Use ALV Optimized for SAP HANA,
please view the simulation in the lesson Optimizing a Report with CDS View and
ALV IDA online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program that determines, for a set of customers to be
entered, the total amount (in your local currency) each customer spends for flights. In the
second step, you want to use the SAP List Viewer with Integrated Data Access (ALV with IDA)
to display the result.
Template:
DDL Source HA400_BOOKING_W_CONV_AMOUNT
Report HA400_CASE_STUDY_S1
Solution:
Report HA400_CASE_STUDY_S2
Task 1: Copy and Analyze Template
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_CASE_STUDY_S1 in your package ZHA400_## (suggested name:
ZHA400_##_CSTUDY_2, where ## is your group number). Activate, analyze, and execute the
program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
2. Analyze the source code of subroutine get_data_cds. Where does the data come from?
3. Activate and execute the program.
Task 2: Replace the Classical ALV with ALV with IDA
Edit your program. Replace the instantiation of the classical ALV with an instantiation of the
ALV with Integrated Data Access (ALV with IDA). Comment out the call of subroutines
get_data_cds and replace it with a call of a new subroutine (suggested name:
set_selection_alv_ida) in which you set the data selection for the new ALV instance. Comment
out the call of subroutine configure_alv and replace it with a call of a new subroutine
© Copyright. All rights reserved.
377
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
(suggested name: configure_alv_ida in which you do the same settings as before but using the
API of the new ALV.
1. Comment out the call of method factory of class cl_salv_table and implement a call of
method create_for_cds_view of class cl_salv_gui_table_ida instead. Supply input
parameter iv_cds_view_name with the name of the CDS view you developed in the
previous exercise. (Alternatively, you can use CDS view
HA400_BOOKING_W_CONV_AMOUNT). Adjust the definition of data object go_salv to be
compatible with the returning parameter of the method.
2. Define a new subroutine (suggested name: set_selection_alv) in which you pass the select
options and a value for the CDS view’s input parameter to the ALV instance. Replace the
call of subroutine get_data_cds with a call to this new subroutine.
Hint:
Call appropriate methods of the ALV instance (interface
if_salv_gui_table_ida) and make use of service class
cl_salv_range_tab_collector.
3. Define a new subroutine (suggested name: configure_alv_ida) in which you hide unwanted
fields, define an aggregation in field CONVAM, a sorting in column FLDATE and a grouping
in columns COUNTRY, CITY and CUSTOMER. Replace the call of subroutine configure_alv
with a call to this new subroutine.
Hint:
Call appropriate methods of the layout object (interface
if_salv_gui_layout_ida), which you can retrieve from the ALV instance via
method default_layout. Note that grouping of values is considered to be a
part of the sorting.
4. Replace the call of method display of the classical ALV instance with a call of the
corresponding method of the new ALV instance.
Hint:
There is no method display in interface if_salv_gui_table_ida. You have to call
method fullscreen first and then method display for the resulting object
reference.
5. Implement appropriate exception handling.
6. Activate and test the report.
378
© Copyright. All rights reserved.
Unit 7
Solution 21
Case Study Part 2: Use ALV Optimized for SAP
HANA
Simulation: Case Study Part 2: Use ALV Optimized for SAP HANA
For more information on Case Study Part 2: Use ALV Optimized for SAP HANA,
please view the simulation in the lesson Optimizing a Report with CDS View and
ALV IDA online in the SAP Learning Hub.
Business Example
You are asked to improve an ABAP program that determines, for a set of customers to be
entered, the total amount (in your local currency) each customer spends for flights. In the
second step, you want to use the SAP List Viewer with Integrated Data Access (ALV with IDA)
to display the result.
Template:
DDL Source HA400_BOOKING_W_CONV_AMOUNT
Report HA400_CASE_STUDY_S1
Solution:
Report HA400_CASE_STUDY_S2
Task 1: Copy and Analyze Template
In system T8N, which uses SAP HANA as its primary database, create a copy of report
HA400_CASE_STUDY_S1 in your package ZHA400_## (suggested name:
ZHA400_##_CSTUDY_2, where ## is your group number). Activate, analyze, and execute the
program.
1. Create a copy of the report. Place it in your package ZHA400_## and assign it to your
workbench task.
a) Complete this step as you learned in previous exercises.
2. Analyze the source code of subroutine get_data_cds. Where does the data come from?
The subroutine selects from CDS view HA400_BOOKING_W_CONV_AMOUNT, which is
defined in the DDL source with the same name.
3. Activate and execute the program.
a) Complete this step as you learned to do in previous classes.
Task 2: Replace the Classical ALV with ALV with IDA
Edit your program. Replace the instantiation of the classical ALV with an instantiation of the
ALV with Integrated Data Access (ALV with IDA). Comment out the call of subroutines
© Copyright. All rights reserved.
379
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
get_data_cds and replace it with a call of a new subroutine (suggested name:
set_selection_alv_ida) in which you set the data selection for the new ALV instance. Comment
out the call of subroutine configure_alv and replace it with a call of a new subroutine
(suggested name: configure_alv_ida in which you do the same settings as before but using the
API of the new ALV.
1. Comment out the call of method factory of class cl_salv_table and implement a call of
method create_for_cds_view of class cl_salv_gui_table_ida instead. Supply input
parameter iv_cds_view_name with the name of the CDS view you developed in the
previous exercise. (Alternatively, you can use CDS view
HA400_BOOKING_W_CONV_AMOUNT). Adjust the definition of data object go_salv to be
compatible with the returning parameter of the method.
a) See the source code extract from the model solution.
2. Define a new subroutine (suggested name: set_selection_alv) in which you pass the select
options and a value for the CDS view’s input parameter to the ALV instance. Replace the
call of subroutine get_data_cds with a call to this new subroutine.
Hint:
Call appropriate methods of the ALV instance (interface
if_salv_gui_table_ida) and make use of service class
cl_salv_range_tab_collector.
a) See the source code extract from the model solution.
3. Define a new subroutine (suggested name: configure_alv_ida) in which you hide unwanted
fields, define an aggregation in field CONVAM, a sorting in column FLDATE and a grouping
in columns COUNTRY, CITY and CUSTOMER. Replace the call of subroutine configure_alv
with a call to this new subroutine.
Hint:
Call appropriate methods of the layout object (interface
if_salv_gui_layout_ida), which you can retrieve from the ALV instance via
method default_layout. Note that grouping of values is considered to be a
part of the sorting.
a) See the source code extract from the model solution.
4. Replace the call of method display of the classical ALV instance with a call of the
corresponding method of the new ALV instance.
Hint:
There is no method display in interface if_salv_gui_table_ida. You have to call
method fullscreen first and then method display for the resulting object
reference.
a) See the source code extract from the model solution.
5. Implement appropriate exception handling.
a) See the source code extract from the model solution.
380
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
6. Activate and test the report.
a) Perform this step as before.
b) Verify that your code matches the following solution:
Code Extract: Report HA400_CASE_STUDY_S2
*&--------------------------------------------------------------------*
*& Report HA400_CASE_STDY_S2
*&--------------------------------------------------------------------*
*&
*&--------------------------------------------------------------------*
REPORT ha400_case_study_s2 MESSAGE-ID ha400.
* Structure for Result
TYPES: BEGIN OF ty_s_booking,
country
TYPE t005t-landx,
city
TYPE scustom-city,
customer
TYPE ha400_customer,
carrid
TYPE sbook-carrid,
connid
TYPE sbook-connid,
fldate
TYPE sbook-fldate,
cityfrom
TYPE spfli-cityfrom,
cityto
TYPE spfli-cityto,
convam
TYPE s_sum,
convam_currency TYPE s_curr,
END OF ty_s_booking.
TYPES: ty_t_bookings TYPE STANDARD TABLE OF ty_s_booking
WITH NON-UNIQUE KEY customer.
DATA: gt_bookings TYPE
gs_booking TYPE
ty_t_bookings,
ty_s_booking.
* ALV Processing
*DATA go_salv TYPE REF TO cl_salv_table.
*DATA gx_excp TYPE REF TO cx_salv_error.
DATA go_salv TYPE REF TO if_salv_gui_table_ida.
DATA gx_excp TYPE REF TO cx_salv_ida_dynamic.
* selection screen
DATA gs_scustom TYPE scustom.
SELECTION-SCREEN BEGIN OF BLOCK cus WITH FRAME TITLE TEXT-cus.
SELECT-OPTIONS:
so_id FOR gs_scustom-id,
so_name FOR gs_scustom-name.
SELECTION-SCREEN END OF BLOCK cus.
AT SELECTION-SCREEN.
* message not needed any more: Application is much faster now
* IF so_id IS INITIAL AND so_name IS INITIAL.
*
MESSAGE w050.
* ENDIF.
© Copyright. All rights reserved.
381
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
START-OF-SELECTION.
* Provide Data
*----------------------*
* PERFORM get_data_cds
*
*
*
*
*
*
* Create ALV Instance
*----------------------*
USING
so_id[]
so_name[]
'USD'
CHANGING
gt_bookings.
TRY.
*
*
*
*
*
*
cl_salv_table=>factory(
IMPORTING
r_salv_table
= go_salv
CHANGING
t_table
= gt_bookings
).
go_salv = cl_salv_gui_table_ida=>create_for_cds_view(
iv_cds_view_name =
'HA400_BOOKING_W_CONV_AMOUNT'
).
* New: Set Data Selection for ALV Instance
*---------------------------------------------*
PERFORM set_selection_alv_ida USING
go_salv
so_id[]
so_name[]
'USD'.
* Configure ALV Instance
*-------------------------*
*
*
*
PERFORM configure_alv
USING
go_salv.
PERFORM configure_alv_ida
USING
go_salv.
* Display
*-------------------------*
*
go_salv->display( ).
go_salv->fullscreen( )->display( ).
* Error Handling
*--------------------------*
*
CATCH cx_salv_error INTO gx_excp.
"
CATCH cx_salv_ida_dynamic INTO gx_excp.
MESSAGE gx_excp TYPE 'I'.
ENDTRY.
382
"
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
*&--------------------------------------------------------------------*
*& Form set_selection_alv_ida
*&--------------------------------------------------------------------*
FORM set_selection_alv_ida
USING po_salv TYPE REF TO if_salv_gui_table_ida
pt_range_id
LIKE so_id[]
pt_range_name
LIKE so_name[]
pv_target_currency TYPE s_curr.
DATA:
lo_range_collector TYPE REF TO cl_salv_range_tab_collector,
lt_named_ranges
TYPE
if_salv_service_types=>yt_named_ranges.
DATA: lt_parameter TYPE if_salv_gui_types_ida=>yt_parameter,
ls_parameter LIKE LINE OF lt_parameter.
* Set parameter
*--------------------------------------*
ls_parameter-name = 'P_TARGET_CURR'.
ls_parameter-value = 'USD'.
APPEND ls_parameter TO lt_parameter.
po_salv->set_view_parameters( lt_parameter ).
* Set ranges for preselection
*--------------------------------------*
CREATE OBJECT lo_range_collector.
lo_range_collector->add_ranges_for_name(
iv_name
= 'ID'
it_ranges = pt_range_id
).
lo_range_collector->add_ranges_for_name(
iv_name
= 'NAME'
it_ranges = pt_range_name
).
lo_range_collector->get_collected_ranges(
IMPORTING
et_named_ranges = lt_named_ranges
).
po_salv->set_select_options(
EXPORTING
it_ranges
= lt_named_ranges
).
ENDFORM.
*&--------------------------------------------------------------------*
*& Form configure_alv_ida
*&--------------------------------------------------------------------*
© Copyright. All rights reserved.
383
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
FORM configure_alv_ida
USING po_salv TYPE REF TO if_salv_gui_table_ida.
* ALV processing
DATA: lo_layout TYPE REF TO if_salv_gui_layout_ida.
DATA:
lt_visible_fields TYPE if_salv_gui_types_ida=>yt_field_name.
DATA: lt_sort_order TYPE
if_salv_gui_types_ida=>yt_sort_rule,
ls_sort_order LIKE LINE OF lt_sort_order.
DATA: lt_aggregation TYPE if_salv_gui_types_ida=>yt_aggregation_rule,
ls_aggregation LIKE LINE OF lt_aggregation.
DATA: lx_excp
TYPE REF TO cx_salv_ida_dynamic.
TRY.
lo_layout = po_salv->default_layout( ).
* Hide unwanted fields
*-----------------------*
APPEND 'COUNTRY'
TO lt_visible_fields.
APPEND 'CITY'
TO lt_visible_fields.
APPEND 'CUSTOMER'
TO lt_visible_fields.
APPEND 'CARRID'
TO lt_visible_fields.
APPEND 'CONNID'
TO lt_visible_fields.
APPEND 'FLDATE'
TO lt_visible_fields.
APPEND 'CITYFROM'
TO lt_visible_fields.
APPEND 'CITYTO'
TO lt_visible_fields.
APPEND 'CONVAM'
TO lt_visible_fields.
APPEND 'CONVAM_CURRENCY' TO lt_visible_fields.
lo_layout->set_visible_fields( lt_visible_fields ).
* Preset sort order, grouping and aggregations
*----------------------------------------------*
* Calculate Sum in Column CONVAM
ls_aggregation-field_name = 'CONVAM'.
ls_aggregation-function
=
if_salv_service_types=>cs_function_code-sum.
APPEND ls_aggregation TO lt_aggregation.
lo_layout->set_aggregations( lt_aggregation
).
* Sorting and subtotals for columns COUNTRY, CITY and CUSTOMER
ls_sort_order-field_name = 'COUNTRY'.
ls_sort_order-descending = abap_false.
ls_sort_order-is_grouped = abap_true.
APPEND ls_sort_order TO lt_sort_order.
ls_sort_order-field_name = 'CITY'.
ls_sort_order-descending = abap_false.
ls_sort_order-is_grouped = abap_true.
APPEND ls_sort_order TO lt_sort_order.
ls_sort_order-field_name = 'CUSTOMER'.
384
© Copyright. All rights reserved.
Lesson: Optimizing a Report with CDS View and ALV IDA
ls_sort_order-descending = abap_false.
ls_sort_order-is_grouped = abap_true.
APPEND ls_sort_order TO lt_sort_order.
* Sorting in column FLDATE
ls_sort_order-field_name = 'FLDATE'.
ls_sort_order-descending = abap_false.
ls_sort_order-is_grouped = abap_false.
APPEND ls_sort_order TO lt_sort_order.
lo_layout->set_sort_order( lt_sort_order ).
* Exception Handling
*--------------------*
CATCH cx_salv_ida_dynamic INTO lx_excp.
MESSAGE lx_excp TYPE 'I'.
ENDTRY.
"
ENDFORM.
© Copyright. All rights reserved.
385
Unit 7: Case Study: Optimize a Report on Flight Customer Revenue
LESSON SUMMARY
You should now be able to:
●
386
Optimizing a report with CDS view and ALV with IDA
© Copyright. All rights reserved.
Unit 7
Learning Assessment
1. I have reviewed the content of this lesson.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
387
Unit 7: Learning Assessment
388
© Copyright. All rights reserved.
UNIT 8
Appendix
Lesson 1
Additional ABAP Language Enhancements
391
Lesson 2
External Session Debugging of ABAP-Managed Database Procedures
395
UNIT OBJECTIVES
●
Use inline data declarations in ABAP code
●
Debugging ABAP-Managed Database Procedures before NetWeaver 7.50
© Copyright. All rights reserved.
389
Unit 8: Appendix
390
© Copyright. All rights reserved.
Unit 8
Lesson 1
Additional ABAP Language Enhancements
LESSON OVERVIEW
In this lesson, you will learn how to use inline data declarations and string and table
expressions in ABAP code.
Business Example
Your company has recognized SAP HANA as an important strategic topic and has asked you
to refresh your ABAP skills, paying particular attention to those required to develop or review
code that leverages the strengths of SAP HANA. Your company ITeLO sells hardware to other
companies, and purchases hardware or parts from other companies. ITeLO uses several
ABAP applications, for example to classify customers according to their payment behavior,
the total sales volume they generate, for dunning runs, financial account results and more.
One of these ABAP applications is called Open Item Analytics and analyzes how long the
customer invoices remain unpaid on average and per customer, the total open invoice
amount per customer, and proposes which customer should receive a payment reminder as a
result of the analysis. Your company ITeLO wants you to improve the performance of this
application considerably, by making use of SAP HANA. The ABAP system has been migrated
to use SAP HANA as its primary database already.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use inline data declarations in ABAP code
Expressions in ABAP
Figure 274: Helpful ABAP Language Improvements: Expressions in ABAP 7.4
In addition to enhancements to the Open SQL language, ABAP 7.4 SPS05 also comes with
considerable enhancements to the ABAP language itself. These improvements can simplify
ABAP development in general, and some of them are particularly handy when using ADBC or
optimizing ABAP code for SAP HANA.
© Copyright. All rights reserved.
391
Unit 8: Appendix
Most improvements relevant in the context of ADBC can be summarized under the title: using
expressions in ABAP. An expression in a programming language like ABAP is a combination of
constants, variables, operators, functions and values which is evaluated at runtime and
returns a result. It can therefore be used in program statements in places where you would
put a constant or variable in the simplest case.
The ABAP language originally had relatively limited support for expressions and was very
imperative, leading to the need for sequences of statements and intermediate variables to
calculate results used in subsequent statements. The situation has improved considerably
over the last number of years, for example with the introduction of method call chaining and
recently string expressions, but ABAP 7.4 makes another leap. ABAP now supports inline data
and field symbol declarations, constructor expressions and even table expressions.
This allows you to write ABAP code in a style that corresponds more to what you may be used
to in other programming languages like C or Java. It allows you to express more of what you
want to calculate and less of how to calculate it. You do not have to write a statement for each
intermediate step in a calculation and this way need fewer local variables used once only.
Figure 275: String Expressions and String Templates
The first example in the figure, String Expressions and String Templates, for expression
support has already been introduced with ABAP 7.02: string expressions and string
templates.
These expressions can be very handy when using native SQL, to compose the native SQL
strings typically containing literals, local or system variables, and also single quotes in the
result.
With classical ABAP statements, you have to introduce a local variable to hold the result of the
concatenation and a CONCATENATE statement. In addition you have to be very careful with
trailing blanks and escaping the quotes correctly.
String expressions can simplify composing a native SQL statement in ABAP as follows:
●
Use the pipe symbol to define so-called string templates.
●
Mix in the values of variables or even expressions, enclosing them in curly braces.
●
392
Simply use single quotes within the string templates, as the string templates are not
delimited by single quotes.
© Copyright. All rights reserved.
Lesson: Additional ABAP Language Enhancements
●
Use the string expression directly as parts of statements, for example, as parameter of a
method call. You do not have to assign the string to a local variable first.
Figure 276: Inline Declarations and Constructor Expressions
ABAP 7.4 SPS05 introduces considerably more support for expressions. One group of
expressions allows declaring data objects and creating instances of classes and data objects,
as follows:
●
●
●
●
●
Local variables and their type can be defined in a single step, using an expression
containing the DATA( ) operator.
The equivalent works for field symbols using the FIELD-SYMBOL( ) operator.
The NEW( ) operator can be used to instantiate objects (including data objects). You can
specify the class respectively type explicitly using NEW <type>( ), or let the ABAP compiler
infer the type using NEW #( ).
Data references can be created inline using the REF( ) operator. You can specify the
reference type explicitly using REF <type>( ), or let the ABAP compiler infer the type using
REF #( ).
You can also create value objects without introducing variables, using the VALUE( )
operator. Again, you can specify the data type explicitly using VALUE <type>( ), or let the
ABAP compiler infer the type. Value objects can be simple, complex structures and even
tables. Using value objects can be helpful for unit-testing, assertions, for example.
For type conversions, the new operators CONV( ) and CAST can be used – check the online
documentation for details and a full list of newly supported expressions and operators.
© Copyright. All rights reserved.
393
Unit 8: Appendix
Figure 277: Table Expressions
Another helpful type of expressions is table expressions.
With table expressions, you can access table rows in a similar ways as with a READ TABLE
statement, for example by specifying the index of the row you want access, or by specifying
the value of a column. Since table expressions are expressions, you can use them directly as
parts of statements, without reading into a work area first, you can directly reference fields of
the resulting row and even chain such expressions.
This way, far fewer READ TABLE statements and one-off local variables to hold intermediate
results are necessary, making ABAP code more readable.
LESSON SUMMARY
You should now be able to:
●
394
Use inline data declarations in ABAP code
© Copyright. All rights reserved.
Unit 8
Lesson 2
External Session Debugging of ABAP-Managed
Database Procedures
LESSON OVERVIEW
This lesson covers how to debug ABAP-Managed Database Procedures.
Business Example
Your company ITeLO wants you to improve the performance of some ABAP application
considerably, by making use of SAP HANA installed as a primary database for the ABAP
system. You have developed an ABAP-managed database procedure and use it in an ABAP
application, but the application does not produce the expected result. You thus want to debug
into the database procedure to verify that parameters are passed correctly and that the
procedure works correctly.
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Debugging ABAP-Managed Database Procedures before NetWeaver 7.50
Debugging ABAP-Managed Database Procedures in SAP NetWeaver 7.40
In earlier ABAP releases supporting AMDPs, procedures can only be debugged using a direct
database connection in the SAP HANA studio and so-called “external session debugging”.
This results in three user accounts being involved, and some authorizations that must be
granted as a prerequisite.
© Copyright. All rights reserved.
395
Unit 8: Appendix
Figure 278: Involved User Accounts and Authorizations
The ABAP user (ABAPDEV in the figure, Involved User Accounts and Authorizations)
executing the ABAP application needs the usual authorizations on ABAP level, that is, the
authorization to execute the application, and to debug on the ABAP level if the ABAP code is
also to be stepped through.
An SAP HANA user (HANADEBUG in the figure) who can access the database and perform
the database debugging needs the authorizations to do the following:
●
Read the SAP HANA database catalog and the ABAP system’s schema
●
Execute and debug the procedure in question (see SAP note 1942471)
●
Attach the debugger to sessions of the SAP<SID> user
The SAP<SID> user used by the ABAP system to access the database (SAP T8N in the
figure). This user initiates executing the database procedure. Only the SAP<SID> user can
grant the HANADEBUG user the permission to attach a debugger to SAP<SID> user sessions,
and this user can also grant the permission to execute and debug the procedure.
The SQL grant statements to be executed on the SAP HANA level (as SAP<SID> user) for
ABAP-Managed Database Procedure AMDP_NAME in ABAP system SAPT8N are
GRANT DEBUG ON "SAPT8N"."AMDP_NAME" TO HANADEBUG; GRANT EXECUTE ON
"SAPT8N"."AMDP_NAME" TO HANADEBUG; GRANT ATTACH DEBUGGER to HANADEBUG;
Alternatively, the grant statements for the authorization to debug any ABAP-Managed
Database Procedure in the schema SAPT8N are as follows:
GRANT DEBUG ON SCHEMA "SAPT8N" TO HANADEBUG; GRANT EXECUTE ON SCHEMA
"SAPT8N" TO HANADEBUG; GRANT ATTACH DEBUGGER to HANADEBUG;
396
© Copyright. All rights reserved.
Lesson: External Session Debugging of ABAP-Managed Database Procedures
External Session Debugging using SAP HANA Tools
Figure 279: Setting Up External Session Debugging in SAP HANA
To prepare the debugging session, perform the following steps:
1. Make sure that the procedure has been called at least once, by an appropriate run of the
ABAP application. This is necessary because the AMDPs are only created on the database
level upon the first call.
2. Use one of the SAP HANA perspectives in the SAP HANA studio (for example, the Modeler
perspective) to locate the database procedure in the database catalog. The procedure
belongs to the ABAP system schema.
3. Open the procedure named exactly like the method in the ABAP system. Additional
procedures with extended names are generated stubs only.
4. Set breakpoints as needed.
5. Create a debug configuration for external session debugging, using as filter parameters:
●
SAP HANA System: the connection of the HANA user used for debugging,
HANADEBUG in the example.
●
HANA User: the SAP<SID> user, SAPT8N in the example.
●
Application User: The ABAP user, ABAPDEV in the example.
6. Start a debug thread.
The debug thread does not execute the database procedure and stop at a breakpoint.
Instead, the thread waits for the HANA user entered in the debug configuration to initiate a
database session and hit a breakpoint. Only then will the thread attach to the HANA user's
session and debugging begin.
© Copyright. All rights reserved.
397
Unit 8: Appendix
Figure 280: Performing External Session Debugging
To begin debugging, start the ABAP application using the ABAP user entered as Application
User in the debug configuration. Application execution will stop once the first breakpoint in
the database procedure is reached.
In the SAP HANA studio Debug perspective, the code of the database procedure is shown and
execution waits at the first breakpoint.
You can see the input and output parameters and the instantiated local variables in view
Variables. You can also inspect their values.
To proceed debugging, resume execution. The database procedure debugger does not
support stepping through the code like you may be used to from the ABAP debugger. You can
only resume execution.
Hint:
While the debugger is waiting at a breakpoint, you can still add breakpoints. You
can also set a breakpoint at the line of code containing the database procedure
end statement.
Caution:
When finished, explicitly terminate the debugging process using the Terminate
button. If you do not, the SAP HANA system will keep waiting for sessions to
attach a debugger.
LESSON SUMMARY
You should now be able to:
●
398
Debugging ABAP-Managed Database Procedures before NetWeaver 7.50
© Copyright. All rights reserved.
Unit 8
Learning Assessment
1. String expressions can simplify composing a native SQL statement in ABAP by using the
pipe symbol to define so-called string templates.
Determine whether this statement is true or false.
X
True
X
False
2. Which of the following steps should be performed when preparing the debugging session?
Choose the correct answers.
X
B Ensure that the procedure has been called at least once
X
C Delete a debug thread
X
D Set breakpoints per the need
X
E Remove debugger from sessions
© Copyright. All rights reserved.
399
Download