Ha400 en Col08 Fv Part a4
April 5, 2017 | Author: Luna Minea | Category: N/A
Short Description
Download Ha400 en Col08 Fv Part a4...
Description
HA400 ABAP Programming for SAP HANA SAP HANA
Date Training Center Instructors
Education Website
Participant Handbook Course Version: 08 Course Duration: 3 Day(s) Material Number: 50124861
An SAP course - use it to learn, reference it for work
Copyright Copyright © 2014 SAP AG 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 AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors.
Trademarks Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered trademarks of Adobe Systems Incorporated in the United States and other countries. Apple, App Store, FaceTime, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C, Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc. Bluetooth is a registered trademark of Bluetooth SIG Inc. Citrix, ICA, Program Neighborhood, MetaFrame now XenApp, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems Inc. Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH. Edgar Online is a registered trademark of EDGAR Online Inc., an R.R. Donnelley & Sons Company. Facebook, the Facebook and F logo, FB, Face, Poke, Wall, and 32665 are trademarks of Facebook. Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps, Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync, Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik, and Android are trademarks or registered trademarks of Google Inc. HP is a registered trademark of the Hewlett-Packard Development Company L.P. HTML, XML, XHTML, and W3C are trademarks, registered trademarks, or claimed as generic terms by the Massachusetts Institute of Technology (MIT), European Research Consortium for Informatics and Mathematics (ERCIM), or Keio University. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation. Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are registered trademarks of Microsoft Corporation. INTERMEC is a registered trademark of Intermec Technologies Corporation. IOS is a registered trademark of Cisco Systems Inc. The Klout name and logos are trademarks of Klout Inc. Linux is the registered trademark of Linus Torvalds in the United States and other countries. Motorola is a registered trademark of Motorola Trademark Holdings LLC. Mozilla and Firefox and their logos are registered trademarks of the Mozilla Foundation. Novell and SUSE Linux Enterprise Server are registered trademarks of Novell Inc.
g2014623102738
OpenText is a registered trademark of OpenText Corporation. Oracle and Java are registered trademarks of Oracle and its affiliates. QR Code is a registered trademark of Denso Wave Incorporated. RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry AppWorld are trademarks or registered trademarks of Research in Motion Limited. SAVO is a registered trademark of The Savo Group Ltd. The Skype name is a trademark of Skype or related entities. Twitter and Tweet are trademarks or registered trademarks of Twitter. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Wi-Fi is a registered trademark of Wi-Fi Alliance. SAP, R/3, ABAP, BAPI, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork, SAP HANA, the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, Sybase, Adaptive Server, Adaptive Server Enterprise, iAnywhere, Sybase 365, SQL Anywhere, Crossgate, B2B 360° and B2B 360° Services, m@gic EDDY, Ariba, the Ariba logo, Quadrem, b-process, Ariba Discovery, SuccessFactors, Execution is the Difference, BizX Mobile Touchbase, It's time to love work again, SuccessFactors Jam and BadAss SaaS, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany or an SAP affiliate company. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary.
Disclaimer These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies (“SAP Group”) for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group 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.
g2014623102738
g2014623102738
About This Handbook This handbook is intended to complement the instructor-led presentation of this course, and serve as a source of reference. It is not suitable for self-study.
Typographic Conventions American English is the standard used in this handbook. The following typographic conventions are also used. Type Style
Description
Example text
Words or characters that appear on the screen. These include field names, screen titles, pushbuttons as well as menu names, paths, and options. Also used for cross-references to other documentation both internal and external.
2014
Example text
Emphasized words or phrases in body text, titles of graphics, and tables
EXAMPLE TEXT
Names of elements in the system. These include report names, program names, transaction codes, table names, and individual key words of a programming language, when surrounded by body text, for example SELECT and INCLUDE.
Example text
Screen output. This includes file and directory names and their paths, messages, names of variables and parameters, and passages of the source text of a program.
Example text
Exact user entry. These are words and characters that you enter in the system exactly as they appear in the documentation.
Variable user entry. Pointed brackets indicate that you replace these words and characters with appropriate entries.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
v
About This Handbook
HA400
Icons in Body Text The following icons are used in this handbook. Icon
Meaning For more information, tips, or background
Note or further explanation of previous point Exception or caution Procedures
Indicates that the item is displayed in the instructor's presentation.
vi
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Contents Course Overview .......................................................... ix Course Goals ........................................................... ix Course Objectives ..................................................... ix
Unit 1: Introduction........................................................ 1 SAP HANA Basics and Technical Concepts ........................3 Introduction to SAP HANA Studio .................................. 22 Introduction to ABAP Development Tools (ADT) ................. 32 Introduction to the EPM Sample Application ...................... 46
Unit 2: Taking ABAP to SAP HANA .................................. 53 SAP HANA as Secondary Database – Access via Open SQL . 55 Preparing for SAP HANA ............................................ 69 Guided Performance Analysis....................................... 90 Performance Rules and Guidelines for SAP HANA ............. 114
Unit 3: Code-to-Data with SAP HANA as Secondary Database .................................................................. 121 Classical Open SQL and Its Limitations ..........................123 ABAP Database Connectivity (ADBC) ............................129 Native SQL Syntax...................................................133 Working with Views in SAP HANA Studio ........................154 Consuming SAP HANA Views via Native SQL ..................163 Working With Database Procedures in SAP HANA Studio.....178 Calling SAP HANA Procedures in ABAP .........................184
Unit 4: Optimizing ABAP On Primary Database SAP HANA .. 199 New Open SQL ......................................................200 Core Data Services in ABAP .......................................219 Associations in Core Data Services ...............................242
Unit 5: Using ABAP-managed Database Procedures .......... 253 ABAP-Managed Database Procedures ...........................254 Debugging ABAP-managed Database Procedures .............271
Unit 6: SAP HANA Proxy Objects ................................... 281 Accessing SAP HANA Views via ABAP Dictionary External Views...............................................................283 Transport of SAP HANA Objects ..................................298
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
vii
Contents
HA400
Calling SAP HANA Procedures via ABAP Database Procedure Proxies.............................................................308
Unit 7: Advanced Topics .............................................. 323 Using SAP HANA Full Text Search ................................324 ABAP List Viewer (ALV) with Integrated Access to SAP HANA 351
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue ................................................................... 373 Creating an Analytic View...........................................374
Unit 9: Appendix ........................................................ 403 Additional ABAP Language Enhancements ......................404
viii
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Course Overview Target Audience This course is intended for the following audiences: •
Developers and development consultants who need to write or review performance-optimized ABAP code for SAP HANA.
Course Prerequisites Required Knowledge • • • • •
HA100 HANA Overview BC400 ABAP Workbench Fundamentals BC401 ABAP Objects Experience in ABAP Programing ( procedural and object oriented) Open SQL details (joins, views, aggregations)
Recommended Knowledge •
HA150 SQL Basics for SAP HANA
Course Goals This course will prepare you to: •
Develop and optimize ABAP applications that access data stored in the SAP HANA Database
Course Objectives After completing this course, you will be able to: • • • • • • •
2014
Understand the technical concepts of SAP HANA Understand how to optimize classic ABAP for SAP HANA Describe the use of analysis tools for performance optimization (Runtime Analysis, Code Inspector, SQL Trace, SQL Performance Tuning Worklist) Understand the SQL performance rules of ABAP for SAP HANA Access SAP HANA from ABAP using native SQL and ADBC (ABAP Database Connectivity) Use enhanced Open SQL Use Core Data Services in ABAP to define advanced views
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
ix
Course Overview
• • •
x
HA400
Call SAP HANA stored procedures in ABAP and embed stored procedures in ABAP Consume SAP HANA views in ABAP Create a simple SAP HANA view
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 1 Introduction Unit Overview This unit is designed to teach the following topics: • • • •
SAP HANA basics SAP HANA technical concepts Introduction to SAP HANA Studio Introduction to ABAP Development Tools
Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • • •
Describe SAP HANA goals, technical innovations and challenges Understand the fundamental technical concepts of SAP HANA Explain the SAP HANA and ABAP evolution, architecture, and direction Determine if HANA’s row store or column store is used for an ABAP transparent table, and which indices are used on HANA Explain the central functions of HANA Studio Switch between different perspectives in the SAP HANA Studio Set up a connection to a SAP HANA database Understand schemata and tables in SAP HANA Studio Analyze the definition of tables in SAP HANA Studio Use the ABAP Development Tools in Eclipse Describe the Enterprise Procurement Model business example Describe the Open Item Analytics sample applications and which computations it involves
Unit Contents Lesson: SAP HANA Basics and Technical Concepts .........................3 Exercise 1: Log on to ABAP Systems and Create Packages ......... 17 Lesson: Introduction to SAP HANA Studio ................................... 22 Exercise 2: Log on to SAP HANA Studio ................................ 29
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
1
Unit 1: Introduction
HA400
Lesson: Introduction to ABAP Development Tools (ADT) .................. 32 Exercise 3: Create a Project in ABAP Development Tools ............ 41 Lesson: Introduction to the EPM Sample Application....................... 46
2
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Lesson: SAP HANA Basics and Technical Concepts Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • •
Describe SAP HANA goals, technical innovations and challenges Understand the fundamental technical concepts of SAP HANA Explain the SAP HANA and ABAP evolution, architecture, and direction Determine if HANA’s row store or column store is used for an ABAP transparent table, and which indices are used on 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.
SAP HANA Goals
Figure 1: Today's Technology Requires Tradeoff Decisions
Developing applications using technology that pre-dates SAP HANA typically required making several trade-off decisions. The figure shows the five dimensions of requirements that are typical for business applications. These dimensions have been conflicting so far. For example, you had to make trade-off decisions between providing a high-speed application and developing an application that doesn’t require preparing the data in a special way first, for example by calculating aggregations beforehand and by
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
3
Unit 1: Introduction
HA400
storing the results in addition to the base data. Another example is that it was not possible to develop an application which is both real-time and able to analyze a large amount of data, maybe even unstructured data, at the same time.
Figure 2: SAP HANA: Delivers Across 5 Dimensions
SAP HANA tries to deliver across all these 5 dimensions, so that you no longer have to make so many trade-off decisions. In other words, the ambition is to enable developing applications which combine Online Transaction Processing and Online Analytical Processing usage patterns. This leads to certain goals HANA has to meet.
Figure 3: SAP HANA Goals
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, to reduce cost of ownership and to enable new scenarios and applications that were not possible before.
4
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
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, row-based 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 run on SAP HANA without changes. Support For Text Analysis, Indexing and Search An important goal of SAP HANA is to provide powerful analysis, text indexing and search capabilities that support a state-of-the-art search experience. This includes full text search with advanced features such as free style 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 it is required to share a system – 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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
5
Unit 1: Introduction
HA400
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 needs to be transferred between 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. From an ABAP programmer's point of view there are two groups of scenarios: Those where SAP HANA functions as database for an Application Server ABAP and scenarios based on a standalone SAP HANA Server. Naturally, the non-ABAP scenarios are just mentioned here and are not in the focus of this course.
Types of SAP HANA-Based Applications
Figure 4: 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: Those where SAP HANA functions as database for an Application Server ABAP and scenarios based on a standalone SAP HANA Server. Naturally, the non-ABAP scenarios are just mentioned here and are not in the focus of this course: The first type are data warehouses. Typical for them is that data is 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.
6
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
A second type of HANA-based applications are newly-built, native applications developed using SAP HANA Extended Application Services.
Figure 5: SAP HANA as Database for ABAP Applications
Primary concern of this course is to learn how to optimize ABAP applications directly running on SAP HANA, that is application using SAP HANA as the primary database underneath the ABAP stack. A typical example for this kind of application is SAP CRM powered by SAP HANA, or the Business Suite powered by SAP HANA. The course also covers the right-hand type of applications: using SAP HANA to accelerate ABAP applications by putting a separate HANA server besides the ABAP stack, replicating some the ABAP system’s data into HANA, and calling HANA remotely from ABAP to speed up selected reports or transactions.
SAP HANA Innovations and Challenges
Figure 6: What Made SAP HANA Possible?
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
7
Unit 1: Introduction
HA400
Dramatically improved hardware economics and technology innovations in software made it possible for SAP to deliver on its vision of the Real-Time Enterprise with in-memory business applications. Understanding them is important to understand 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, e. g. by minimizing the number of disk blocks (or pages) to be read into main memory when processing a query.In addition, CPUs had a single core, network was far slower etc.
Figure 7: Shift of Performance Bottlenecks
Computer architecture has changed in recent years. Now multi-core CPUs (multiple CPUs on one chip or in one package) are standard, with fast communication between processor cores enabling parallel processing. Main memory is no longer a limited resource, modern servers can have 2TB of system memory and this 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.
8
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Figure 8: New Bottlenecks Become Important – How To Avoid Them?
To fully get the most out of current hardware, the new bottlenecks have to be avoided by addressing two challenges: • •
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.
Column Store versus Row Store
Figure 9: 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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
9
Unit 1: Introduction
HA400
Figure 10: Column Store
Data Compression
Figure 11: Columnar Dictionary Compression
SAP HANA uses different, efficient compression methods such as dictionary encoding, run-length encoding and more. Reduces the amount of memory required. Speeds up operations on columns because the columns can be loaded into the CPU caches faster and with fewer loading cycles. Speeds up operations on columns because many comparisons become integer value comparisons. These are faster than string comparisons, for example.
10
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Partitioning and Parallel Processing
Figure 12: 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.
Figure 13: Using Partitioning To Further Leverage Parallelism
Making 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 managing and processing huge amounts of data.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
11
Unit 1: Introduction
HA400
ABAP Programming for SAP HANA: Evolution and Opportunities
Figure 14: SAP HANA Evolution
What's in it for ABAP Programmers? The new capabilities of SAP HANA offer a huge variety of opportunities for ABAP Developers:
Figure 15: What's in it for ABAP Programmers
12
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Accelerate By optimizing the coding of long running background jobs for SAP HANA, their runtime can be reduced. More jobs can be executed in the same time window, particularly costly tasks are possible in one go rather than splitting them up. Extend In the past, some reports had to be executed in 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. Innovation Finally, with SAP HANA's analysis and calculation capabilities, ABAP developers can design completely new applications that would not have been possible in the past. The arrival of in-memory technology on the database layer also requires a change in the way we design and implement applications:
Figure 16: New Programming Approach
The basic approach of classic ABAP programming was: Keep load from the database Get all the data you need on the application server and do your processing in ABAP
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
13
Unit 1: Introduction
HA400
But 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. Now it becomes “logic to data“ rather than” data to logic”.
Figure 17: Highlights of SAP NetWeaver AS ABAP 7.4 – Overview
ABAP 7.4 provides support for optimizing ABAP applications running on SAP HANA. There are transparent optimizations: These are optimizations you don’t 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 OpenSQL, the implementation of which has been improved. The ABAP language and the OpenSQL 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 other words SQL Script, in ABAP code. Consumption of SAP HANA artifacts has been simplified. For example, you can access SAP HANA columns views through the ABAP Dictionary, that is using OpenSQL. In addition, performance analysis tools have been improved, for example static code checks and the runtime analysis. The ABAP Profiler perspective in the ABAP Development Tools in Eclipse has been enhanced as well. Finally, some re-use components have been extended or optimized for SAP HANA, e.g. the SAP List Viewer (ALV)
14
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
In addition, the ABAP platform team provides guidelines for optimizing ABAP code running on HANA.
Figure 18: ABAP Dictionary Extensions in ABAP 7.4
An example for an ABAP Dictionary extension in ABAP 7.4 is the capability to control which store a table of the ABAP system should live in. 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 to switch between three storage types when running on a SAP HANA database: • • •
2014
Storage type Column Store, which creates the database table in SAP HANA’s column store, or moves it there. Storage type Row Store, which creates the database table in SAP HANA’s row store or moves it there. In principle, this setting can be changed after the table has been created, and the table will be moved into the other store. Note, however, that this may involve re-organizing table contents, should such content exist already. So use this with caution.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
15
Unit 1: Introduction
16
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Exercise 1: Log on to ABAP Systems and Create Packages Exercise Objectives After completing this exercise, you will be able to: • Log on to SAP NetWeaver Application Server ABAP and create a development package
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.
Task 1: Log on to Application Server ABAP with SAP HANA as primary database In SAP GUI, log on to the Application Server ABAP that uses SAP HANA as a primary database. Use the System ID, user and password provided by your instructor. Create development package ZHA400_##, where ## stands for your group ID. 1.
Start SAPlogon and log on to the system labelled NW740 on HANA.
2.
Open 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 button Own Requests to find and use this request).
4.
Start transaction SE11 and open the definition of table “BUT000”. Which of SAP HANA's table stores is used for table “BUT000”? In other words: what is the table's storage type?
5.
Inspect the secondary database indices defined for table “BUT000”. Which of the non-unique indexes are generated when the ABAP system is deployed on an SAP HANA database, and which non-unique indexes are not created on SAP HANA?
6.
What is the main differences between the indexes created on SAP HANA, and those created on other DBMSs?
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
17
Unit 1: Introduction
HA400
Task 2: Log on to other Application Server ABAP with Sybase as primary database In SAP GUI, 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 development package ZHA400_##, where ## stands for your group ID.
18
1.
Start SAPlogon and log on to the system labelled ZME on Sybase.
2.
Open 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 button Own Requests to find and use this request).
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Solution 1: Log on to ABAP Systems and Create Packages Task 1: Log on to Application Server ABAP with SAP HANA as primary database In SAP GUI, log on to the Application Server ABAP that uses SAP HANA as a primary database. Use the System ID, user and password provided by your instructor. Create development package ZHA400_##, where ## stands for your group ID. 1.
Start SAPlogon and log on to the system labelled NW740 on HANA. a)
2.
3.
Open system status and check the system's release and database. a)
From the main menu bar, open System → Status....
b)
In frame SAP System data, press button Component Information to see the installed components and their versions.
c)
In frame Database data check the content of field Database System.
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 button Own Requests to find and use this request). a)
4.
Perform this step as you have (hopefully) done before.
Start transaction SE11 and open the definition of table “BUT000”. Which of SAP HANA's table stores is used for table “BUT000”? In other words: what is the table's storage type? a)
5.
Perform this step as you have (hopefully) done before.
Open Technical Settings, tab DB-Specific Properties. Storage Type is Column Store
Inspect the secondary database indices defined for table “BUT000”. Which of the non-unique indexes are generated when the ABAP system is deployed on an SAP HANA database, and which non-unique indexes are not created on SAP HANA? a)
Return to Display Table, then open Indexes
b)
15 secondary, non-unique indexes are defined for table “BUT000” in the ABAP Dictionary. Of these, the 7 indexes “H6Z, H7D, H7M, HED, HHT, HLT” and “HOL” are only created if the ABAP system runs on SAP HANA. The 8 indexes “ADR, EXT, FRD, GUI, NAM, PER, SRT” and “TOD” are not created if the ABAP system runs on SAP HANA, but only on all other supported DBMSs. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
19
Unit 1: Introduction
6.
HA400
What is the main differences between the indexes created on SAP HANA, and those created on other DBMSs? a)
The indexes created on SAP HANA are all indexes on a single column only. I.e. they don't contain the CLIENT column, and index “H7M” is on the “BU_SORT2” column only, compared to index “SRT” which comprises columns “CLIENT, BU_SORT1” and “BU_SORT2”.
Task 2: Log on to other Application Server ABAP with Sybase as primary database In SAP GUI, 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 development package ZHA400_##, where ## stands for your group ID. 1.
Start SAPlogon and log on to the system labelled ZME on Sybase. a)
2.
Open system status and check the system's release and database. a)
3.
Perform this step as before.
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 button Own Requests to find and use this request). a)
20
Perform this step as before.
Perform this step as before.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA Basics and Technical Concepts
Lesson Summary You should now be able to: • Describe SAP HANA goals, technical innovations and challenges • Understand the fundamental technical concepts of SAP HANA • Explain the SAP HANA and ABAP evolution, architecture, and direction • Determine if HANA’s row store or column store is used for an ABAP transparent table, and which indices are used on HANA
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
21
Unit 1: Introduction
HA400
Lesson: Introduction to SAP HANA Studio Lesson Overview Lesson Objectives After completing this lesson, you will be able to: • • • • •
Explain the central functions of HANA Studio Switch between different perspectives in the SAP HANA Studio Set up a connection to a SAP HANA database Understand schemata and tables in SAP HANA Studio 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.
SAP HANA Studio – An Eclipse Based Tool
Figure 19: SAP HANA Studio – An Eclipse-Based Development Environment
When you start optimizing ABAP applications for SAP HANA, you may have to access the SAP HANA layer, the SAP HANA database server itself, for example to prototype native SQL statements, to look at SAP HANA artifacts like attribute views, column views, or database procedures, or to debug database procedures.
22
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to SAP HANA Studio
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, and also provides tools to administer, monitor and configure SAP HANA systems. These tools are based on existing Eclipse frameworks. SAP chose Eclipse as the platform for an SAP HANA 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. What is Eclipse? 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 plugin 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 make use of the Eclipse platform. These include SAP NetWeaver Visual Composer, the Sybase Unwired Platform and the SAP HANA studio. These include SAP NetWeaver Visual Composer, the Sybase Unwired Platform and the SAP HANA studio. As a result of SAP’s 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.
Figure 20: SAP HANA Studio – Perspectives and Views
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
23
Unit 1: Introduction
HA400
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 for perspectives are: • • •
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 for views are: • • •
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, e.g. the properties of a configured SAP HANA system Job Log – showing the list of recent jobs performed, e.g. imports of development objects, activations etc.
Details of HANA Studio
Figure 21: Most Relevant Perspective For ABAP Developers: Modeler
The Modeler Perspective
24
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to SAP HANA Studio
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 22: System View
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, like database tables and database views. The content contains models, i.e. specific objects that allow an 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, in that they group objects that logically belong together.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
25
Unit 1: Introduction
HA400
Systems – Access to SAP HANA Server
Figure 23: Connecting to an SAP HANA Database
To connect to an SAP HANA system and see the corresponding catalog, content etc., use the Systems view, context menu item Add System ... To add a system, you need: • • • • •
26
Host Name on which the SAP HANA system is installed. Note that this typically is different from the host of the ABAP system Instance Number of the SAP HANA system.Again note that this typically is different from the instance number of the ABAP system Description Database user – also different from your ABAP user Password for the database user
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to SAP HANA Studio
The Catalog – Tables
Figure 24: Tables 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 Content – Packages and Models
Figure 25: SAP HANA Content – Packages, Models, Delivery Units
To develop SAP HANA information models, special types of views and database procedures for optimized read access, you should create your own Content packages.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
27
Unit 1: Introduction
HA400
Transport of SAP HANA Content: Delivery Units To transport of SAP HANA content, packages are assigned to delivery units. Each package may be assigned to one delivery unit only. Navigate to the administration view for delivery units from the Quick Launch view. 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. SAP’s vendor name is “sap.com”. You can assign whole hierarchies of packages to the same delivery unit from within the administration of delivery units. Hint: Alternatively, a delivery unit can be entered in the definition of a package.
28
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to SAP HANA Studio
Exercise 2: Log on to SAP HANA Studio Exercise Objectives After completing this exercise, you will be able to: • Open the SAP HANA Studio and connect to the SAP HANA Server • Create a content package in SAP HANA • Create a delivery unit and assign a package to it
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.
Task 1: Log on to SAP HANA Open the SAP HANA Studio and establish a connection to the SAP HANA Server provided by your instructor. Create content package zha400-##, where ## stands for your group ID. Create delivery unit ZHA400_## and assign your package to it. 1.
Open SAP HANA Studio.
2.
Add a new system. Use the server name, user ID and password provided by your instructor.
Task 2: Create a Content Package and Delivery Unit Create content package zha400-##, where ## stands for your group ID. Create delivery unit ZHA400_## and assign your package to it.
2014
1.
Create the content package.
2.
Create the delivery unit.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
29
Unit 1: Introduction
HA400
Solution 2: Log on to SAP HANA Studio Task 1: Log on to SAP HANA Open the SAP HANA Studio and establish a connection to the SAP HANA Server provided by your instructor. Create content package zha400-##, where ## stands for your group ID. Create delivery unit ZHA400_## and assign your package to it. 1.
Open SAP HANA Studio. a)
2.
Choose Start → All Programs → SAP HANA → SAP HANA Studio from the Windows Start Menu
Add a new system. Use the server name, user ID and password provided by your instructor. a)
Make sure you are in the Modeler perspective. If not, change perspective using the buttons in the upper right-hand corner.
b)
Right-click anywhere in the Systems window on the left and choose Add System....
c)
Enter host name and instance number provided by your instructor and a description, then press button Next >.
d)
Enter user ID and password provided by your instructor, then choose Finish.
Task 2: Create a Content Package and Delivery Unit Create content package zha400-##, where ## stands for your group ID. Create delivery unit ZHA400_## and assign your package to it. 1.
2.
30
Create the content package. a)
In the Systems window, open node Content. Right click on this node and choose New → Package....
b)
Enter the package name and a description, then press button OK.
Create the delivery unit. a)
Open view Quick Launch.
b)
Click on link Delivery Units.
c)
Press the Create... button next to the list of existing delivery units
d)
Enter the name of the delivery unit and your user name as responsible person. Then press Ok.
e)
Press the Add... button next to the (empty) list of packages. Find your package, click on it and press Finish.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to SAP HANA Studio
Lesson Summary You should now be able to: • Explain the central functions of HANA Studio • Switch between different perspectives in the SAP HANA Studio • Set up a connection to a SAP HANA database • Understand schemata and tables in SAP HANA Studio • Analyze the definition of tables in SAP HANA Studio
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
31
Unit 1: Introduction
HA400
Lesson: Introduction to 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.
Lesson Objectives After completing this lesson, you will be able to: •
Use the ABAP Development Tools in Eclipse
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.
Using ABAP Development Tools
Figure 26: ABAP Development Tools for SAP NetWeaver – Architecture
32
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to 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 can capitalize on the usability, speed and flexibility of Eclipse while also benefitting from proven ABAP Workbench features. It’s the best of both worlds. ADT 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. ADT 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 IDE. Note: In addition, ADT is tightly integrated with 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 so that developers use a single Eclipse client, installed locally, that connects to several ABAP back-end systems of different releases using an RFC/REST-based protocol. This allows developers to control all activities in a central location and helps avoid time-consuming 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 ADT, you log onto an SAP backend 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 - 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 container for the development objects that are stored in particular ABAP backend system containing the logon parameters for a particular system logon like: • • •
2014
System Client User and language
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
33
Unit 1: Introduction
HA400
You must be logged onto 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. Note: You can create multiple ABAP projects in Eclipse, each related to a different system.
Figure 27: ABAP Development Tools – Editors
There are two kinds of editors in ADT – those for which there is a “native” Eclipse implementation and others that appear in-place in the SAP GUI. The figure above 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 ADT for ABAP Development, and each developer is free to choose whether to use ADT or the classic ABAP Workbench. The functions and features of Eclipse in general and ADT 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.
34
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Some new functions, however, are only provided within ADT and do not have an equivalent function in the ABAP Workbench. Serveral of these pertain to ABAP development for SAP HANA.
Working with ADT
Figure 28: ABAP Project
Figure 29: Native with Eclipse Look & Feel
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
35
Unit 1: Introduction
HA400
Figure 30: ADT Quick Reference Card
ADT 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 SCN page http://scn.sap.com/community/abap/eclipse/blog/2012/07/02/adt-quick-reference-card. Examples for keyboard shortcuts ABAP developers new to ADT often don‘t find quickly are: • • •
36
Shift+F1 to format the source code, i.e. 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, e.g. a class or method name, adds a link and allows to navigate to the definition or implementation of the object.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Figure 31: Editing Source Code
The source code editor in ADT provides many helpful features, for example: •
• • • • • •
Code completion, which includes keyword completion, using code templates for completion and Content Assist to suggest completions for variable names, method names etc. while typing. Quick Fix, which allows to quickly resolve errors or warnings reported about the code.There are many quick fixes available for ABAP e.g.: 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 … and many, many more.
For a complete list please check the documentation.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
37
Unit 1: Introduction
HA400
Figure 32: Troubleshooting Tools – ABAP Debugger in Eclipse
Debugging ABAP Code The latest ABAP debugger is completely integrated in the Eclipse debug framework. It is an ABAP debugger, but 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 etc. 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. Start the debugger by setting a breakpoint in your code and then run the ABAP program, e.g. start it directly with F8. The debugger offers, among other features editing in the debugger. You can correct a bug right when you find it. Debugging in the IDE is not supported if you are working with a 7.0 EHP3 backend system. For more information please visit the latest information on the Service Market Place.
38
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Figure 33: 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, e.g.: The SAP Software Download Center: http://service.sap.com/swdc, part of the SAP Service Marketplace. 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 the how to install or update the SAP Development Tools for Eclipse using the SAP Development Tools for Eclipse Update Site. Hint: A good idea is also to check the SAP Community Network pages http://scn.sap.com/community/abap/eclipse and http://scn.sap.com/community/abap/hana. They provide documentation and support on how to install the SAP Development Tools for Eclipse.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
39
Unit 1: Introduction
HA400
Figure 34: Installed Features
The About item in the Help menu provides information about installed features and plugins.
Figure 35: Installing and Updating Features
The Check for Updates and Install New Software commands in the Help menu provide the ability to update existing features and to find, download, and install new features (provided you configured suitable update sites in Eclipse).
40
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Exercise 3: Create a Project in ABAP Development Tools Exercise Objectives After completing this exercise, you will be able to: • Open ABAP Development Tools and connect to an Application Server ABAP • Make a development package a favorite in your project
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.
Task 1: Create a Project in ABAP Development Tools Open ABAP Development Tools and create a project in the Application Server ABAP that uses SAP HANA as primary database. Use the System ID, user and password provided by your instructor. Add your development package ZHA400_##, to the favorites of this project. 1.
Open ABAP Development Tools (i.e. ABAP perspective in Eclipse).
2.
Create a project. Use the system ID, user ID and Password provided by your instructor.
3.
Add your package ZHA400_## as a favorite under your project.
4.
Using the ABAP Development Tools, create a report ZHA400_##_HELLO_WORLD, where ## is your group number.
5.
In your report, define a variable lv_name of type STRING with some constant value, and add a simple WRITE statement for this variable. Save the report.
6.
Execute the syntax check via toolbar button (or STRG+F2). Activate and run the report. To run, you can also press F8.
Task 2: Debug a report using ABAP Development Tools 1.
Set a breakpoint in your report.
2.
Run the report again. This should result in a popup asking if you want to switch to the Debug perspective. Choose Yes. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
41
Unit 1: Introduction
42
HA400
3.
Inspect the value of variable lv_name.
4.
Resume execution.
5.
Close the Debug perspective.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Solution 3: Create a Project in ABAP Development Tools Task 1: Create a Project in ABAP Development Tools Open ABAP Development Tools and create a project in the Application Server ABAP that uses SAP HANA as primary database. Use the System ID, user and password provided by your instructor. Add your development package ZHA400_##, to the favorites of this project. 1.
2.
3.
4.
5.
Open ABAP Development Tools (i.e. ABAP perspective in Eclipse). a)
Open SAP HANA Studio.
b)
Change to the ABAP perspective using the pushbuttons in the upper right-hand corner.
Create a project. Use the system ID, 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)
Use the value help to choose one of the available connections and press the Next > button
c)
Enter the client, user and password given to you by your instructor and press the Finish button
Add your package ZHA400_## as a favorite under your project. a)
In the Project Explorer, right click on Favorite Packages under your project and choose Add a Package....
b)
Enter the name of your package and press the Ok button.
Using the ABAP Development Tools, create a report ZHA400_##_HELLO_WORLD, where ## is your group number. a)
Select your package in the list of favorite packages, and choose context menu item New → ABAP Program.
b)
Enter report name and description.
In your report, define a variable lv_name of type STRING with some constant value, and add a simple WRITE statement for this variable. Save the report. a)
Write the report code as usual.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
43
Unit 1: Introduction
6.
HA400
Execute the syntax check via toolbar button (or STRG+F2). Activate and run the report. To run, you can also press F8. a)
Press the toolbar button Check ABAP Development Object (or Ctrl+F2).
b)
Press the toolbar button Activate ABAP Development Object (or Ctrl+F3).
c)
Press the toolbar button Run As ... or F8. Select ABAP Application in the popup.
Task 2: Debug a report using ABAP Development Tools 1.
Set a breakpoint in your report. a)
2.
3.
Run the report again. This should result in a popup asking if you want to switch to the Debug perspective. Choose Yes. a)
Press the toolbar button Run As ... or F8.
b)
In the Confirm Perspective Switch popup, choose Yes.
Inspect the value of variable lv_name. a)
4.
Press the toolbar button Resume or F8.
Close the Debug perspective. a)
44
The variable can be inspected in the Debug perspective, top-right view.
Resume execution. a)
5.
Double-click in the grey column of a code line in the editor window to set the breakpoint.
Open the context menu of the Debug perspective icon (top-right toolbar button) and choose item Close, or choose menu item Window → Close Perspective.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to ABAP Development Tools (ADT)
Lesson Summary You should now be able to: • Use the ABAP Development Tools in Eclipse
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
45
Unit 1: Introduction
HA400
Lesson: Introduction to the EPM Sample Application Lesson Overview This lesson introduces • •
The Enterprise Procurement Model business example And the Open Item Analytics sample applications on which many of the exercises are based
Lesson Objectives After completing this lesson, you will be able to: • •
Describe the Enterprise Procurement Model business example Describe the Open Item Analytics sample applications and which computations it involves
Business Example 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 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. Your company ITeLO wants you to improve the performance of this application considerably, by making use of SAP HANA.
Enterprise Procurement Model (EPM) The ITeLO example described is part of a larger sample business scenario called Enterprise Procurement Model. This scenario has been introduced in SAP NetWeaver ABAP as a reference and show case for how to use newer technologies. Most SAP HANA courses use this scenario, and that‘s why it will also be used during a large part of this course. Because ITeLO both sells and buys hardware, its full set of applications includes a sales part, a procurement part, and master data management. This is reflected in the data model, which includes Sales Orders, Goods Issues, Customer Invoices on the sales side, similar entities on the procurement side, and master data entities like stock, business partners (customers and suppliers) and products.
46
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to the EPM Sample Application
Figure 36: The Enterprise Procurement Model Demo Scenario
As this course focusses on the sales and customer management part, having a closer look at the related master data and document data models is sufficient.
Figure 37: Master Data – Product and Business Partner
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
47
Unit 1: Introduction
HA400
Figure 38: Document Data – Sales Order And Invoice
It allows switching between different ways how the analysis can be implement, especially in an ABAP system running on SAP HANA.
Figure 39: The Open Item Analytics Demo Application
One of ITeLO’s applications, the Open Item Analytics application, serves as the basis for many of the exercises that follow. The application determines, for each customer, the average age of the open (=unpaid) invoices, the total open invoice amount in €, and uses threshold values for both measures to propose which customer should receive a payment reminder. The original show case application can be started using transaction code SEPM_OIA, or using Web Dynpro application S_EPM_OIA_WD.
48
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Introduction to the EPM Sample Application
Figure 40: Computations in the Open Item Analytics Demo Application
The application has to perform three computation steps, the first two of which are data-intensive and take considerably time when implemented the classical way in ABAP.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
49
Unit 1: Introduction
HA400
Lesson Summary You should now be able to: • Describe the Enterprise Procurement Model business example • Describe the Open Item Analytics sample applications and which computations it involves
50
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Unit Summary
Unit Summary You should now be able to: • Describe SAP HANA goals, technical innovations and challenges • Understand the fundamental technical concepts of SAP HANA • Explain the SAP HANA and ABAP evolution, architecture, and direction • Determine if HANA’s row store or column store is used for an ABAP transparent table, and which indices are used on HANA • Explain the central functions of HANA Studio • Switch between different perspectives in the SAP HANA Studio • Set up a connection to a SAP HANA database • Understand schemata and tables in SAP HANA Studio • Analyze the definition of tables in SAP HANA Studio • Use the ABAP Development Tools in Eclipse • Describe the Enterprise Procurement Model business example • Describe the Open Item Analytics sample applications and which computations it involves
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
51
Unit Summary
52
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 2 Taking ABAP to SAP HANA Unit Overview This unit is designed to teach the following topics: • • •
Access the SAP HANA Database using Open SQL and a secondary database connection Optimize Open SQL access to SAP HANA Performance rules and guidelines for SAP HANA
Unit Objectives After completing this unit, you will be able to: • • • • • • •
Describe how to access the SAP HANA Database by using Open SQL and a secondary database connection Use Code Inspector (SCI) and ABAP Test Cockpit (ATC) to locate potential functional and performance issues. Use the ABAP Trace (SAT) and the ABAP Profiling perspective to measure and compare runtime consumption Use the SQL Monitor (SQLM) to identify most important database access Use the Performance Tuning Worklist (SWLT) to combine static and dynamic performance analysis results Use SQL Trace (ST05) for in depth analysis of database accesses Understand the performance rules and guidelines for ABAP on SAP HANA
Unit Contents Lesson: SAP HANA as Secondary Database – Access via Open SQL .. 55 Exercise 4: Access SAP HANA Via a Secondary Database Connection ................................................................... 59 Lesson: Preparing for SAP HANA ............................................. 69 Exercise 5: Improve Open SQL Using ABAP Test Cockpit (ATC) .... 79 Lesson: Guided Performance Analysis ....................................... 90 Exercise 6: Use the SQL Performance Tuning Worklist to Analyze Static and Runtime Check Results ........................................ 99
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
53
Unit 2: Taking ABAP to SAP HANA
HA400
Exercise 7: Improve Open SQL Statements Using The SQL Trace (ST05) ........................................................................105 Lesson: Performance Rules and Guidelines for SAP HANA.............. 114
54
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
Lesson: SAP HANA as Secondary Database – Access via Open SQL Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Describe 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.
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. Besides this primary database connection it is possible to establish connections to additional database management systems, so called 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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
55
Unit 2: Taking ABAP to SAP HANA
HA400
Figure 41: Transaction DBACOCKPIT
Figure 42: Secondary database connections, among other things, are created and maintained via transaction DBACOCKPIT. Each database connection is identified by name that has to be unique within the application server.
56
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
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.
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 addition CONNECTION which has to be followed by the name of the secondary database connection.
Figure 43: Open SQL Using Secondary Database Connection
But some restrictions apply, when using Open SQL to access a secondary database.
Figure 44: Open SQL over Secondary DB Connection – Restrictions
Because of the syntax check for Open SQL statements, the tables and fields the statement refers to, need to exist in the ABAP Dictionary of the application server.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
57
Unit 2: Taking ABAP to SAP HANA
HA400
This implies, that objects only known to SAP HANA (e.g. SAP HANA views or procedures) are not accessible by open SQL. Note: We will 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.
58
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
Exercise 4: Access SAP HANA Via a Secondary Database Connection Exercise Objectives After completing this exercise, you will be able to: • Understand how secondary database connections are maintained and tested • Understand the prerequisites for accessing tables of the secondary database via open SQL
Business Example 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 the Application Server ABAP that does not have SAP HANA as a primary database. 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.
Start SAP Logon and log on to the system labelled ZME on Sybase.
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench request.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
59
Unit 2: Taking ABAP to SAP HANA
HA400
3.
Analyze the source code of the program. Which are the two main parts of the data processing. In which processing blocks are they encapsulated?
4.
The data comes from database tables
and . All columns but one come from database table (column ). The remaining column is the result of a calculation. As input, this calculation uses two fields. These fields are and of table . The calculated column returns the of . Fill in the blanks to complete the sentence.
5.
Activate the program.
Task 2: Analyze 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 which have been maintained in your AS ABAP. Note: You do not need to change anything.
2.
Find a database connection that points to your SAP HANA server and note down the DB user and connection name.
3.
The connection name is HANA server is
and the DB user for the SAP .
Fill in the blanks to complete the sentence.
4.
Go to SAP HANA Studio and open the schema with the same name as the user in the database connection.
Continued on next page
60
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
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 andRS_ are technical objects and should not be considered here. They are used by the mechanism that replicates data from primary to secondary database.
6.
Which are the tables that 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 addition CONNECTION to access the secondary database rather than the primary database. Hint: Instead of hard coding the connection, it is recommended to define a constant of type dbcon_name (ABAP Dictionary data element).
3.
2014
Activate and test your program.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
61
Unit 2: Taking ABAP to SAP HANA
HA400
Solution 4: Access SAP HANA Via a Secondary Database Connection Task 1: Copy and understand templates In SAP GUI, log on to the Application Server ABAP that does not have SAP HANA as a primary database. 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.
Start SAP Logon and log on to the system labelled ZME on Sybase. a)
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench request. a)
3.
Perform this step as before.
Complete this step as you learned to do in previous classes.
Analyze the source code of the program. Which are the two main parts of the data processing. In which processing blocks are they encapsulated? Answer: 1. 2.
4.
Reading from the database and computing a list of customers, subroutine get_data_template. displaying the list of customers, subroutine display.
The data comes from database tables SNWD_BPA and SNWD_SO_INV_HEAD. All columns but one come from database table SNWD_BPA (column CREATED_AT). The remaining column is the result of a calculation. As input, this calculation uses two fields. These fields are LV_CURRENT_DATE and CREATED_AT of table SNWD_SO_INV_HEAD. The calculated column returns the average age of open sales order invoices. Answer: SNWD_BPA, SNWD_SO_INV_HEAD, SNWD_BPA, CREATED_AT, LV_CURRENT_DATE, CREATED_AT, SNWD_SO_INV_HEAD, average age, open sales order invoices
5.
Activate the program. a)
Complete this step as you learned to do in previous classes.
Continued on next page
62
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
Task 2: Analyze 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 which have been maintained in your AS ABAP. Note: You do not need to change anything.
2.
3.
a)
Start transaction DBACOCKPIT.
b)
In the navigation area on the left, click on button Database Connections.
Find a database connection that points to your SAP HANA server and note down the DB user and connection name. a)
On the list on the right, expand node SAP HANA database to find all database connections that point to a SAP HANA database.
b)
Find the connection with the correct server in column DB Host.
The connection name is HANADB and the DB user for the SAP HANA server is REPZME. Answer: HANADB, REPZME
4.
5.
Go to SAP HANA Studio and open the schema with the same name as the user in the database connection. a)
In SAP HANA Studio, open perspective Modeler.
b)
In the Navigation window on the left, open Catalog → REPZME.
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 andRS_ are technical objects and should not be considered here. They are used by the mechanism that replicates data from primary to secondary database. a)
6.
Under schema REPZME, open node tables.
Which are the tables that are of interest to the application programmer? Answer: MARA, SBOOK, SCARR, SCUSTOM, SFLIGHT, SPFLI, STRAVELAG, SNWD_AD, SNWD_BPA, SNWD_BPA_CONTACT, SWND_PD; SNWD_SO, SNWD_SO_I, SNWD_SO_INV_HEAD, SNWD_SO_INV_ITEM, SNWD_TEXTS, SNWD_TEXT_KEY
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
63
Unit 2: Taking ABAP to SAP HANA
7.
HA400
Verify for at least one table that the definition in the SAP HANA database is identical to the definition in the primary database. a)
Double-click on one of the tables to see the list of fields, their SQL data types and dimensions.
b)
On the AS ABAP, open the definition of this table in the ABAP Dictionary (transaction SE11 or SE80).
c)
From the menu choose Utilities → Database Object → Display to see the definition of this table on 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. Use the Copy & Paste functions of the ABAP Editor.
a) 2.
In subroutine get_data_solution, search for all SELECT-statements and use addition CONNECTION to access the secondary database rather than the primary database. Hint: Instead of hard coding the connection, it is recommended to define a constant of type dbcon_name (ABAP Dictionary data element). a)
3.
See source code extract from model solution.
Activate and test your program. a)
Complete this step as you learned to do in previous classes.
Result
Source code extract from model solution (Program HA400_SEC_DB_CON_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------*
Continued on next page
64
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE snwd_bpa, ls_invoice TYPE snwd_so_inv_head. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT * FROM snwd_bpa INTO ls_partner. ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
* CLEAR: ls_customer-avg_days_open, lv_count. SELECT * FROM snwd_so_inv_head INTO ls_invoice WHERE buyer_guid = ls_partner-node_key AND payment_status 'P'. ls_customer-avg_days_open = ls_customer-avg_days_open abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_invoice-created_at ) / 86400. lv_count = lv_count + 1. ENDSELECT. IF ls_customer-avg_days_open 0.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
65
Unit 2: Taking ABAP to SAP HANA
HA400
ls_customer-avg_days_open = ls_customer-avg_days_open /
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 USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE snwd_bpa, ls_invoice TYPE snwd_so_inv_head. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT * FROM snwd_bpa CONNECTION (pv_dbcon) INTO ls_partner. ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
Continued on next page
66
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: SAP HANA as Secondary Database – Access via Open SQL
* CLEAR: ls_customer-avg_days_open, lv_count. SELECT * FROM snwd_so_inv_head CONNECTION (pv_dbcon) INTO ls_invoice WHERE buyer_guid = ls_partner-node_key AND payment_status 'P'. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_invoice-created_at ) / 86400. lv_count = lv_count + 1. ENDSELECT. IF ls_customer-avg_days_open 0. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers. ENDIF. ENDSELECT. SORT ct_customers BY id. ENDFORM.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
67
Unit 2: Taking ABAP to SAP HANA
HA400
Lesson Summary You should now be able to: • Describe how to access the SAP HANA Database by using Open SQL and a secondary database connection
68
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Lesson: Preparing for SAP HANA Lesson Overview This lessons introduces some tools to analyze potential functional and performance issues in ABAP programs when migrating to SAP HANA
Lesson Objectives After completing this lesson, you will be able to: • •
Use Code Inspector (SCI) and ABAP Test Cockpit (ATC) to locate potential functional and performance issues. Use the ABAP Trace (SAT) and the ABAP Profiling perspective to measure and compare runtime consumption
Business Example You identified an ABAP program the performance of which can and should be improved. As a next step, you want to analyze why the program does not perform as well as desired, to conclude how its performance can be improved.
Considerations before migrating to SAP HANA
Figure 45: ABAP Developer‘s Questions: SAP HANA Impact on Custom ABAP Code
Most likely, you think about SAP HANA because you want to improve your ABAP applications’ performance. 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 re-write ABAP code. SAP tools and guidelines help for each of the above questions to get your custom code ready for and optimized for SAP HANA.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
69
Unit 2: Taking ABAP to SAP HANA
HA400
Figure 46: Migrating to SAP HANA May Affect Existing DB Specific ABAP Code
Migrating to SAP HANA is similar to other database migrations in that some technical changes may affect existing ABAP coding. But in general, no changes are necessary if your SQL code follows the golden Open SQL rules. Use static checks to find SQL patterns that violate the golden Open SQL.
Figure 47: Avoid Potential Functional Issues: Examples for Mandatory Adaptations
Standard ABAP code is fully portable between different database types. However, it is also possible to make use of database specific features explicitly or implicitly. In such situations, the code has to be revisited when migrating to SAP HANA.
70
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Some concrete scenarios: •
•
If ABAP code makes use of native SQL (e.g. via ADBC or EXEC SQL), this code must be checked and adapted. The ADBC example in the figure uses the proprietary ROWNUM pseudo column offered by some databases as an iterator to count over a result set. As this is not supported in this form in the SQL dialect of SAP HANA, this coding needs to be adapted. A second example are hints to the database, respectively the database interface. They allow to optimize query execution for specific databases. In the example shown a specific behavior for treating the FOR ALL ENTRIES clause is defined for Microsoft SQL Server. Such hints will be ignored after a database migration e.g. 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.
Figure 48: Avoid Potential Functional Issues: Examples for Mandatory Adaptations
There are more subtle scenarios. Although Open SQL is database independent, it is possible to rely on unspecified behavior or internals. For instance, when SELECTing data, the result is not sorted unless explicit sort criteria are defined using the ORDER BY clause. But a certain sorting can be observed for some databases (e.g. by primary key or a specific secondary key), which existing code may rely on mistakenly. There is no guarantee that subtle problems can arise after database migration, e.g. when accessing the result table via an READ TABLE statement using BINARY SEARCH assuming a sorted table. Whenever selecting data which should be sorted, the ORDER BY clause must be used (independently of SAP HANA). This also applies to the special case of Pool/Cluster tables which are transformed into transparent tables on SAP HANA. More exotic scenarios are if the physical clusters/pool are accessed or program code depends explicitly on existence of indices. Such cases must also be checked and most likely adapted after migration.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
71
Unit 2: Taking ABAP to SAP HANA
HA400
Performance Considerations
Figure 49: Transitioning ABAP Code to SAP HANA – Performance Considerations
In addition to enabling an existing component, a central goal of using SAP HANA is to accelerate performance and to fully benefit from HANA. In many situations existing ABAP code might run faster immediately after a migration to HANA. However, there can also be situations where existing code is negatively impacted, especially if the classical performance recommendations were not taken into account. In general, we can say that well-written ABAP code has a good chance to immediately run better on SAP HANA. A first step to detect code that would lead to functional or performance issues when migrating to SAP HANA is to run a static code analysis.
72
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Figure 50: ABAP Code Inspector and ABAP Test Cockpit
The ABAP Code Inspector can perform a whole range of static functional and performance checks. The existing rules and guidelines checked by Code Inspector are as valid for SAP HANA as they are for other databases. With SAP NetWeaver 7.40, several additional checks were added which are particularly important with regard to SAP HANA (although again, they are valid for other databases too). Many of these checks have been downported into lower releases. Three performance check examples are: • • •
SELECTS in LOOPs across modularization units Problematic SELECT * statements (where less than a certain percentage of the fields are subsequently used) Find SELECT…FOR ALL ENTRIES statements that can be replaced by a join
All three new checks have documentation available describing how the check works, and the meaning of the check parameters which can be maintained. When creating a check variant including the new performance checks, remember to check the parameters, and if necessary change them. The check parameters are documented in case you are not sure what they represent. Example: The Check for Problematic SELECT * Statements The check for problematic SELECT * statements in particular has several check parameters. This check searches for SELECT * FROM dbtab statements where less than a specified percentage of the fields are effectively used. The default value for the percentage is 20 percent. If less than 20 percent of the fields are
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
73
Unit 2: Taking ABAP to SAP HANA
HA400
used it is more efficient to select only the used fields. The value if this parameter highly depends on the database used. When on a database with column store, e.g. SAP HANA, this value should be set to a lower value than on a traditional, row store only database. Inspection Result The following figure shows an example of the inspection result where two of the new checks have resulted in an error message. Remember, you can double-click on the message to navigate to the problem code.
Figure 51: Code Inspector And ATC – Inspection Results
Figure 52: ABAP Test Cockpit
74
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
With ABAP 7.02, ABAP Test Cockpit (ATC) was introduced as a holistic quality assurance tool. If you know the ABAP Code Inspector, then rest assured: the ABAP Test Cockpit integrates the code inspector, including the configuration of check variants. The ATC offers more, in particular flexibly scheduling check runs, distribution of results and in general support for quality management processes. ATC is • •
Integrated into ABAP Development Tools and ABAP Workbench Integrates with SAP Solution Manager
The ATC checks can be used to detect certain kinds of issues in the context of ABAP on SAP HANA, e.g. • •
ABAP source code which should be analyzed before a database migration ABAP source code with performance optimization potential
The checks performed by the ABAP Test Cockpit can be configured. Standard configuration is that it reuses the ABAP Code Inspector checks, check variant DEFAULT. The check variant used may have to be adjusted to make sure all checks relevant for SAP HANA are performed.
Figure 53: Runtime Analysis: ABAP Trace
Once you identified ABAP code the performance of which can be improved, analyzing the runtime behavior can be very helpful. This shows if the critical code is executed at all, helps to understand where the performance issue originates from, and measure the improvement after the code is adapted.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
75
Unit 2: Taking ABAP to SAP HANA
HA400
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 Runtime Analysis (SE30). • • •
The functions of the classic Runtime Analysis (SE30) and the new ABAP Trace (SAT) can be completely used in the HANA Context Both tools measure runtime of processing blocks (methods, functions, subroutines) or single statements No database-specific functions are available
Figure 54: Runtime Analysis: ABAP Profiling Perspective in ABAP Development Tools
When using the ABAP Development Tools in Eclipse, an alternative to using the SAP GUI-based ABAP Trace is to use a dedicated perspective in ADT, 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 be analyzed in the other tool as well.
76
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Depending on which configuration is used to generate a trace, the ABAP Profiling perspective provides different views: • • • •
An overview, which 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, for example: –
•
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 form of a diagram. In general, information shown in this graphical view corresponds to the one in the Call Tree view. The horizontal of the diagram displays the temporal sequence of each trace event measured, whereas the horizontal represents the call depth within a call hierarchy. In contrast to the Call Tree, the trace events however are represented not as discrete tree nodes, but as a continuous sequence.The advantage of 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).
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
77
Unit 2: Taking ABAP to SAP HANA
78
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Preparing for SAP HANA
Exercise 5: Improve Open SQL Using ABAP Test Cockpit (ATC) Exercise Objectives After completing this exercise, you will be able to: • Analyze a program with the ABAP Test Cockpit (ATC), respectively Code Inspector (SCI), to detect potential performance problems • Analyze the improved program • Quantify the improvement with the ABAP Trace (SAT)
Business Example Template: Report HA400_OPT_OSQL_S1
Task 1: Copy and understand template Create a copy of report HA400_OPT_OSQL_S1 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.
Task 2: Analyze Review Code Inspector variant HA400 to verify that it is suitable for a static performance analysis. Analyze your copy of program HA400_OPT_OSQL_S1 with the ABAP Test Cockpit to identify potential performance problems. 1.
Analyze global check variant HA400 for the Code Inspector. Make sure that all performance checks are active in the check variant.
2.
Perform an ATC run of your program based on the check variant HA400.
3.
Analyze the inspection result. Navigate to the ABAP Source Code. What can be done about the reported issue?
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
79
Unit 2: Taking ABAP to SAP HANA
HA400
4.
In the search for problematic SELECT *-statements you should find an error related to database table SNWD_BPA and an error related to database table SNWD_SO_INV_HEAD. Looking at the check in the check variant, why could errors related to problematic SELECT*-statements from other database tables be missing?
5.
How would you improve the two pieces of code reported by the search for problematic SELECT *-statements?
6.
Which fields of table SNWD_BPA are actually needed?
7.
Which fields of table SNWD_SO_INV_HEAD are actually needed?
Continued on next page
80
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Task 3: Analyze Improvement Fortunately, the program already contains the improved code in subroutine get_data_solution. Understand the improved code. 1.
The static code check also resulted in check messages about nested SELECT statements. How does subroutine get_data_solution addresses these messages as well?
2.
Why is it important to define the two tables as sorted tables?
Task 4: Quantify Improvement perform a runtime measurement with the ABAP Trace (SAT) or the ABAP Profiling perspective of the ABAP Development Tools for Eclipse. Compare the runtime consumption of subroutine get_data_template and subroutine get_data_solution. 1.
Perform a runtime measurement with the ABAP Trace (SAT) or the ABAP Profiling perspective and compare the gross runtime of the two subroutines.
2.
On SAP HANA, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Fill in the blanks to complete the sentence.
3.
Repeat the runtime measurement with data retrieval from the primary database.
4.
On the primary database, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Fill in the blanks to complete the sentence.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
81
Unit 2: Taking ABAP to SAP HANA
HA400
Solution 5: Improve Open SQL Using ABAP Test Cockpit (ATC) Task 1: Copy and understand template Create a copy of report HA400_OPT_OSQL_S1 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)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Analyze Review Code Inspector variant HA400 to verify that it is suitable for a static performance analysis. Analyze your copy of program HA400_OPT_OSQL_S1 with the ABAP Test Cockpit to identify potential performance problems. 1.
2.
Analyze global check variant HA400 for the Code Inspector. Make sure that all performance checks are active in the check variant. a)
Start transaction SCI.
b)
In the frame Check Variant, press the button with the person icon to switch to global variants. Enter the check variant name HA400 and click the Display button.
c)
In the check variant, make sure all Performance Checks are selected.
Perform an ATC run of your program based on the check variant HA400. a)
In the Repository Browser object tree, right-click your program and choose menu item Check → ABAP Test Cockpit With ....
b)
In frame Options, enter HA400 as the name of the Code Inspector Check Variant.
c)
On the toolbar, click on the button labelled Execute Checks.
Continued on next page
82
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
3.
4.
Analyze the inspection result. Navigate to the ABAP Source Code. What can be done about the reported issue? a)
Check the reported errors. Double click a message to see the corresponding documentation. Navigate to the ABAP source code by clicking on the Object Name, and then double-clicking one of the message text lines.
b)
Read the check documentation to get hints on how the program could be improved.
In the search for problematic SELECT *-statements you should find an error related to database table SNWD_BPA and an error related to database table SNWD_SO_INV_HEAD. Looking at the check in the check variant, why could errors related to problematic SELECT*-statements from other database tables be missing? Answer: 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. Fortunately, the default value is sufficient in case of the exercise. You may have to adjust it in general.
5.
How would you improve the two pieces of code reported by the search for problematic SELECT *-statements? Answer: Replace the asterisk in the SELECT * statements with the explicit list of fields needed in the ABAP code.
6.
Which fields of table SNWD_BPA are actually needed? Answer: NODE_KEY, BP_ID, COMPANY_NAME
7.
Which fields of table SNWD_SO_INV_HEAD are actually needed? Answer: BUYER_GUID, CREATED_AT
Task 3: Analyze Improvement Fortunately, the program already contains the improved code in subroutine get_data_solution. Understand the improved code. 1.
The static code check also resulted in check messages about nested SELECT statements. How does subroutine get_data_solution addresses these messages as well? Answer: The subroutine defines two internal tables lt_partner and lt_invoice, with line types lty_s_partner and lty_s_invoice containing the fields to be selected only. It reads all business partners and all unpaid invoices into these internal tables, and replaces the SELECT-loops with LOOPs over the internal tables.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
83
Unit 2: Taking ABAP to SAP HANA
2.
HA400
Why is it important to define the two tables as sorted tables? Answer: Otherwise the runtime environment would not be able to optimize the loops over these tables and we would loose a lot of runtime by searching for the necessary entries.
Task 4: Quantify Improvement perform a runtime measurement with the ABAP Trace (SAT) or the ABAP Profiling perspective of the ABAP Development Tools for Eclipse. Compare the runtime consumption of subroutine get_data_template and subroutine get_data_solution. 1.
Perform a runtime measurement with the ABAP Trace (SAT) or the ABAP Profiling perspective and compare the gross runtime of the two subroutines. a)
Start transaction SAT .
b)
Enter the name of your program and, if necessary, the name of the variant (DEFAULT).
c)
Press Execute, fill in the selection screen and press Execute again.
d)
If you want to use the ABAP Profiling perspective instead of the ABAP trace, create an ABAP Project for the ABAP System that does not use SAP HANA as primary database. Then open perspective ABAP Profiling (Window → Open Perspective → ABAP Profiling or Window → Perspective → Other → ABAP Profiling or use the Open Perspective toolbar button. Open your program into the editor. Choose menu item Window → Preferences → ABAP Development → Profiling and select radio button Perform aggregated measurement? → Yes, hit list is sufficient. Press OK. Choose menu item Run → Profile As ... → ABAP Application. Fill in the selection screen (Subroutine Solution and Secondary connection) and press “Execute”
2.
On SAP HANA, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Answer:
3.
Repeat the runtime measurement with data retrieval from the primary database. a)
Execute the runtime analysis as before but this time, choose option Primary Database on the report's selection screen. Continued on next page
84
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
On the primary database, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %.
4.
Answer:
Result
Source code extract from model solution (Program HA400_OPT_OSQL_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------* FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE snwd_bpa, ls_invoice TYPE snwd_so_inv_head. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT * FROM snwd_bpa CONNECTION (pv_dbcon) INTO ls_partner.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
85
Unit 2: Taking ABAP to SAP HANA
HA400
ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
* CLEAR: ls_customer-avg_days_open, lv_count. SELECT * FROM snwd_so_inv_head CONNECTION (pv_dbcon) INTO ls_invoice WHERE buyer_guid = ls_partner-node_key AND payment_status 'P'. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_invoice-created_at ) / 86400. lv_count = lv_count + 1. ENDSELECT. IF ls_customer-avg_days_open 0. ls_customer-avg_days_open = ls_customer-avg_days_open /
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 USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** TYPES: BEGIN OF lty_s_partner, node_key
TYPE snwd_bpa-node_key,
bp_id
TYPE snwd_bpa-bp_id,
company_name TYPE snwd_bpa-company_name, END OF lty_s_partner. TYPES: BEGIN OF lty_s_invoice,
Continued on next page
86
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
buyer_guid
TYPE snwd_bpa-node_key,
created_at
TYPE snwd_so-created_at,
END OF lty_s_invoice. * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE lty_s_partner, lt_partner TYPE SORTED TABLE OF lty_s_partner WITH UNIQUE KEY bp_id, ls_invoice TYPE lty_s_invoice, lt_invoice TYPE SORTED TABLE OF lty_s_invoice WITH NON-UNIQUE KEY buyer_guid. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT node_key bp_id company_name FROM snwd_bpa CONNECTION (pv_dbcon) INTO TABLE lt_partner. SELECT buyer_guid created_at FROM snwd_so_inv_head CONNECTION (pv_dbcon) INTO TABLE lt_invoice WHERE payment_status 'P'. LOOP AT lt_partner INTO ls_partner. ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
* CLEAR: ls_customer-avg_days_open, lv_count. LOOP AT lt_invoice INTO ls_invoice WHERE buyer_guid = ls_partner-node_key.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
87
Unit 2: Taking ABAP to SAP HANA
HA400
ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_invoice-created_at ) / 86400. lv_count = lv_count + 1. ENDLOOP. IF ls_customer-avg_days_open > 0. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers. ENDIF. ENDLOOP. *
SORT ct_customers BY id. " already sorted
ENDFORM.
88
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Preparing for SAP HANA
Lesson Summary You should now be able to: • Use Code Inspector (SCI) and ABAP Test Cockpit (ATC) to locate potential functional and performance issues. • Use the ABAP Trace (SAT) and the ABAP Profiling perspective to measure and compare runtime consumption
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
89
Unit 2: Taking ABAP to SAP HANA
HA400
Lesson: Guided Performance Analysis Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • •
Use the SQL Monitor (SQLM) to identify most important database access Use the Performance Tuning Worklist (SWLT) to combine static and dynamic performance analysis results 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.
Best Practice when transitioning ABAP code for SAP HANA Instead of analyzing each ABAP program individually, a good practice when transitioning and optimizing ABAP applications to SAP HANA is to follow a three-step approach.
Figure 55: Steps to Transition ABAP Code for HANA
90
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
First step is to detect those places where performance can or should be improved, and analyze and prioritize the findings based on the importance of the places detected. Next step is to optimize the existing code, using the prioritized list. An optional last step is to use the new potential and features to re-design and innovate on custom business processes.
Figure 56: Guided Performance Optimization
The first two steps are supported by several tools, which in total result in a guided performance optimization procedure. •
• • •
2014
Static code check tools such as Code Inspector and ABAP Test Cockpit to find pieces of code using known critical constructs, e.g. deviations from the classical performance recommendations. Tools analyzing performance at run-time, to determine if critical constructs really cause issues at run-time, for example the ABAP Trace. A new tool called SQL Monitor to determine the priority if different programs access the database intensively. Finally, a new tool called SQL Performance Tuning Worklist combining the results of static and run-time analyses to create a prioritized worklist.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
91
Unit 2: Taking ABAP to SAP HANA
HA400
Determining an ABAP System's SQL Profile: SQL Monitor
Figure 57: 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, etc. This includes how often each request was executed, which tables were accessed, the total runtime, how many records were fetched, and more. The SQL Monitor is a new development with ABAP 7.4. However, in order to support using it also before a migration, it is also offered as part of the so-called ST-PI support Add-On provided by SAP Active Global Support.
Figure 58: The New ABAP SQL Monitor – Architecture
92
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
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 Monitors 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 (e.g. transaction, source code position, accessed tables, etc.) using the runtime monitor infrastructure (file based). This data is transferred periodically to the SQL Monitor database tables (e.g. every 24 hours; manual refresh possible). The transfer is required for data analysis and in order 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.
Figure 59: Switching the SQL Monitor On and Viewing SQL Monitor Data
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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
93
Unit 2: Taking ABAP to SAP HANA
HA400
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 (e.g. transaction VA01, Web Dynpro Application ) resp. request type (ie. URL, RFC, Report, etc.). You can also define a filter for looking into accesses to concrete database tables. You can select a certain aggregation type and an sorting of the result list.
Figure 60: Exporting and Importing SQL Monitor Snapshots
As the SQL Monitor should collect data in a productive system, and the code optimizations are usually planned in another system, e.g. 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 nice visualizations and more complex analytical operations.
94
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
Creating a Prioritized Worklist
Figure 61: SQL Performance Tuning Worklist – Motivation
Finally, for performance optimization it makes sense to combine the results of both static source code analysis (carried out via the ABAP Test Cockpit / Code Inspector) and the SQL Monitor runtime data. This correlation can be done in another new tool, the SQL Performance Tuning Work list. This tools can be used to create a ranking based on cost and benefit of a potential optimization.
Figure 62: SQL Performance Tuning Worklist – Usage
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
95
Unit 2: Taking ABAP to SAP HANA
HA400
In-depth Analysis of Performance Issues Before starting to optimize ABAP code detected and prioritized using the SQL Performance Worklist, you may have to perform a detailed run-time analysis to better understand where the performance issue originates from.
Figure 63: Detailed Analysis: ABAP Trace or ABAP Profiling Perspective
For a full runtime analysis, you can use the ABAP Trace (SAT) or the ABAP Profiling perspective in the ABAP Development Tools for Eclipse.
Figure 64: Runtime Analysis: SQL Trace
Another tool for runtime performance analysis is the SQL Trace (ST05). This tool in particular analyses database accesses. It can thus 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 performance issues.
96
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
Figure 65: Performance Trace
Figure 66: Execution Plan
Hint: Note that the Explain function in the SQL Trace is database-specific. Hence a database execution plan will look different for each database platform supported by SAP.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
97
Unit 2: Taking ABAP to SAP HANA
98
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Guided Performance Analysis
Exercise 6: Use the SQL Performance Tuning Worklist to Analyze Static and Runtime Check Results Exercise Objectives After completing this exercise, you will be able to: • Use the SQL Performance Tuning Worklist tool to analyze check results regarding static source code and runtime related checks
Business Example Combine static code checks and run-time analysis to improve the performance of important ABAP code. You performed a static code analysis using the SAP Code Inspector, and collected run-time data for the same code. You combine the results of both using the SAP Performance Tuning Worklist to analyze which pieces of code should be improved with highest priority. You improved the corresponding pieces of code and now repeat the analysis to quantify the performance improvement achieved. Sample report: Report HA400D_SWLT_OPEN_AMOUNT Sample classes: Class CL_HA400_SWLT_OPEN_AMOUNT Class CL_HA400_SWLT_OPEN_AMOUNT_OPT
Task 1: Understand the entities in package HA400_SWLT Open report HA400D_SWLT_OPEN_AMOUNT in package HA400_SWLT and understand the coding. 1.
Open report HA400D_SWLT_OPEN_AMOUNT in package HA400_SWLT.
2.
The report takes a range of customers as input, and determines the of each customer within the range. It does so with the help of a class, the name of which has to be provided as input parameter. Fill in the blanks to complete the sentence.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
99
Unit 2: Taking ABAP to SAP HANA
3.
HA400
Open class CL_HA400_SWLT_OPEN_AMOUNT and understand the coding. Important to understand is the call stack: Report HA400D_SWLT_OPEN_AMOUNT calls method , which, within a loop, calls method which again, within a loop, calls method leads to a
. This -fold nested loop fetching data from the database.
Fill in the blanks to complete the sentence.
4.
Open class CL_HA400_SWLT_OPEN_AMOUNT_OPT and understand the coding. This class has method which takes care of loading the data from the database. hidden loops, nested method calls. Fill in the blanks to complete the sentence.
Task 2: Analyze Analyze the program and classes using the SQL Performance Tuning Worklist. 1.
Start the SQL Performance Tuning Work List Tool
2.
In the Object Set section, specify package HA400_SWLT
3.
On the SQL Monitor Snapshot Selection section, select an SQLM snapshot.
4.
On the Static Checks section, specify the inspection HA400_SWLT
5.
In the Additional Options choose Aggregate Findings in Overview – By Code Position
6.
Execute the analysis in the SQL Performance Tuning Work List Tool.
7.
Analyze the findings. Look for the SQL Monitor Results and Static Check Findings for object CL_HA400_SWLT_OPEN_AMOUNT and processing blocks GET_OPEN_AMOUNT_4_INVC and GET_OPEN_AMOUNT_4_CUST.
Continued on next page
100
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
8.
Method GET_OPEN_AMOUNT_4_INVC has been executed ________ times, with a total execution time of ca. ____s and nearly _______ executions/session. The static code analysis reports issues: , and Method GET_OPEN_AMOUNT_4_CUST has been executed less often, but still with a total execution time of ca. ___s and a mean execution time of nearly ___ms. The static code analysis reports issues, the first two of which are: , and Fill in the blanks to complete the sentence.
9.
Analyze the findings: Look for the SQL Monitor Results and Static Check Findings for object CL_HA400_SWLT_OPEN_AMOUNT_OPT.
10. Method GET_OPEN_AMOUNT has been called __ times – as often as the original method with the same name in class CL_HA400_SWLT_OPEN_AMOUNT. The calls lead to a total execution time of ca. ___s. The method is thus roughly __ times faster than the original method. The static code analysis reports issues. Fill in the blanks to complete the sentence.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
101
Unit 2: Taking ABAP to SAP HANA
HA400
Solution 6: Use the SQL Performance Tuning Worklist to Analyze Static and Runtime Check Results Task 1: Understand the entities in package HA400_SWLT Open report HA400D_SWLT_OPEN_AMOUNT in package HA400_SWLT and understand the coding. 1.
Open report HA400D_SWLT_OPEN_AMOUNT in package HA400_SWLT. a)
2.
Complete this step as you learned to do in previous classes.
The report takes a range of customers as input, and determines the total open invoice amount of each customer within the range. It does so with the help of a class, the name of which has to be provided as input parameter. Answer: total open invoice amount
3.
Open class CL_HA400_SWLT_OPEN_AMOUNT and understand the coding. Important to understand is the call stack: Report HA400D_SWLT_OPEN_AMOUNT calls method GET_OPEN_AMOUNT, which, within a loop, calls method GET_OPEN_AMOUNT_4_CUST which again, within a loop, calls method GET_OPEN_AMOUNT_4_INVC. This leads to a three-fold nested loop fetching data from the database. Answer: GET_OPEN_AMOUNT, GET_OPEN_AMOUNT_4_CUST, GET_OPEN_AMOUNT_4_INVC, three
4.
Open class CL_HA400_SWLT_OPEN_AMOUNT_OPT and understand the coding. This class has only one method GET_OPEN_AMOUNT which takes care of loading the data from the database. No hidden loops, no nested method calls. Answer: only one, GET_OPEN_AMOUNT, No, no
Task 2: Analyze Analyze the program and classes using the SQL Performance Tuning Worklist. 1.
Start the SQL Performance Tuning Work List Tool a)
2.
Open an SAP GUI window and start transaction SWLT.
In the Object Set section, specify package HA400_SWLT a)
Enter package HA400_SWLT in the Object Set section
Continued on next page
102
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
3.
4.
5.
On the SQL Monitor Snapshot Selection section, select an SQLM snapshot. a)
Navigate to the SQL Monitor Snapshot Selection section
b)
Press the Select Snapshot button
c)
Choose the SQLM Snapshot
On the Static Checks section, specify the inspection HA400_SWLT a)
Press the Select Inspection button
b)
Select inspection HA400_SWLT
In the Additional Options choose Aggregate Findings in Overview – By Code Position a)
6.
Execute the analysis in the SQL Performance Tuning Work List Tool. a)
7.
Press the Execute button (F8).
Analyze the findings. Look for the SQL Monitor Results and Static Check Findings for object CL_HA400_SWLT_OPEN_AMOUNT and processing blocks GET_OPEN_AMOUNT_4_INVC and GET_OPEN_AMOUNT_4_CUST. a)
8.
Select entry By Code Position in the corresponding drop-down listbox.
Double click the rows for processing blocks GET_OPEN_AMOUNT_4_INVC and GET_OPEN_AMOUNT_4_CUST
Method GET_OPEN_AMOUNT_4_INVC has been executed ________ times, with a total execution time of ca. ____s and nearly _______ executions/session. The static code analysis reports 2 issues: Problematic SELECT * statement, and SELECTS in LOOPs across modularization units. Method GET_OPEN_AMOUNT_4_CUST has been executed less often, but still with a total execution time of ca. ___s and a mean execution time of nearly ___ms. The static code analysis reports 4 issues, the first two of which are: Problematic SELECT * statement, and SELECTS in LOOPs across modularization units. Answer: 2, Problematic SELECT * statement, SELECTS in LOOPs across modularization units, 4, Problematic SELECT * statement, SELECTS in LOOPs across modularization units
9.
Analyze the findings: Look for the SQL Monitor Results and Static Check Findings for object CL_HA400_SWLT_OPEN_AMOUNT_OPT. a)
Double click the row for object CL_HA400_SWLT_OPEN_AMOUNT_OPT in the Result Overview
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
103
Unit 2: Taking ABAP to SAP HANA
HA400
10. Method GET_OPEN_AMOUNT has been called __ times – as often as the original method with the same name in class CL_HA400_SWLT_OPEN_AMOUNT. The calls lead to a total execution time of ca. ___s. The method is thus roughly __ times faster than the original method. The static code analysis reports no issues. Answer: no
104
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
Exercise 7: Improve Open SQL Statements Using The SQL Trace (ST05) Exercise Objectives After completing this exercise, you will be able to: • Analyze a program with SQL Trace (ST05) to detect repeated selects • Analyze the improved program • Quantify the improvement with ABAP Trace (SAT)
Business Example Template: Report HA400_OPT_OSQL_S2
Task 1: Analyze Analyze the program HA400_OPT_OSQL_S2 with the SQL Trace (ST05) to detect repeated selects 1.
In a separate session (window), switch on the SQL Trace with a filter for your user name and the program.
2.
Execute the program and switch off the SQL Trace as soon as possible.
3.
Analyze the trace result and identify the most expensive statement and repeated SELECTs.
Task 2: Analyze Improvement Fortunately, the program already contains the improved code in subroutine get_data_solution. Understand the improved code. 1.
The improved subroutine fetches the data using statement, making use of an and repeated SELECT statements are replaced by over an internal table.
SELECT . The original nested
Fill in the blanks to complete the sentence.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
105
Unit 2: Taking ABAP to SAP HANA
HA400
Task 3: Quantify improvement Perform a runtime measurement with ABAP Trace (SAT) or the ABAP Profiling perspective. Compare the runtime consumption of subroutine get_data_template and subroutine get_data_solution Repeat the measurement with access to primary database and compare the runtime consumption. 1.
Perform a runtime measurement with ABAP Trace (SAT) or ABAP Profiling perspective and compare the gross runtime of the two subroutines.
2.
On SAP HANA, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Fill in the blanks to complete the sentence.
3.
On the selections screen, choose option Primary Database and repeat the runtime measurement with ABAP Trace (SAT).
4.
On primary database, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Fill in the blanks to complete the sentence.
106
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
Solution 7: Improve Open SQL Statements Using The SQL Trace (ST05) Task 1: Analyze Analyze the program HA400_OPT_OSQL_S2 with the SQL Trace (ST05) to detect repeated selects 1.
2.
3.
In a separate session (window), switch on the SQL Trace with a filter for your user name and the program. a)
Start transaction ST05 in a new session (enter /oST05 in the command field).
b)
Choose Activate Trace with Filter.
c)
Enter your user name and the program name and choose Enter.
Execute the program and switch off the SQL Trace as soon as possible. a)
Return to the first session (window) and execute the program with the default selection parameters.
b)
As soon as possible, return to the SQL Trace and choose Deactivate.
Analyze the trace result and identify the most expensive statement and repeated SELECTs. a)
In SQL Trace, choose Display Trace and Execute (F8) to see the trace result.
b)
From the application toolbar, choose Aggregate Trace → Structure-Identical Statements.
c)
Sort the list by column Duration and identify the most expensive statement.
d)
Sort the list by column Executions and identify the statement that has been repeated most often.
e)
Click on the statement and choose Display ABAP Call Location from the tool bar.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
107
Unit 2: Taking ABAP to SAP HANA
HA400
Task 2: Analyze Improvement Fortunately, the program already contains the improved code in subroutine get_data_solution. Understand the improved code. 1.
The improved subroutine fetches the data using a single SELECT statement, making use of an INNER JOIN. The original nested and repeated SELECT statements are replaced by a single loop over an internal table. Answer: a single, INNER JOIN, a single loop
Task 3: Quantify improvement Perform a runtime measurement with ABAP Trace (SAT) or the ABAP Profiling perspective. Compare the runtime consumption of subroutine get_data_template and subroutine get_data_solution Repeat the measurement with access to primary database and compare the runtime consumption. 1.
Perform a runtime measurement with ABAP Trace (SAT) or ABAP Profiling perspective and compare the gross runtime of the two subroutines. a)
2.
Perform this step as before.
On SAP HANA, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Answer:
3.
On the selections screen, choose option Primary Database and repeat the runtime measurement with ABAP Trace (SAT). a)
4.
Perform this step as before.
On primary database, the gross runtime of subroutine get_data_template is: ___________ microseconds. The gross runtime of subroutine get_data_solution is: ___________ microseconds. This is a reduction of the runtime by ______ %. Answer:
Result
Source code extract from model solution (Program HA400_OPT_OSQL_S2) *&---------------------------------------------------------------------*
Continued on next page
108
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
*&
Form
get_data_template
*&---------------------------------------------------------------------* *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------* FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE snwd_bpa, ls_invoice TYPE snwd_so_inv_head. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT * FROM snwd_bpa CONNECTION (pv_dbcon) INTO ls_partner. ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
* CLEAR: ls_customer-avg_days_open, lv_count. SELECT * FROM snwd_so_inv_head CONNECTION (pv_dbcon) INTO ls_invoice
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
109
Unit 2: Taking ABAP to SAP HANA
HA400
WHERE buyer_guid = ls_partner-node_key AND payment_status 'P'. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_invoice-created_at ) / 86400. lv_count = lv_count + 1. ENDSELECT. IF ls_customer-avg_days_open 0. ls_customer-avg_days_open = ls_customer-avg_days_open /
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 USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Type for target fields TYPES: BEGIN OF tty_customer_invoice, id
TYPE snwd_bpa-bp_id,
name
TYPE snwd_bpa-company_name,
created_at
TYPE snwd_so_inv_head-created_at,
END OF tty_customer_invoice. * local structure and work areas DATA: ls_customer
LIKE LINE OF ct_customers,
ls_customer_invoice TYPE
tty_customer_invoice.
* Targets for Select DATA lt_customer_invoice TYPE SORTED TABLE OF tty_customer_invoice WITH NON-UNIQUE KEY id.
Continued on next page
110
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
* help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. CLEAR ct_customers. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. SELECT bp~bp_id AS bp_id bp~company_name AS bp_name inv~created_at AS created_at FROM snwd_so_inv_head AS inv JOIN snwd_bpa AS bp ON inv~buyer_guid = bp~node_key CONNECTION (pv_dbcon) INTO TABLE lt_customer_invoice WHERE inv~payment_status 'P' ORDER BY bp~bp_id.
LOOP AT lt_customer_invoice INTO ls_customer_invoice. IF sy-tabix = 1. ls_customer-id
= ls_customer_invoice-id.
ls_customer-name
= ls_customer_invoice-name.
ELSEIF ls_customer_invoice-id ls_customer-id. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers. CLEAR ls_customer. CLEAR lv_count. ls_customer-id
= ls_customer_invoice-id.
ls_customer-name
= ls_customer_invoice-name.
ENDIF. lv_count = lv_count + 1. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_customer_invoice-created_at ) / 86400.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
111
Unit 2: Taking ABAP to SAP HANA
HA400
ENDLOOP. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers.
*
SORT ct_customers BY id. "already sorted
ENDFORM.
112
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Guided Performance Analysis
Lesson Summary You should now be able to: • Use the SQL Monitor (SQLM) to identify most important database access • Use the Performance Tuning Worklist (SWLT) to combine static and dynamic performance analysis results • Use SQL Trace (ST05) for in depth analysis of database accesses
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
113
Unit 2: Taking ABAP to SAP HANA
HA400
Lesson: Performance Rules and Guidelines for SAP HANA Lesson Overview Lesson Objectives After completing this lesson, you will be able to: •
Understand 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.
Performance Guidelines for ABAP on SAP HANA The classical performance guidelines for using Open SQL and for ABAP programming essentially remain vaild. These guidelines can be phrased a “5 Golden Rules”:
Figure 67: Golden Rules for Open SQL
114
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Performance Rules and Guidelines for SAP HANA
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: Use SELECT with a field list instead of SELECT * in order to transfer just the columns you really need 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, etc. 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 In a nutshell, the first three rules are: Do not retrieve data from the database which is not needed, by selecting the Minimal number of rows Minimal number of columns With a minimal number of database interactions Minimize the Search Overhead: You minimize the size of the result set by using the WHERE and HAVING clauses. To increase the efficiency of these clauses, you should 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. You should therefore still aim to reduce the database load as much as possible. You can use the following methods: Avoid reading data redundantly. Use table buffering (if applicable) and do not bypass it. Sort data in your ABAP programs
Figure 68: Conclusion II
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
115
Unit 2: Taking ABAP to SAP HANA
HA400
Some guidelines become even more important with SAP HANA. Keep the result set small and reduce the amount of data transferred: • •
Don’t 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 • •
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. Also use array variants of INSERT, UPDATE, MODIFY, and DELETE
Figure 69: Conclusion III
116
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Performance Rules and Guidelines for SAP HANA
Some guidelines are new! •
•
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, it is not recommended to execute the same operations redundantly
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
117
Unit 2: Taking ABAP to SAP HANA
HA400
Lesson Summary You should now be able to: • Understand the performance rules and guidelines for ABAP on SAP HANA
118
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Unit Summary
Unit Summary You should now be able to: • Describe how to access the SAP HANA Database by using Open SQL and a secondary database connection • Use Code Inspector (SCI) and ABAP Test Cockpit (ATC) to locate potential functional and performance issues. • Use the ABAP Trace (SAT) and the ABAP Profiling perspective to measure and compare runtime consumption • Use the SQL Monitor (SQLM) to identify most important database access • Use the Performance Tuning Worklist (SWLT) to combine static and dynamic performance analysis results • Use SQL Trace (ST05) for in depth analysis of database accesses • Understand the performance rules and guidelines for ABAP on SAP HANA
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
119
Unit Summary
120
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 3 Code-to-Data with SAP HANA as Secondary Database Unit Overview This unit is designed to teach the following topics: • • • • • • • •
Optimizing ABAP applications using SAP HANA as a secondary database ABAP Database Connectivity (ADBC) Native SQL Syntax Finding and analyzing views in SAP HANA Studio Distinguishing features of different types of SAP HANA views Consuming SAP HANA views in a secondary SAP HANA database Working with database procedures stored on SAP HANA Consuming SAP HANA database procedures in a secondary SAP HANA database
Unit Objectives After completing this unit, you will be able to: • • • • • • • • • • • •
2014
Explain Open SQL in the context of SAP HANA Know the limitations of classical Open SQL Understand ABAP Database Connectivity (ADBC) Use ADBC to execute native SQL statements Understand the main difference between native SQL Syntax and Open SQL Syntax Write syntactically correct Native SQL Statements Describe different approaches to moving data-intensive calculations into a secondary SAP HANA database Search for views in SAP HANA Studio Analyze the Definition of SAP HANA views Describe the different Types of SAP HANA views Test views with the data preview Consume HANA views in ABAP
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
121
Unit 3: Code-to-Data with SAP HANA as Secondary Database
• •
HA400
Work with database procedures in SAP HANA Studio Call SAP HANA procedures in ABAP
Unit Contents Lesson: Classical Open SQL and Its Limitations ...........................123 Lesson: ABAP Database Connectivity (ADBC) .............................129 Lesson: Native SQL Syntax ...................................................133 Exercise 8: Issue a Native SQL Join Via ADBC........................137 Exercise 9: Optional: Use Native SQL to Access SAP HANA Specific Functionality .................................................................147 Lesson: Working with Views in SAP HANA Studio .........................154 Lesson: Consuming SAP HANA Views via Native SQL ...................163 Exercise 10: Analyze a SAP HANA View and Use it in Native SQL.167 Lesson: Working With Database Procedures in SAP HANA Studio .....178 Lesson: Calling SAP HANA Procedures in ABAP ..........................184 Exercise 11: Analyze a SAP HANA Database Procedure and Call it with Native SQL.............................................................187
122
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Classical Open SQL and Its Limitations
Lesson: Classical Open SQL and Its Limitations Lesson Overview Classical Open SQL can be used to a limited extent to follow the code-to-data paradigm and benefit from the potential of SAP HANA. Additional approaches are described, all of which lead to using native SQL when working in an ABAP release < 7.4 SP02, respectively when using SAP HANA as a secondary database.
Lesson Objectives After completing this lesson, you will be able to: • •
Explain Open SQL in the context of SAP HANA Know the limitations of classical Open SQL
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 secondary database side-by-side the ABAP system.
The Code-to-Data Paradigm
Figure 70: Code-to-Data Paradigm
To make ABAP code truly benefit from the potential of SAP HANA, a paradigm shift is necessary. Today's applications execute many data intense operations on the application server. High performance applications delegate data intensive operations to the SAP HANA layer such that they really profit from how SAP
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
123
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
HANA can make use of parallelism and optimized data storage and transfer on the database server. The new paradigm therefore is: Code-to-data instead of the old way, data-to-code.
Open SQL
Figure 71: Open SQL in a Nutshell
To some extent, Open SQL allows executing logic in the SAP HANA data layer and to improve performance, provided the performance recommendations are kept mind. Using Open SQL as much as possible is desirable, because Open SQL has several advantages: •
• •
Open SQL provides a unified syntax across the different SQL dialects and a common semantics for constructs where the SQL standard is not fully precise. An ABAP program that only uses Open SQL statements will work in any SAP system, regardless of the database system in use. Open SQL is embedded into the ABAP language. Consider, for example, variable binding, software logistics or automatic client handling.
To be able to provide these advantages, classical Open SQL reflects a subset of standard (ANSI) SQL only.
124
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Classical Open SQL and Its Limitations
Figure 72: Reminder: SQL In A Nutshell
Native SQL is largely standardized as ANSI SQL, but each vendor adds own features. The language can be divided into three parts. •
•
•
In ABAP releases lower than ABAP 7.4 SP05, only the Data Manipulation Language (DML) is reflected in ABAP as Open SQL (with unified syntax and semantics). The Data Definition Language (DDL) is reflected in a considerably restricted way in the ABAP Dictionary. This changes with ABAP 7.4 SP05, where the Core Data Services language starts reflecting the DDL – see later units. The Data Control Language (DCL) is not reflected in ABAP systems at all, due to how an ABAP system interacts with its database.
Figure 73: ABAP Database Integration in a Nutshell
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
125
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
An ABAP system interacts with its database using two layers: •
•
The Database Interface (DBI) provides a database independent interface and additional services like 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 ABAP system runs with a single database user (by default “SAP” or “SAPR3”). This user has many database privileges. The ABAP system stores all data in the database schema corresponding to this user.
Figure 74: Example: Translation of Open SQL to Native SQL
Figure 75: Limitations of Classical Open SQL
126
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Classical Open SQL and Its Limitations
When Open SQL was invented, its scope was limited because many database systems did not support the full SQL standard yet. For example, classical Open SQL as available in ABAP releases below ABAP 7.4 SP05 does not support expressions in the column list, unions, all types of joins, or sub-queries in the SELECT and FROM clauses. In addition, because Open SQL is to provide a common syntax and semantics across all supported database systems, it cannot support database-specific SQL, for example using functions specific to SAP HANA SQL. As a result, you need to use native SQL if you have to use any these features to achieve the desired performance for your applications in ABAP releases below ABAP 7.4 SP02.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
127
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson Summary You should now be able to: • Explain Open SQL in the context of SAP HANA • Know the limitations of classical Open SQL
128
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP Database Connectivity (ADBC)
Lesson: ABAP Database Connectivity (ADBC) Lesson Overview Lesson Objectives After completing this lesson, you will be able to: • •
Understand ABAP Database Connectivity (ADBC) Use ADBC to execute native SQL statements
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 secondary database side-by-side the ABAP system.
Basic Features of ADBC
Figure 76: Basic Features of ADBC
We recommend using the ABAP Database Connectivity API, for short ADBC, for native SQL calls in ABAP. As an API, it allows determining where native SQL calls are used and supports handling exceptions. It is flexible, object-oriented, and still not difficult to use as only two-three main classes are relevant in most cases.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
129
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Usage of ADBC
Figure 77: Logical Sequence for Reading Data with ADBC
The logical sequence to issue a native SQL query using ADBC is shown in the above figure. 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 looks as follows:
Figure 78: Coding Example: ABAP Database Connectivity (ADBC)
130
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP Database Connectivity (ADBC)
Figure 79: Things to Keep in Mind when Using ADBC
When using native SQL, you should be aware of several pitfalls. For example, •
•
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 in case the native SQL string contains an error. This may be especially helpful since the syntax of native SQL differs from the syntax of Open SQL. Native SQL calls bypass the ABAP Database Interface. As a consequence, –
–
2014
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 etc. have to include client field explicitly.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
131
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson Summary You should now be able to: • Understand ABAP Database Connectivity (ADBC) • Use ADBC to execute native SQL statements
132
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Lesson: Native SQL Syntax Lesson Overview Lesson Objectives After completing this lesson, you will be able to: • •
Understand the main difference between native SQL Syntax and Open SQL Syntax Write syntactically correct Native SQL Statements
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 secondary database side-by-side the ABAP system.
Native SQL in ABAP
Figure 80: Native SQL in ABAP
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
133
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Native SQL and Open SQL
Figure 81: Native SQL Syntax – Open SQL Syntax
Figure 82: Example 1: Open SQL Syntax and Native SQL Syntax
134
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Figure 83: Example 2: Joins in Open SQL and Native SQL
Testing Native SQL Statements in the SAP HANA Studio As there is no syntax check for native SQL statements in ABAP, it can be very tiresome to get the syntax right. A convenient solution could be to use the SQL Console view of the SAP HANA Studio.
Figure 84: SQL Console
Here you can enter SQL Statements (SAP HANA syntax) and execute them.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
135
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Figure 85: Enter SQL Statement and Execute
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.
136
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Exercise 8: Issue a Native SQL Join Via ADBC Exercise Objectives After completing this exercise, you will be able to: • Use ABAP Database Connectivity (ADBC) to read data from a database • Understand the syntax of joins in native SQL
Business Example Template: Report HA400_NATIVE_SQL_T1 Solution: Report HA400_NATIVE_SQL_S1
Task 1: Copy and understand template Create a copy of report HA400_NATIVE_SQL_T1 in your package ZHA400_## (suggested name: ZHA400_##_NSQL_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 ADBC to send a native SQL-SELECT with a join to the SAP HANA database Edit your program. In subroutine get_data_solution, fill the missing pieces to replace the open SQL SELECT on SNWD_SO_INV_HEAD and SNWD_BPA used in get_data_template with a native SQL SELECT issued by means of ADBC. Make sure you read exactly the same data as in the template subroutine. 1.
In subroutine get_data_solution, create an instance of class CL_SQL_CONNECTION. Create an instance of class CL_SQL_STATEMENT, handing over the instance of CL_SQL_CONNECTION to the constructor Hint: As of Netweaver 7.02, you may chain these two methods together, thus omitting the reference variable for the connection object.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
137
Unit 3: Code-to-Data with SAP HANA as Secondary Database
2.
HA400
Define a string variable (suggested name: lv_sql) and fill it with the native SQL syntax that corresponds to the open SQL statement found in the template. Use either a classical CONCATENATE or a more modern string-template/-expression approach. Caution: Make sure to use “.” instead of “~” as field selector.
3.
Execute the query, assign the target data object, retrieve the data and close the query. Hint: Check the definition of the target data object carefully.
138
4.
What do you have to change to make the data object work as a target for ADBC?
5.
Implement suitable exception handling for the relevant class-based exceptions that might be raised by the ADBC-methods called.
6.
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Solution 8: Issue a Native SQL Join Via ADBC Task 1: Copy and understand template Create a copy of report HA400_NATIVE_SQL_T1 in your package ZHA400_## (suggested name: ZHA400_##_NSQL_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)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Use ADBC to send a native SQL-SELECT with a join to the SAP HANA database Edit your program. In subroutine get_data_solution, fill the missing pieces to replace the open SQL SELECT on SNWD_SO_INV_HEAD and SNWD_BPA used in get_data_template with a native SQL SELECT issued by means of ADBC. Make sure you read exactly the same data as in the template subroutine. 1.
In subroutine get_data_solution, create an instance of class CL_SQL_CONNECTION. Create an instance of class CL_SQL_STATEMENT, handing over the instance of CL_SQL_CONNECTION to the constructor Hint: As of Netweaver 7.02, you may chain these two methods together, thus omitting the reference variable for the connection object. a)
2.
See source code extract from model solution.
Define a string variable (suggested name: lv_sql) and fill it with the native SQL syntax that corresponds to the open SQL statement found in the template. Use either a classical CONCATENATE or a more modern string-template/-expression approach. Caution: Make sure to use “.” instead of “~” as field selector. a)
See source code extract from model solution.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
139
Unit 3: Code-to-Data with SAP HANA as Secondary Database
3.
HA400
Execute the query, assign the target data object, retrieve the data and close the query. Hint: Check the definition of the target data object carefully. a)
4.
See source code extract from model solution.
What do you have to change to make the data object work as a target for ADBC? Answer: Sorted tables as targets are not supported by ADBC.
5.
Implement suitable exception handling for the relevant class-based exceptions that might be raised by the ADBC-methods called. a)
6.
See source code extract from model solution.
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.
Result
Source code extract from model solution (Program HA400_NATIVE_SQL_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------* FORM get_data_template
USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * Declarations **************** * Type for target fields TYPES: BEGIN OF tty_customer_invoice, id
TYPE snwd_bpa-bp_id,
name
TYPE snwd_bpa-company_name,
created_at
TYPE snwd_so_inv_head-created_at,
END OF tty_customer_invoice. * local structure and work areas DATA: ls_customer
LIKE LINE OF ct_customers,
ls_customer_invoice TYPE
tty_customer_invoice.
* Targets for Select
Continued on next page
140
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
DATA lt_customer_invoice TYPE SORTED TABLE OF tty_customer_invoice WITH NON-UNIQUE KEY id. * help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date.
SELECT bp~bp_id AS bp_id bp~company_name AS bp_name inv~created_at AS created_at FROM snwd_so_inv_head AS inv JOIN snwd_bpa AS bp ON inv~buyer_guid = bp~node_key CONNECTION (pv_dbcon) INTO TABLE lt_customer_invoice WHERE inv~payment_status 'P' ORDER BY bp~bp_id.
LOOP AT lt_customer_invoice INTO ls_customer_invoice. IF sy-tabix = 1. ls_customer-id
= ls_customer_invoice-id.
ls_customer-name
= ls_customer_invoice-name.
ELSEIF ls_customer_invoice-id ls_customer-id. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers. CLEAR ls_customer. CLEAR lv_count. ls_customer-id
= ls_customer_invoice-id.
ls_customer-name
= ls_customer_invoice-name.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
141
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
ENDIF. lv_count = lv_count + 1. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_customer_invoice-created_at ) / 86400. ENDLOOP. ls_customer-avg_days_open = ls_customer-avg_days_open /
lv_count.
INSERT ls_customer INTO TABLE ct_customers. *
SORT ct_customers BY id. "already sorted
ENDFORM.
"
*&---------------------------------------------------------------------* *&
Form
get_data_solution
*&---------------------------------------------------------------------* FORM get_data_solution USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * analyze, then improve code here * Declarations **************** TYPES: BEGIN OF lts_partner, bp_id
TYPE snwd_bpa-bp_id,
company_name TYPE snwd_bpa-company_name, created_at
TYPE snwd_so_inv_head-created_at,
END OF lts_partner. * Work Area for Result DATA ls_customer LIKE LINE OF ct_customers. * Targets for Select DATA: ls_partner TYPE lts_partner, lt_partner TYPE STANDARD TABLE OF lts_partner. * ADBC Objects and variables DATA:
lo_sql_stmt TYPE REF TO cl_sql_statement, lo_conn
TYPE REF TO cl_sql_connection,
lo_result
TYPE REF TO cl_sql_result_set,
lv_sql
TYPE string,
lr_data
TYPE REF TO data.
Continued on next page
142
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
* Eception handling DATA:
lx_sql_exc TYPE REF TO cx_sql_exception, lv_text TYPE string.
* help variables DATA: lv_current_date TYPE timestampl, lv_count TYPE i. *
processing
**************** TRY. CLEAR ct_customers. CLEAR lv_count. " get current date (UTC) GET TIME STAMP FIELD lv_current_date. *
Step 1: Construct the native SQL string into local variable lv_sql.
*
Make sure to order by business partner ID CONCATENATE 'SELECT BP.BP_ID, BP.COMPANY_NAME, INV.CREATED_AT' '
FROM SNWD_BPA AS BP INNER JOIN SNWD_SO_INV_HEAD AS INV'
'
ON BP.NODE_KEY = INV.BUYER_GUID'
' WHERE INV.CLIENT = ''' sy-mandt ''' AND PAYMENT_STATUS ''P''' '
ORDER BY BP.BP_ID'
INTO lv_sql. **
Alternative using String templates and expressions:
*
lv_sql = | SELECT BP.BP_ID, BP.COMPANY_NAME, INV.CREATED_AT |
*
&& |
*
&& |
FROM SNWD_BPA AS BP INNER JOIN SNWD_SO_INV_HEAD AS INV |
*
&& |
WHERE INV.CLIENT = '{ SY-MANDT }' AND PAYMENT_STATUS 'P' |
*
&& |
ORDER BY BP.BP_ID |.
ON BP.NODE_KEY = INV.BUYER_GUID |
*
Step 2: Instantiate the SQL connection and the SQL statement objects
*
Get a secondary DB connection
*
Create an SQL statement to be executed via the connection
lo_conn = cl_sql_connection=>get_connection( pv_dbcon ). lo_sql_stmt = lo_conn->create_statement( ). **
ALTERNATIVE: Do both in one step.
*
CREATE OBJECT lo_sql_stmt EXPORTING con_ref
* **
= cl_sql_connection=>get_connection( pv_dbcon ). ALTERNATIVE: Don't even pass a secondary connection
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
143
Unit 3: Code-to-Data with SAP HANA as Secondary Database
* *
HA400
if the "default" connection is used anyway CREATE OBJECT lo_sql_stmt. lo_sql_stmt->set_table_name_for_trace( 'SNWD_SO join SNWD_BPA' ).
*
Step 3: Execute the native SQL query lo_result = lo_sql_stmt->execute_query( lv_sql ).
*
Step 4: Read the result into the internal table lt_partner GET REFERENCE OF lt_partner INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ).
*
Step 5: close resources, i.e. the SQL statement and connection lo_result->close( ). lo_conn->close( ).
* *
Loop over result as in Open SQL version to calculate the average sales order ages LOOP AT lt_partner INTO ls_partner. IF sy-tabix = 1. " First customer, first order ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
CLEAR: ls_customer-avg_days_open. ELSEIF ls_customer-id ls_partner-bp_id. "Next customer ls_customer-avg_days_open = ls_customer-avg_days_open / lv_count. INSERT ls_customer INTO TABLE ct_customers. ls_customer-id
= ls_partner-bp_id.
ls_customer-name
= ls_partner-company_name.
CLEAR: ls_customer-avg_days_open, lv_count.
ENDIF. lv_count = lv_count + 1. ls_customer-avg_days_open = ls_customer-avg_days_open + cl_abap_tstmp=>subtract( tstmp1 = lv_current_date tstmp2 = ls_partner-created_at ) / 86400. ENDLOOP. ls_customer-avg_days_open = ls_customer-avg_days_open / lv_count.
Continued on next page
144
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
INSERT ls_customer INTO TABLE ct_customers. "Last customer CATCH cx_sql_exception INTO lx_sql_exc. lv_text = lx_sql_exc->get_text( ). MESSAGE lv_text TYPE 'E'. ENDTRY. ENDFORM.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
145
Unit 3: Code-to-Data with SAP HANA as Secondary Database
146
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Native SQL Syntax
Exercise 9: Optional: Use Native SQL to Access SAP HANA Specific Functionality Exercise Objectives After completing this exercise, you will be able to: • Use ABAP Database Connectivity (ADBC) to read data from a database • Understand the syntax of native SQL • Understand how native SQL gives access to SAP HANA specific functionality
Business Example Template: Report HA400_NATIVE_SQL_T2 Solution: Report HA400_NATIVE_SQL_S2
Task 1: Copy and understand template Create a copy of report HA400_NATIVE_SQL_T2 in your package ZHA400_## (suggested name: ZHA400_##_NSQL_2, 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 ADBC and native SQL to replace the complete data retrieval with just one SELECT Edit your 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 directly without any further processing. Make use of the fact that within the field list of native SQL SELECTs calculations are possible. Also use aggregation and ordering techniques of SQL. Make sure you read exactly the same data. 1.
Copy the source code of subroutine get_data_template to subroutine get_data_solution
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
147
Unit 3: Code-to-Data with SAP HANA as Secondary Database
2.
HA400
In subroutine get_data_solution, change the native SQL Statement. Eliminate fields “INV.CREATED_AT” from the field list and replace it by the aggregated difference. Hint: The correct syntax is AVG(DAYS_BETWEEN(TO_DATE(inv.created_at), CURRENT_UTCDATE )) AS AVG_DAYS_OPEN. ‘inv.’ within the TO_DATE( ) function represents the SQL alias of table SNWD_SO_INV_HEAD
3.
Round the aggregated difference, as the target structure only contains an integer field for the result. Surround the previously defined aggregate with a function to round the result. Hint: The correct syntax is ROUND(, decimal length), with the decimal length parameter being optional.
148
4.
In the native SQL Syntax, add a GROUP BY addition that lists the client and all fields found in the field list.
5.
Replace the target data object lt_partner with ct_customers .
6.
Remove the now superfluous loop over lt_partner with the calculation and aggregation.
7.
Activate and test your program, selecting Database to be accessed: Secondary Database. Make sure the two subroutines deliver the same data. Note that executing the solution on the primary database leads to an error, because the solution makes use of SAP HANA-specific SQL.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Solution 9: Optional: Use Native SQL to Access SAP HANA Specific Functionality Task 1: Copy and understand template Create a copy of report HA400_NATIVE_SQL_T2 in your package ZHA400_## (suggested name: ZHA400_##_NSQL_2, 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)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Use ADBC and native SQL to replace the complete data retrieval with just one SELECT Edit your 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 directly without any further processing. Make use of the fact that within the field list of native SQL SELECTs calculations are possible. Also use aggregation and ordering techniques of SQL. Make sure you read exactly the same data. 1.
Copy the source code of subroutine get_data_template to subroutine get_data_solution a)
2.
Use Copy & Paste-function of the ABAP Editor.
In subroutine get_data_solution, change the native SQL Statement. Eliminate fields “INV.CREATED_AT” from the field list and replace it by the aggregated difference. Hint: The correct syntax is AVG(DAYS_BETWEEN(TO_DATE(inv.created_at), CURRENT_UTCDATE )) AS AVG_DAYS_OPEN. ‘inv.’ within the TO_DATE( ) function represents the SQL alias of table SNWD_SO_INV_HEAD a)
See source code extract from model solution.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
149
Unit 3: Code-to-Data with SAP HANA as Secondary Database
3.
HA400
Round the aggregated difference, as the target structure only contains an integer field for the result. Surround the previously defined aggregate with a function to round the result. Hint: The correct syntax is ROUND(, decimal length), with the decimal length parameter being optional. a)
4.
See source code extract from model solution.
In the native SQL Syntax, add a GROUP BY addition that lists the client and all fields found in the field list. a)
5.
See source code extract from model solution.
Replace the target data object lt_partner with ct_customers . a)
6.
See source code extract from model solution.
Remove the now superfluous loop over lt_partner with the calculation and aggregation. a)
7.
See source code extract from model solution.
Activate and test your program, selecting Database to be accessed: Secondary Database. Make sure the two subroutines deliver the same data. Note that executing the solution on the primary database leads to an error, because the solution makes use of SAP HANA-specific SQL. a)
Complete this step as you learned to do in previous classes.
Result
Source code extract from model solution (Program HA400_NATIVE_SQL_S2) *&---------------------------------------------------------------------* *&
Form
get_data_solution
*&---------------------------------------------------------------------* FORM get_data_solution USING pv_dbcon
TYPE dbcon-con_name
CHANGING ct_customers TYPE tt_customer. * analyze, then improve code here * Declarations **************** * ADBC Objects and variables
Continued on next page
150
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
DATA:
lo_sql_stmt 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.
* Eception handling DATA:
lx_sql_exc TYPE REF TO cx_sql_exception, lv_text TYPE string.
*
processing
**************** TRY. CLEAR ct_customers. *
Step 1: Construct the native SQL string into local variable lv_sql.
*
Make sure to order by business partner ID CONCATENATE 'SELECT bp.bp_id, bp.company_name,' '
ROUND( AVG( DAYS_BETWEEN( TO_DATE(inv.created_at), CURRENT_UTCDATE )))'
'
FROM snwd_bpa AS bp INNER JOIN snwd_so_inv_head AS inv '
'
ON bp.node_key = inv.buyer_guid'
' WHERE inv.client = ''' sy-mandt ''' AND payment_status ''P''' ' GROUP BY bp.bp_id, bp.company_name' ' ORDER BY bp.bp_id' INTO lv_sql. **
Alternative using string expressions:
*
lv_sql = | SELECT bp.bp_id, bp.company_name, |
** *
use HANA built-in function to
sum the sales orders' age
&& | ROUND(AVG( DAYS_BETWEEN( TO_DATE(inv.created_at), CURRENT_UTCDATE ))) |
*
&& |
*
&& |
FROM snwd_bpa AS bp INNER JOIN snwd_so_inv_head AS inv |
*
&& |
WHERE inv.client = '{ sy-mandt }' AND payment_status 'P' |
*
&& |
GROUP BY bp.bp_id, bp.company_name |
*
&& |
ORDER BY bp.bp_id |.
*
Step 2: Instantiate the SQL connection and the SQL statement objects
ON bp.node_key = inv.buyer_guid |
CREATE OBJECT lo_sql_stmt EXPORTING con_ref = cl_sql_connection=>get_connection( pv_dbcon ) tab_name_for_trace = 'SNWD_SO join SNWD_BPA'. *
Step 3: Execute the native SQL query lo_result = lo_sql_stmt->execute_query( lv_sql ).
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
151
Unit 3: Code-to-Data with SAP HANA as Secondary Database
*
HA400
Step 4: Read the result into form parameter ct_customer GET REFERENCE OF ct_customers INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ).
*
Step 5: close resources, i.e. the SQL statement and connection lo_result->close( ). CATCH cx_sql_exception INTO lx_sql_exc. lv_text = lx_sql_exc->get_text( ). MESSAGE lv_text TYPE 'E'. ENDTRY.
ENDFORM.
152
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Native SQL Syntax
Lesson Summary You should now be able to: • Understand the main difference between native SQL Syntax and Open SQL Syntax • Write syntactically correct Native SQL Statements
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
153
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson: Working with Views in SAP HANA Studio Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • • •
Describe different approaches to moving data-intensive calculations into a secondary SAP HANA database Search for views in SAP HANA Studio Analyze the Definition of SAP HANA views Describe the different Types of SAP HANA views Test views with the data preview
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 secondary database side-by-side the ABAP system.
Code-to-Data in ABAP releases < ABAP 7.4 One way of approaching the code-to-data paradigm is to use of native SQL intensively, for example built-in functions. Encoding all computations in native SQL statements has a drawback, though: You have to get the SQL statements right, for example the join conditions, the built-in functions etc. In addition, encoding everything in native SQL statements makes reusing parts of the computations difficult.
154
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working with Views in SAP HANA Studio
Figure 86: 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, 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, such calls also require using native SQL. Before looking at how SAP HANA Views can be used in ABAP programs, a short repeat of what SAP HANA views are and how to work with them in the SAP HANA Studio may be helpful.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
155
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Search for SAP HANA Views
Figure 87: Search Functions – Global Search
Figure 88: Search Functions – Local Search in Content
156
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working with Views in SAP HANA Studio
Definition of SAP HANA Views
Figure 89: Open Definition and Data Preview
Attribute Views
Figure 90: Attribute View
Figure 91: Example: Attribute View with Referential Join
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
157
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Analytic Views
Figure 92: Analytic View
Figure 93: Example: Analytic View with Calculated Column
Figure 94: Example: Analytic View with Currency Conversion
158
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working with Views in SAP HANA Studio
Calculation Views
Figure 95: Calculation View
Figure 96: Example: Graphical Calculation View with Aggregated Columns and Filter
Figure 97: Example: Calculation View Based on SQL Script
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
159
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Test and Data Preview
Figure 98: Preview of Raw Data
Figure 99: Analysis of Distinct Values
160
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working with Views in SAP HANA Studio
Figure 100: Graphical Analysis
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
161
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson Summary You should now be able to: • Describe different approaches to moving data-intensive calculations into a secondary SAP HANA database • Search for views in SAP HANA Studio • Analyze the Definition of SAP HANA views • Describe the different Types of SAP HANA views • Test views with the data preview
162
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
Lesson: Consuming SAP HANA Views via Native SQL Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Consume HANA views in ABAP
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.
Consuming SAP HANA Views Using Native SQL SAP HANA Views without Input Parameters
Figure 101: Consuming HANA Views – Logical Picture
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
163
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Figure 102: Consuming HANA Views – Native SQL Syntax
SAP HANA Views with Input Parameters
Figure 103: Consuming HANA Views with Input Parameters – Logical View
Figure 104: Input Parameters in HANA Views – The Facts
164
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
Figure 105: Consuming HANA Views with Input Parameters – Native SQL Syntax
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
165
Unit 3: Code-to-Data with SAP HANA as Secondary Database
166
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
Exercise 10: Analyze a SAP HANA View and Use it in Native SQL Exercise Objectives After completing this exercise, you will be able to: • Analyze and understand views defined on SAP HANA • Use SAP HANA views in the FROM-clause of native SQL SELECTs
Business Example Template: Report HA400_HANA_VIEW_T1 Solution: Report HA400_HANA_VIEW_S1
Task 1: Copy and understand template 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: Find and analyze a SAP HANA View In the SAP HANA Studio, search for a view that contains the relevant information from tables SNWD_BPA, SNWD_SO and SNWD_SO_INV_HEAD, including a calculated field for the average of open days between sales order date (created_at) and the current timestamp. The view should not provide any aggregation yet. Check all relevant properties of the view, display the raw data and do a little analysis of the view’s content with the data preview tool. 1.
Go to the SAP HANA Studio and search the Content for views with the string “open”
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
167
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
2.
The list contains the following views:
3.
The views are located in the following packages:
4.
According to naming conventions, which of the views can you expect to be attribute views?
5.
According to the naming, in which of the packages would you expect views that access replicated data in schema REPZME?
6.
Choose the attribute view that accesses replicated data and analyze its definition. Make sure it accesses the right data, i.e. data replicated from your ABAP system.
Continued on next page
168
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
7.
View tables
,
is based on database and from schema
. The tables are joined by a join of cardinality . The view consists of fields from tables and 1 calculated field. The calculated field's name is . It's calculation expression reads as follows: The view contains one filter condition: Only such entries are selected where the field is unequal to the value . Key field is . Fill in the blanks to complete the sentence.
Task 3: Use the SAP HANA View in a native SQL Select Edit your 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 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, change the native SQL Statement. In the FROM-clause, replace the join of tables SNWD_BPA and SNWD_SO_INV_HEAD with the view you just found. Hint: Remember to state the view's name with it's complete path, i.e. _SYS_BIC... ... / Caution: Names on SAP HANA are case sensitive. But everything not included in “” will be translated to upper case!
3.
Adjust the field list of your SQL statement to make the field names correspond to the field names in the view. Define an aggregation of field DAYS_OPEN, using aggregation function AVG( ) and add a GROUP BY addition that lists the client and all fields from the field list.
4.
Remove the WHERE-clause as this filter condition is already part of the view's definition.
5.
Replace target data object lt_partner with ct_customers .
6.
Remove the now superfluous loop over lt_partner with the calculation and aggregation. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
169
Unit 3: Code-to-Data with SAP HANA as Secondary Database
7.
170
HA400
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
Solution 10: Analyze a SAP HANA View and Use it in Native SQL Task 1: Copy and understand template 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)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Find and analyze a SAP HANA View In the SAP HANA Studio, search for a view that contains the relevant information from tables SNWD_BPA, SNWD_SO and SNWD_SO_INV_HEAD, including a calculated field for the average of open days between sales order date (created_at) and the current timestamp. The view should not provide any aggregation yet. Check all relevant properties of the view, display the raw data and do a little analysis of the view’s content with the data preview tool. 1.
2.
Go to the SAP HANA Studio and search the Content for views with the string “open” a)
In the Navigator window on the left side, right-click on node Content and choose Find.
b)
Enter the search string (e.g. “open” ).
The list contains the following views: Answer: AT_OPEN_INVOICES (4x) AN_OPEN_INVOICE_AMOUNT (4x) CA_OPEN_INVOICE_AMOUNT (1x) DP_OPEN_INVOICE_AMOUNT (1x)
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
171
Unit 3: Code-to-Data with SAP HANA as Secondary Database
3.
HA400
The views are located in the following packages: Answer: ha400.primdb.demo ha400.primdb.templates ha400.secdb.demo sap.bc.epm.oia.dfg.
4.
According to naming conventions, which of the views can you expect to be attribute views? Answer: AT_OPEN_INVOICES, as AT stands for attribute view.
5.
According to the naming, in which of the packages would you expect views that access replicated data in schema REPZME? Answer: Package ha400.secdb.demo, as “secondary database” hints at replicated data.
6.
Choose the attribute view that accesses replicated data and analyze its definition. Make sure it accesses the right data, i.e. data replicated from your ABAP system. a)
Double click the view in the search result or click on it and choose OK.
b)
Click on Data Foundation to see a graphical display of the database tables, the join conditions, the fields of the output and their origin. Filter icons indicate fields where filters are in place.
c)
Click on one of the join lines to see the join type and the cardinality.
d)
In the output-frame on the right, double click on the calculated field DAYS_OPEN to see the calculation rule.
e)
Click on Semantics to see a list of the output fields with their visibility and their classification as key attributes or normal attributes.
Continued on next page
172
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
7.
View AT_OPEN_INVOICES is based on database tables SNWD_BPA, SNWD_SO and SNWD_SO_INV_HEAD from schema REPZME. The tables are joined by a referential join of cardinality n..1. The view consists of 7 fields from tables and 1 calculated field. The calculated field's name is DAYS_OPEN. It's calculation expression reads as follows: rounddown( utcnow() - date("SOINV_CREATED_AT") , 0 ). The view contains one filter condition: Only such entries are selected where the field PAYMENT_STATUS is unequal to the value 'P'. Key field is INVOICE_GUID. Answer: AT_OPEN_INVOICES, SNWD_BPA, SNWD_SO, SNWD_SO_INV_HEAD, REPZME, referential, n..1, 7, DAYS_OPEN, rounddown( utcnow() - date("SOINV_CREATED_AT") , 0 ), PAYMENT_STATUS, 'P', INVOICE_GUID
Task 3: Use the SAP HANA View in a native SQL Select Edit your 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 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)
2.
Use Copy & Paste-function of the ABAP Editor.
In subroutine get_data_solution, change the native SQL Statement. In the FROM-clause, replace the join of tables SNWD_BPA and SNWD_SO_INV_HEAD with the view you just found. Hint: Remember to state the view's name with it's complete path, i.e. _SYS_BIC... ... / Caution: Names on SAP HANA are case sensitive. But everything not included in “” will be translated to upper case! a)
3.
See source code extract from model solution.
Adjust the field list of your SQL statement to make the field names correspond to the field names in the view. Define an aggregation of field DAYS_OPEN, using aggregation function AVG( ) and add a GROUP BY addition that lists the client and all fields from the field list. a)
See source code extract from model solution. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
173
Unit 3: Code-to-Data with SAP HANA as Secondary Database
4.
HA400
Remove the WHERE-clause as this filter condition is already part of the view's definition. a)
See source code extract from model solution.
Replace target data object lt_partner with ct_customers .
5.
a)
See source code extract from model solution.
Remove the now superfluous loop over lt_partner with the calculation and aggregation.
6.
a) 7.
See source code extract from model solution.
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.
Result
Source code extract from model solution (Program HA400_HANA_VIEW_S1) *&---------------------------------------------------------------------* *&
Form
get_data_solution
*&---------------------------------------------------------------------* FORM get_data_solution
USING pv_dbcon
TYPE dbcon-con_name
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.
Continued on next page
174
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
TRY. * 1. Get secondary DB Connection lo_con = cl_sql_connection=>get_connection( pv_dbcon ). * 2. Create statement object CREATE OBJECT lo_sql EXPORTING con_ref = lo_con. * 3. assemble SQL statement CONCATENATE 'SELECT "BP_ID", "COMPANY_NAME",' ' '
AVG("DAYS_OPEN") AS AVG_DAYS_OPEN' FROM "_SYS_BIC"."ha400.secdb.demo/AT_OPEN_INVOICES"'
' GROUP BY "BP_ID", "COMPANY_NAME"' ' ORDER BY "BP_ID"' INTO lv_sql. **
Alternative using string expressions and templates:
*
lv_sql = |SELECT "BP_ID", "COMPANY_NAME"|
*
|
*
| FROM "_SYS_BIC"."ha400.secdb.demo/AT_OPEN_INVOICES"
AVG("DAYS_OPEN") AS AVG_DAYS_OPEN | &&
*
| GROUP BY "BP_ID", "COMPANY_NAME" | &&
*
| ORDER BY "BP_ID" |.
| &&
* HINT: Verify that client handling is covered by the Attribute View. *
Hana Attribute View -> Semantic settings ->client = Session Client.
* 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.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
175
Unit 3: Code-to-Data with SAP HANA as Secondary Database
176
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Consuming SAP HANA Views via Native SQL
Lesson Summary You should now be able to: • Consume HANA views in ABAP
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
177
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson: Working With Database Procedures in SAP HANA Studio Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Work with database procedures in SAP HANA Studio
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system use SAP HANA as a secondary database. You realize that the performance improvement you aim for cannot be reached using native SQL or information models alone.
Searching for SAP HANA Procedures
Figure 106: Stored Procedures – Recap
Code-to-data is a key principle when working with SAP HANA, the aim being to push data-intensive calculations to SAP HANA in order to reduce the data transfer to the application server and to exploit advanced SAP HANA capabilities from
178
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working With Database Procedures in SAP HANA Studio
ABAP. The course so far covered how the code-to-data principle can be applied using Open SQL, native SQL or different kinds of views. These techniques may not always be sufficient to reach the desired performance goals. SAP HANA, like many database systems, provides another mechanism for executing logic on the data layer. The mechanism is more powerful than what’s possible with views and can boost performance further if used cleverly. That mechanism are stored procedures, or Database Procedures as they are called in SAP HANA. SAP HANA database procedures • • • •
Are based on SAP HANA-specific language SQL Script, an extension to SQL. Can have any number of scalar and table-like input parameters. Cacn have any number of output parameters. May contain read and/or write access to the database.
Figure 107: Search for Database Procedures
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
179
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Analyzing SAP HANA Procedures
Figure 108: Parameters of a Procedure
Figure 109: Parameter Details
180
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working With Database Procedures in SAP HANA Studio
Figure 110: Source Code of Procedure
Testing SAP HANA Procedures
Figure 111: Test Procedures – Open SQL Console
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
181
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Figure 112: Test Procedures – Enter Procedure Call in SQL Console
Figure 113: Test Procedures – See Result
182
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Working With Database Procedures in SAP HANA Studio
Lesson Summary You should now be able to: • Work with database procedures in SAP HANA Studio
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
183
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson: Calling SAP HANA Procedures in ABAP Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Call SAP HANA procedures in ABAP
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system use SAP HANA as a secondary database. You realize that the performance improvement you aim for cannot be reached using native SQL or information models alone.
Figure 114: Calling HANA Procedures with Overview
184
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures in ABAP
Figure 115: Calling HANA Procedures – Retrieve one Result Set
Figure 116: Calling HANA Procedures with Overview – Native SQL Syntax
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
185
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Figure 117: Coding Example: Calling HANA Procedure with Overview
Figure 118: Coding Example: Retrieving Result from Overview
186
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures in ABAP
Exercise 11: Analyze a SAP HANA Database Procedure and Call it with Native SQL Exercise Objectives After completing this exercise, you will be able to: • Analyze and understand stored procedures defined on SAP HANA • Call SAP HANA stored procedures via native SQL
Business Example Template: Report HA400_PROCEDURE_T1 Solution: Report HA400_PROCEDURE_S1
Task 1: Copy and understand template Create a copy of report HA400_PROCEDURE_T1 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_HPROC_1, 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. Pay special attention to the changing parameters of the routine and how they are filled with data.
3.
What is the main difference between this program and the ones we used before?
4.
Activate and execute the program.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
187
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Task 2: Analyze a SAP HANA stored procedure In the SAP HANA Studio, analyze the definition of the stored procedure DP_EARLY_ AND_LATE_PAYERS. Check all relevant properties of the procedure. 1.
Go to the SAP HANA Studio, search for procedure DP_EARLY_ AND_LATE_PAYERS and open its definition.
2.
Analyze the procedure's definition.
3.
Stored procedure DP_EARLY_ AND_LATE_PAYERS has input parameter called . It is used to . The script has
output parameters named . The script contains two select statements which look almost identical. The only difference is
and
Fill in the blanks to complete the sentence.
Task 3: Call the SAP HANA Procedure in a native SQL Statement Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution,implement a native SQL Statement that calls the stored procedure. Use addition WITH OVERVIEW to receive first a list of name/value pairs for the export parameters. Using this list, retrieve the content of the export parameters via native SQL Selects from the database. 1.
Copy the source code of subroutine get_data_template to subroutine get_data_solution
2.
In subroutine get_data_solution, replace the string with the native SQL SELECT with a call of the stored procedure. Use addition WITH OVERVIEW. Hint: The procedure expects three parameters separated by colons. The first one is the input parameter. Provide a suitable value for it (content of data object pv_number). The last two parameters correspond to the output parameters. they can be supplied with “null” when using addition WITH OVERVIEW.
3.
Define an internal table with two columns of type string. (Suggested name for the table: lt_overview, suggested names for the columns: param and value). Replace target data object ct_cust_late with this new internal table.. Continued on next page
188
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
2014
Lesson: Calling SAP HANA Procedures in ABAP
4.
After you closed the first query with the call of the procedure, use statement READ TABLE to read the line from lt_overview where column param contains the name of procedure parameter ET_EARLY. Use the content of column value in the FROM-clause of a native SQL SELECT. By doing so, you read the content of the procedure's export parameter from the database. Use the subroutines parameter ct_cust_early as target for this SELECT statement.
5.
After you closed this second query, use statement READ TABLE to read the line from lt_overview where column param contains the name of procedure parameter ET_LATE. Again, use the content of column value in the FROM-clause of a third native SQL SELECT. But this time use the subroutines parameter ct_cust_late as the target for the SELECT statement.
6.
Activate and test your program. Use the debugger to analyze the content of the overview table and the retrieval of the procedures results. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
189
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Solution 11: Analyze a SAP HANA Database Procedure and Call it with Native SQL Task 1: Copy and understand template Create a copy of report HA400_PROCEDURE_T1 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_HPROC_1, 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)
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)
3.
Complete this step as you learned to do in previous classes.
Complete this step as you learned to do in previous classes.
What is the main difference between this program and the ones we used before? Answer: Instead of just one list of all customers, two lists of customers are gathered: One list of customers with the longest average time their invoices remain open, and list of customers with the shortest average time their invoices remain open.
4.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Analyze a SAP HANA stored procedure In the SAP HANA Studio, analyze the definition of the stored procedure DP_EARLY_ AND_LATE_PAYERS. Check all relevant properties of the procedure. 1.
Go to the SAP HANA Studio, search for procedure DP_EARLY_ AND_LATE_PAYERS and open its definition. a)
2.
Perform this step as before.
Analyze the procedure's definition. a)
All relevant information is directly visible in the procedure definition.
Continued on next page
190
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures in ABAP
3.
Stored procedure DP_EARLY_ AND_LATE_PAYERS has 1 input parameter called iv_number . It is used to restrict the number of datasets that are selected. The script has 2 output parameters named ET_EARLY and ET_LATE . The script contains two select statements which look almost identical. The only difference is the sorting order (one sorts ascending, the other descending) Answer: 1, iv_number , restrict the number of datasets that are selected, 2, ET_EARLY , ET_LATE , the sorting order (one sorts ascending, the other descending)
Task 3: Call the SAP HANA Procedure in a native SQL Statement Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution,implement a native SQL Statement that calls the stored procedure. Use addition WITH OVERVIEW to receive first a list of name/value pairs for the export parameters. Using this list, retrieve the content of the export parameters via native SQL Selects from the database. 1.
Copy the source code of subroutine get_data_template to subroutine get_data_solution a)
2.
Use Copy & Paste-function of the ABAP Editor.
In subroutine get_data_solution, replace the string with the native SQL SELECT with a call of the stored procedure. Use addition WITH OVERVIEW. Hint: The procedure expects three parameters separated by colons. The first one is the input parameter. Provide a suitable value for it (content of data object pv_number). The last two parameters correspond to the output parameters. they can be supplied with “null” when using addition WITH OVERVIEW. a)
3.
Define an internal table with two columns of type string. (Suggested name for the table: lt_overview, suggested names for the columns: param and value). Replace target data object ct_cust_late with this new internal table.. a)
4.
See source code extract from model solution.
See source code extract from model solution.
After you closed the first query with the call of the procedure, use statement READ TABLE to read the line from lt_overview where column param contains the name of procedure parameter ET_EARLY. Use the content of column value in the FROM-clause of a native SQL SELECT. By doing so, Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
191
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
you read the content of the procedure's export parameter from the database. Use the subroutines parameter ct_cust_early as target for this SELECT statement. a) 5.
See source code extract from model solution.
After you closed this second query, use statement READ TABLE to read the line from lt_overview where column param contains the name of procedure parameter ET_LATE. Again, use the content of column value in the FROM-clause of a third native SQL SELECT. But this time use the subroutines parameter ct_cust_late as the target for the SELECT statement. a)
6.
See source code extract from model solution.
Activate and test your program. Use the debugger to analyze the content of the overview table and the retrieval of the procedures results. Make sure the two subroutines deliver exactly the same data. a)
Complete this step as you learned to do in previous classes.
Result
Source code extract from model solution (Program HA400_PROCEDURE_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.
* Processing **************************** CLEAR: ct_cust_early, ct_cust_late. TRY. * Create statement object (primary DB connection) DATA(lo_sql) = NEW cl_sql_statement( ). * Classical stype without expressions: *
DATA: lo_sql
TYPE REF TO cl_sql_statement,
*
lo_result TYPE REF TO cl_sql_result_set,
*
lv_sql
*
TYPE
string.
CREATE OBJECT lo_sql.
Continued on next page
192
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures in ABAP
* *
lv_sql = pv_number.
*
CONCATENATE `SELECT TOP `
*
lv_sql
*
`
*
`
*
` GROUP BY BP_ID, COMPANY_NAME`
*
BP_ID, COMPANY_NAME, AVG(DAYS_OPEN) AS DAYS_OPEN` FROM _SYS_BIC."ha400.primdb.demo/AT_OPEN_INVOICES" `
` ORDER BY DAYS_OPEN DESC`
*
INTO lv_sql.
* First query (fill et_cust_late) DATA(lo_result) = lo_sql->execute_query( |SELECT TOP { pv_number } | && | && |
BP_ID, COMPANY_NAME, AVG(DAYS_OPEN) AS DAYS_OPEN | FROM _SYS_BIC."ha400.primdb.demo/AT_OPEN_INVOICES"
|
&& | GROUP BY BP_ID, COMPANY_NAME | && | ORDER BY DAYS_OPEN DESC | ). *
lo_result = lo_sql->execute_query( lv_sql ).
*
DATA lr_data TYPE REF TO data.
*
GET REFERENCE OF ct_cust_late INTO lr_data.
*
lo_result->set_param_table(
lr_data ).
lo_result->set_param_table( REF #( ct_cust_late ) ). lo_result->next_package( ). lo_result->close( ). * Second query (fill et_cust_early)) * Classical code style omitted for brevity lo_result = lo_sql->execute_query( |SELECT TOP { pv_number } | && | && |
BP_ID, COMPANY_NAME, AVG(DAYS_OPEN) AS DAYS_OPEN | FROM _SYS_BIC."ha400.primdb.demo/AT_OPEN_INVOICES"
|
&& | GROUP BY BP_ID, COMPANY_NAME | && | ORDER BY DAYS_OPEN ASC | ). lo_result->set_param_table( REF #( ct_cust_early ) ). lo_result->next_package( ). lo_result->close( ). * Exception handling CATCH cx_sql_exception INTO DATA(lx_sql_exc). "Excpt. Class for SQL Error MESSAGE lx_sql_exc TYPE 'E'. ENDTRY.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
193
Unit 3: Code-to-Data with SAP HANA as Secondary Database
ENDFORM.
HA400
"
*&---------------------------------------------------------------------* *&
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.
* Declarations **************** * type for result overview TYPES: BEGIN OF lty_s_overview, param TYPE string, value TYPE string, END OF lty_s_overview. * Data objects for result overview DATA: lt_overview TYPE TABLE OF lty_s_overview, ls_overview TYPE
lty_s_overview.
* ADBC Objects and Variables DATA: lo_con lo_sql
TYPE REF TO cl_sql_connection, 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_cust_early, ct_cust_late. TRY. * Create statement object (primary DB connection) CREATE OBJECT lo_sql. * Call Procedure with Overview (fill lt_overview) lo_result = lo_sql->execute_query( |CALL _SYS_BIC."ha400.primdb.demo/DP_EARLY_AND_LATE_PAYERS"( |
Continued on next page
194
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures in ABAP
&& |{ pv_number }, null , null ) WITH OVERVIEW | ). GET REFERENCE OF lt_overview INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). lo_result->close( ). * Retrieve first result (Parameter et_early) READ TABLE lt_overview INTO ls_overview WITH KEY param = 'ET_EARLY'. lo_result = lo_sql->execute_query( |SELECT * FROM { ls_overview-value } | ). GET REFERENCE OF ct_cust_early INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). lo_result->close( ). * Retrieve second result (Parameter et_late) READ TABLE lt_overview INTO ls_overview WITH KEY param = 'ET_LATE'. lo_result = lo_sql->execute_query( |SELECT * FROM { ls_overview-value } | ). GET REFERENCE OF ct_cust_late INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). 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.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
195
Unit 3: Code-to-Data with SAP HANA as Secondary Database
HA400
Lesson Summary You should now be able to: • Call SAP HANA procedures in ABAP
196
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Unit Summary
Unit Summary You should now be able to: • Explain Open SQL in the context of SAP HANA • Know the limitations of classical Open SQL • Understand ABAP Database Connectivity (ADBC) • Use ADBC to execute native SQL statements • Understand the main difference between native SQL Syntax and Open SQL Syntax • Write syntactically correct Native SQL Statements • Describe different approaches to moving data-intensive calculations into a secondary SAP HANA database • Search for views in SAP HANA Studio • Analyze the Definition of SAP HANA views • Describe the different Types of SAP HANA views • Test views with the data preview • Consume HANA views in ABAP • Work with database procedures in SAP HANA Studio • Call SAP HANA procedures in ABAP
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
197
Unit Summary
198
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 4 Optimizing ABAP On Primary Database SAP HANA Unit Overview This unit is designed to teach the following topics: • •
Using enhanced Open SQL to move calculations to the database Defining and using advanced views in ABAP using Core Data Services
Unit Objectives After completing this unit, you will be able to: • • • • • • • •
Describe code-to-data approaches possible with ABAP 7.4 SP05 Use the new Open SQL syntax for simple SELECT statements Use expressions in Open SQL SELECT statements Define database views using Core Data Services (CDS) in ABAP Use expressions, joins and unions in CDS-based view definitions Use aggregation and grouping in CDS-based view definitions Use Open SQL to select data based on CDS views Use associations in Core Data Services
Unit Contents Lesson: New Open SQL .......................................................200 Exercise 12: New Features in OpenSQL................................209 Lesson: Core Data Services in ABAP........................................219 Exercise 13: Core Data Services in ABAP ..............................229 Lesson: Associations in Core Data Services................................242 Exercise 14: Use Associations in Core Data Services in ABAP .....245
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
199
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Lesson: New Open SQL Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • •
Describe code-to-data approaches possible with ABAP 7.4 SP05 Use the new Open SQL syntax for simple SELECT statements Use expressions in Open SQL SELECT statements
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system has been migrated to use SAP HANA as its primary database already.
Figure 119: Code-to-Data Capabilities in ABAP 7.4
In an earlier lesson, the bottom-up approach to the code-to-data paradigm possible with ABAP releases below 7.4 was discussed. This approach has drawbacks, for example considering management of the SAP HANA artefacts and the ABAP code that depends on them, and the need for developers to directly access the database system. This is why ABAP 7.4 provides additional capabilities to support the code-to-data paradigm, especially beginning with ABAP 7.4 SP05. Three different kinds of additional code-to-data capabilities can be distinguished:
200
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
Transparent Optimizations are improvements in the ABAP stack itself your code directly benefits from without any adjustments. For example: • • • • •
Fast Data Access, a new data exchange protocol between the ABAP stack and the database Optimizations how Open SQL SELECT FOR ALL ENTRIES clauses are translated into native SQL Optimizations of SELECT... INTO ITAB and of SELECT SINGLE Enhancements to the table buffer A new SQL parser
A Database-oriented programming model is supported better through: • •
A new and advanced Open SQL, supporting considerably more of the SQL-92 standard New capabilities to define views. Definition capabilities were extended to have a Tight-Database-Programming-Model by introducing a common set of domain-specific languages and services for defining and consuming semantically rich data models – called Core Data Services
Using HANA Specific Features is improved by introducing a new concept called ABAP-Managed Database Procedures.
Figure 120: Top-Down Approach with AS ABAP 7.4 ≥ SP05
The new approach can be called 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. This approach will be the topic of the next lessons.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
201
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 121: Performance Improvement vs. Code Adjustments
The different approaches to code-to-data and code adjustments correlate with the potential gain in performance. But the complexity of the resulting code may also increase the more code is moved to the database or made database-specific. •
•
•
Transparent optimizations in principle improve performance without any code adjustments. Some code adjustments may be necessary while migrating to SAP HANA, though, to profit from the adjustments. Using enhanced Open SQL and the advanced view definition capabilities in ABAP, you can create new data models and consume themnativelyin ABAP applications, thereby improving the productivity and performance without introducing database-specific artefacts. Using native database features may be necessary to achieve the best performance, but the code adjustment effort might increase as well as the complexity of bringing code to the database layer.
The following lessons and units cover the advanced SQL capabilities and ABAP-managed database procedures, beginning with enhanced Open SQL in this lesson.
202
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
Figure 122: What is Open SQL? Why Enhance It?
In an earlier lesson the use of ADBC and Native SQL was discussed as a way to get around the limitations of classic Open SQL. However, working with Native SQL can be quite clumsy and prone to errors and problems, using Open SQL would be more desirable in most cases. Open SQL in the AS ABAP, respectively in the ABAP language, is a database abstraction layer with an SQL-like syntax. The most important fact is, that Open SQL defines a common SQL semantic for all databases supported by SAP, it is not just a subset of SQL commands common to all databases. The common semantic for all supported DBs ensures that the result of an Open SQL query is independent of the underlying database. One of the reasons why using native SQL was necessary was that the SQL-92 standard defines a long list of syntax for features that were not previously available in Open SQL. For example, Open SQL lacked expressions, had only limited JOIN types, and did not support UNION or UNION ALL. Of course ABAP developers were asking: “Why doesn't SAP minimize these limitations?”. Luckily, as of SAP NetWeaver 7.40 SPS5, the scenarios where Native SQL will be necessary are reduced, because Open SQL has been extended. Of course these extensions are relevant regardless of the database (we are talking about Open SQL!), but some of them are of particular importance when we think about the performance guidelines for SAP HANA.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
203
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 123: Summary – Whats New in Open SQL
In order to extend Open SQL, it was necessary to define a common semantic for the new features and functionality. Once this had been settled, the new syntax was incorporated and the available Open SQL syntax was enhanced. Heres a brief list of the new syntax in Open SQL, along with a syntax example on the right-hand side. The first thing you might notice is the “@” symbol used for escaping of so-called host variables. The ABAP system and language are considered the host of the embedded Open SQL, so host variable basically means an ABAP variable or constant inside an Open SQL statement • •
Every host variable except literals can, should, and must be escaped with a preceding “@” sign at every position in the statement. If one host variable is escaped, all host variables have to be escaped.
Moreover, a comma-separated list of fields can now be used. Hint: Do not mix comma-separated fields in Open SQL with the colon-comma syntax for repeated ABAP statements. In addition, Open SQL now supports using arithmetic and string expressions, as well as conditional expressions like CASE command shown in the second coding example.
204
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
You should be aware that using the new Open SQL features has implications: •
•
If you use these new features, you have to use the new syntax throughout your statements. For example, the usage of arithmetic expressions and/or a comma-separated field list implies the escaping of host variables with the “@” symbol. The usage of the new Open SQL syntax implies a so-called “strict mode”, wherein nearly everything that formerly resulted in a syntax warning now results in a syntax error in the context of Open SQL commands.
Figure 124: Arithmetic and String Expressions
One of the key points in the introduction of arithmetic expressions in Open SQL is the common semantics, namely the query behavior for these new features. For example, the SQL standard does not specify the overflow behavior in the addition of two integers or two P-type variables, a job that has 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. On the other hand, the MOD function is only available for Iand 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). So make sure to check the type of variables you are dealing with when programming your Open SQL statement. In addition to arithmetic expressions, Open SQL now also features string expressions, and string concatenation using the “&&” operator.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
205
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 125: Further Limitations Removed
RIGHT OUTER JOIN is now available in Open SQL. It is similar to the LEFT OUTER JOIN, but with switched roles for the “LEFT” and the “RIGHT” tables. In addition to this, the limited support for using brackets in JOIN expressions with more than two tables has been enhanced. So far, the JOIN had to be performed left-to-right, that is the left-most tables always had to be joined first (left-bracketing). This limitation no longer applies. New functionality with regard to the ON conditions of JOIN expressions is now also possible, for example: • • • •
The previous restriction that a field of the right table is present in the ON condition has been dropped. Not only the “=” (equal) operator, but also operators like “BETWEEN” or “greater than”/“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. Implicit client handling in JOINs has been improved: If both sides of a JOIN are 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. → You dont have to struggle with client fields in JOINs any longer.
Beside these new features, two other restrictions have been removed: • •
206
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
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
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 SPS5 system.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
207
Unit 4: Optimizing ABAP On Primary Database SAP HANA
208
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: New Open SQL
Exercise 12: New Features in OpenSQL Exercise Objectives After completing this exercise, you will be able to: • Use the new features of OpenSQL
Business Example Template: Report HA400_OSQL_FEATURES_T1 Report HA400_OSQL_FEATURES_T2 Report HA400_OSQL_FEATURES_T3 Report HA400_OSQL_FEATURES_T4 Solution: Report HA400_OSQL_FEATURES_S1 Report HA400_OSQL_FEATURES_S2 Report HA400_OSQL_FEATURES_S3 Report HA400_OSQL_FEATURES_S4
Task 1: New OpenSQL Syntax Write an OpenSQL query using the new syntax. 1.
Create a copy of report HA400_OSQL_FEATURES_T1 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T1##, where ## is your group number).
2.
Implement an OpenSQL query statement using the new syntax, i.e. comma-separated field list and escaping of host variables. Select the sales order id (so_id), the currency code (currency_code), and the gross amount (gross_amount) of the sales order table (snwd_so). Hint: For simplicity, restrict the result set to 10 rows using the language add on “UP TO … ROWS”.
3.
Save, activate, and execute the report.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
209
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 2: CASE statement in OpenSQL Enhance the OpenSQL query with a CASE statement. 1.
Create a copy of report HA400_OSQL_FEATURES_T2 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T2##, where ## is your group number).
2.
Analyze the SELECT statement. Which tables are used in the query?
3.
Enhance the field list. Select the company_name (table snwd_bpa), the invoice gross amount and currency code (table snwd_so_inv_head), and add a CASE statement on the delivery status (table snwd_so). In the CASE statement, set the delivery status ‘ ’ (space) to ‘OPEN’ and ‘D’ to ‘DELIVERED’. Alias the invoice gross amount as invoiced_amount.
4.
Save, activate, and execute the report.
Task 3: Expressions in OpenSQL Enhance the OpenSQL query with literal and arithmetical expressions. 1.
Create a copy of report HA400_OSQL_FEATURES_T3 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T3##, where ## is your group number).
2.
Analyze the SELECT statement. What is the value of field two?
3.
Enhance the field list with i) reduced gross amount (red_gross_amount): Sales order gross amount multiplied by the discount rate lv_discount ii) half of the gross amount (half_gross_amount): Sales order gross amount divided by a factor of two Continued on next page
210
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
iii) ceil of the gross amount (ceiled_gross_amount): Apply the ceil function on the sales order gross amount Caution: You have to CAST the gross amount and the factor as floating point variable (FLTP). 4.
Save, activate, and execute the report.
Task 4: Generic Existence Check Write a generic existence check. 1.
Create a copy of report HA400_OSQL_FEATURES_T4 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T4##, where ## is your group number).
2.
Implement a generic existence check on the sales order invoice item table (snwd_so_inv_item). Hint: You can use the constant abap_true in the query.
3.
2014
Save, activate, and execute the report.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
211
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Solution 12: New Features in OpenSQL Task 1: New OpenSQL Syntax Write an OpenSQL query using the new syntax. 1.
2.
Create a copy of report HA400_OSQL_FEATURES_T1 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T1##, where ## is your group number). a)
In the ABAP perspective of the SAP HANA Studio, open in the package HA400_PRIMDB_EXERCISE, navigate to Source Library → Programs → HA400_OSQL_FEATURES_T1. Right-click on the program and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the program name ZHA400_ OSQL_FEATURES_T1## (## is your group number). Press Next.
Implement an OpenSQL query statement using the new syntax, i.e. comma-separated field list and escaping of host variables. Select the sales order id (so_id), the currency code (currency_code), and the gross amount (gross_amount) of the sales order table (snwd_so). Hint: For simplicity, restrict the result set to 10 rows using the language add on “UP TO … ROWS”. a)
3.
Remove the comments from the SELECT statement.
Save, activate, and execute the report. a)
Click on the save icon (shortcut CTRL+S) and the activate icon (shortcut CTRL+F3). To execute the report, right-click on the program name in the package explorer and choose Run As → ABAP Application or use the shortcut F8.
Continued on next page
212
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
Task 2: CASE statement in OpenSQL Enhance the OpenSQL query with a CASE statement. 1.
2.
Create a copy of report HA400_OSQL_FEATURES_T2 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T2##, where ## is your group number). a)
In the ABAP perspective of the SAP HANA Studio, open in the package HA400_PRIMDB_EXERCISES, navigate to Source Library → Programs → HA400_OSQL_FEATURES_T2. Right-click on the program and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the program name ZHA400_ OSQL_FEATURES_T2## (## is your group number). Press Next.
Analyze the SELECT statement. Which tables are used in the query? Answer: Tables snwd_so, snwd_bpa, and snwd_so_inv_head are used in the query.
3.
Enhance the field list. Select the company_name (table snwd_bpa), the invoice gross amount and currency code (table snwd_so_inv_head), and add a CASE statement on the delivery status (table snwd_so). In the CASE statement, set the delivery status ‘ ’ (space) to ‘OPEN’ and ‘D’ to ‘DELIVERED’. Alias the invoice gross amount as invoiced_amount. a)
4.
Enhance the field list by bp~company_name, head~currency_code, head~gross_amount as invoiced_amount, and CASE so~delivery_status WHEN ' ' THEN 'OPEN' WHEN 'D' THEN 'DELIVERED' ELSE so~delivery_status END
Save, activate, and execute the report. a)
Click on the save icon (shortcut CTRL+S) and the activate icon (shortcut CTRL+F3). To execute the report, right-click on the program name in the package explorer and choose Run As → ABAP Application or use the shortcut F8.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
213
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 3: Expressions in OpenSQL Enhance the OpenSQL query with literal and arithmetical expressions. 1.
2.
Create a copy of report HA400_OSQL_FEATURES_T3 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T3##, where ## is your group number). a)
In the ABAP perspective of the SAP HANA Studio, open in the package HA400_PRIMDB_EXERCISES, navigate to Source Library → Programs → HA400_OSQL_FEATURES_T3. Right-click on the program and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the program name ZHA400_ OSQL_FEATURES_T3## (## is your group number). Press Next.
Analyze the SELECT statement. What is the value of field two? Answer: The sum of constant 1 and 1, so two contains the value 2.
3.
Enhance the field list with i) reduced gross amount (red_gross_amount): Sales order gross amount multiplied by the discount rate lv_discount ii) half of the gross amount (half_gross_amount): Sales order gross amount divided by a factor of two iii) ceil of the gross amount (ceiled_gross_amount): Apply the ceil function on the sales order gross amount Caution: You have to CAST the gross amount and the factor as floating point variable (FLTP). a)
i) ( @lv_discount * gross_amount ) as red_gross_amount ii) CAST( gross_amount AS fltp ) / cast( 2 AS fltp ) as half_gross_amount iii) CEIL( gross_amount ) as ceiled_gross_amount
4.
Save, activate, and execute the report. a)
Click on the save icon (shortcut CTRL+S) and the activate icon (shortcut CTRL+F3). To execute the report, right-click on the program name in the package explorer and choose Run As → ABAP Application or use the shortcut F8.
Continued on next page
214
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
Task 4: Generic Existence Check Write a generic existence check. 1.
2.
Create a copy of report HA400_OSQL_FEATURES_T4 in your package ZHA400_## (suggested name: ZHA400_ OSQL_FEATURES_T4##, where ## is your group number). a)
In the ABAP perspective of the SAP HANA Studio, open in the package HA400_PRIMDB_EXERCISES, navigate to Source Library → Programs → HA400_OSQL_FEATURES_T4. Right-click on the program and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the program name ZHA400_ OSQL_FEATURES_T4## (## is your group number). Press Next.
Implement a generic existence check on the sales order invoice item table (snwd_so_inv_item). Hint: You can use the constant abap_true in the query. a)
3.
Implement a SELECT SINGLE @abap_true on table snwd_so_inv_item into the resulting variable lv_flag. Note that the constant abap_true and the variable lv_flag have to be escaped with the “@” sign.
Save, activate, and execute the report. a)
Click on the save icon (shortcut CTRL+S) and the activate icon (shortcut CTRL+F3). To execute the report, right-click on the program name in the package explorer and choose Run As → ABAP Application or use the shortcut F8.
Result Source code extract from model solution (Program HA400_OSQL_FEATURES_S1) REPORT ha400_osql_features_s1. * *** Declare your variables and/or tables *** DATA lt_data TYPE STANDARD TABLE OF if_ha400_osql_types=>ty_simple.
* *** Implement your SQL Query *** SELECT so_id AS sales_order_id, currency_code, gross_amount
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
215
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
FROM snwd_so INTO TABLE @lt_data UP TO 10 ROWS.
* *** Write and display the data *** cl_demo_output=>display_data( name
= 'Simple OpenSQL using New Syntax'
value = lt_data ).
(Program HA400_OSQL_FEATURES_S2) REPORT ha400_osql_features_s2. * *** Declare your your variables and/or tables *** DATA lt_data TYPE STANDARD TABLE OF if_ha400_osql_types=>ty_various_new_features.
* *** Implement your SQL Query *** SELECT so~so_id, bp~company_name, head~currency_code, head~gross_amount AS invoiced_amount, CASE so~delivery_status WHEN ' ' THEN 'OPEN' WHEN 'D' THEN 'DELIVERED' ELSE so~delivery_status END FROM snwd_so AS so INNER JOIN snwd_bpa AS bp ON so~buyer_guid = bp~node_key LEFT OUTER JOIN snwd_so_inv_head AS head ON so~node_key = head~so_guid INTO TABLE @lt_data UP TO 10 ROWS *
where clause shows effect of left outer join:
*
Only sales orders without invoices are selected WHERE head~node_key IS NULL.
* *** Write and display the data *** cl_demo_output=>display_data( name
= 'Various New OpenSQL Features'
value = lt_data ).
(Program HA400_OSQL_FEATURES_S3) REPORT ha400_osql_features_s3.
Continued on next page
216
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: New Open SQL
* *** Declare your your variables and/or tables *** DATA lv_discount TYPE p LENGTH 1 DECIMALS 1 VALUE '0.8'. DATA lt_data TYPE STANDARD TABLE OF if_ha400_osql_types=>ty_arithmtcl_expressns.
* *** Implement your SQL Query *** SELECT ( 1 + 1 ) AS two, ( @lv_discount * gross_amount ) AS red_gross_amount, CAST( gross_amount AS fltp ) / cast( 2 AS fltp ) AS half_gross_amount, CEIL( gross_amount ) AS ceiled_gross_amount FROM snwd_so INTO TABLE @lt_data UP TO 10 ROWS. * *** Write and display the data *** cl_demo_output=>display_data( name
= 'Using Arithmetical Expressions'
value = lt_data ).
(Program HA400_OSQL_FEATURES_S4) REPORT ha400_osql_features_s4. * *** Declare your your variables and/or tables *** DATA lv_flag TYPE abap_bool VALUE abap_false. * *** Implement your SQL Query *** SELECT SINGLE @abap_true FROM snwd_so_inv_item INTO @lv_flag. * *** Write and display the data *** cl_demo_output=>display_data( name
= 'Generic Existence Check'
value = lv_flag ).
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
217
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Lesson Summary You should now be able to: • Describe code-to-data approaches possible with ABAP 7.4 SP05 • Use the new Open SQL syntax for simple SELECT statements • Use expressions in Open SQL SELECT statements
218
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Lesson: Core Data Services in ABAP Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • •
Define database views using Core Data Services (CDS) in ABAP Use expressions, joins and unions in CDS-based view definitions Use aggregation and grouping in CDS-based view definitions Use Open SQL to select data based on CDS views
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system has been migrated to use SAP HANA as its primary database already. Core Data Services 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 – e.g. OData EDM models, the Semantic Layer in the BI platform, JPA and enterprise objects in Java, or the business objects frameworks in ABAP. Those 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 (DSL) and services – called Core Data Services – for defining and consuming semantically rich data models. CDS are to be supported by several SAP platforms. They are an integral part of SAP HANA, and can be leveraged in the ABAP stack.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
219
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 126: Core Data Services @ABAP
Supporting enhanced “view entities” in ABAP, based on Core Data Services, provides several advantages: •
More data-intensive calculations can be pushed down to the database (Code-to-Data paradigm) through extended view functionality – –
•
Compared to Open SQL, CDS provide enhanced support for combining queries, e.g. UNION. ABAP CDS are available on all databases
Reading data – –
Via nested views, where one view consumes another view, are supported Associations between view entities can be defined and used can be within WHERE-clause as well as within expressions
The entities of these models provide enhanced access functions, compared to existing database tables and views defined in the ABAP Dictionary, making it possible to optimize Open SQL based applications.
220
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Figure 127: Advanced View Definition in ABAP – 7.4 SP2
Support for CDS in ABAP begins with ABAP 7.4 SP2. In this release, • • •
•
CDS View Definition already supports more features than ABAP Dictionary views. CDS leverages the ABAP Dictionary type system CDS uses the ABAP infrastructure, including the database interface layer which ensures “Open SQL”-like behavior and support for all database platforms supported by the ABAP stack. CDS does not support the full SQL-92 standard and no SAP HANA specific features
Figure 128: Advanced View Definition in ABAP – 7.4 SP5
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
221
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
With SAP NetWeaver ABAP 7.40 SP5, support for associations between entities adds a new conceptual level. Associations can be used to replace joins with simple path expressions in queries. This can ease the consumption of data models and make them more readable. Associations go beyond the traditional ABAP dictionary view and SQL92 capabilities.
Figure 129: Advanced View Definition in ABAP – Outlook
The goal of ABAP CDS is to fully support the SQL-92 standard and beyond that to support additional features like associations, entities, Create, Read, Update and Delete (CRUD) & OData Services.
222
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Figure 130: CDS View Definition in ABAP 7.4 SP5
To create Core Data Services views •
•
• •
Use the ABAP Development Tools for SAP NetWeaver. The ABAP Workbench does not support the new type of ABAP repository objects called “DDL Sources” (R3TR DDLS) In the ABAP Project tree, select the package to contain the CDS view and choose context menu entry New → Other ABAP Repository Object → Dictionary → DDL Source Use DDL statement DEFINE VIEW and SQL-like syntax to define the view. Use additional annotations – marked with the @ sign – to provide additional meta data, for example related to how to buffer view records, client-dependency, and references between amount and quantity columns and the corresponding currency and unit code columns.
The annotation @AbapCatalog.sqlViewName is mandatory, and specifies the name of the representation of the DDL Source in the ABAP Dictionary and the database. Note that the CDS view entities are different from these associated representations on the database layer, that is the corresponding SQL views, and in the ABAP Dictionary. These representations are generated, updated and deleted automatically when activating the DDL source.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
223
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 131: Select List – CASE Expressions in CDS Views
Like the new Open SQL, ABAP CDS supports the CASE expression. It is also possible to nest CASE expressions. With the case expression, using further expressions is supported. An alias name is required for the resulting column except for nested CASE. The resulting column type is derived from expressions after THEN and ELSE clause.
Figure 132: Select List – Other Expressions In CDS Views
224
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Various kinds of expressions, including some built-in functions, can be used as well. For example •
•
•
Arithmetic expressions using operators +, -, & or the unary -, or using built-in functions such as CEIL( ) and MOD( ). The simplest form of expression is a numerical literal. String expressions, including the string concatenation operator &&, or built-in functions, such as LPAD( ), SUBSTRING( ). The simplest form of string expression is a string literal. Using CAST expressions, the data type of values can be converted.
Figure 133: Support For Joins In CDS Views
ABAP CDS support INNER joins, LEFT OUTER & RIGHT OUTER joins. Join conditions can be inserted before or after the select list. Use the brackets to implement complex joins operations. If joins are used no asterix is supported on SELECT statements.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
225
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 134: Use of Annotations In CDS Views
Annotations allow specifying ABAP-specific additional information, such as how records of the view should be buffered by the ABAP table buffer, or whether the view is client-dependent or not. Note that, by default, CDS views are considered client-dependent, and that you do not have to include client fields explicitly in the field list or in the join conditions.
Figure 135: Aggregations, Grouping, Filtering Groups
226
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
With ABAP Core Data Services, you can define views that include the calculation of aggregations and grouping records and filtering groups. The GROUP BY and HAVING clauses may be familiar from Open SQL or standard SQL.
Figure 136: Where Conditions in CDS Views
It is also possible to include WHERE conditions in CDS view definitions.
Figure 137: Unions
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, • •
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, duplicate rows are not removed
Note that this is not supported in new Open SQL yet.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
227
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Figure 138: Selecting Data Using CDS Views
The Open SQL SELECT statement is used in ABAP to select data from a CDS view. You can use the ABAP Dictionary name, respectively the SQL view name, of the CDS view in the SELECT statements FROM clause. When using the new Open SQL syntax, you can, and are recommended to, use the CDS view name, as specified using the DEFINE VIEW keywords in the DDL source file. Note that the CDS view cannot have the same name as the SQL view / ABAP Dictionary view and the CDS view name also does not have to equal the name of the ABAP DDL source. Also note that CDS views are client-dependent by default, even if no client field is included in the view definition. It is in fact recommended to not include client fields in the definition of CDS views. To retrieve data from a client-dependent CDS view, but from a different client, use the new Open SQL syntax USING CLIENT. See program HA400_CDS_QUERY_DEMO for examples.
228
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Exercise 13: Core Data Services in ABAP Exercise Objectives After completing this exercise, you will be able to: • Take advantage of the advanced view definition techniques using Core Data Services (CDS) in the AS ABAP. The exercise consists of the following steps: Create a simple Core Data Services (CDS) view Extend a simple CDS view with built-in functions and expressions Working with Annotations
Business Example Template: Report HA400_CDS_T1 Solution: Report HA400_CDS_S1 DDL Sources: HA400_DDL_SIMPLE_S1 and H400_DDL_ADVANCED_S2
Task 1: Create a simple DDL Source 1.
Create a new DDL source ZHA400_DDL_SIMPLE_## in your corresponding ABAP package ZHA400_##.
2.
In the DDL Source, define a new DDL view name zha400_ddl_simple_## and implement the select clause to fetch data from the sales order table SNWD_SO and use alias name so for the sales order table.
3.
Specify the projection list of the DDL source: the view should only retrieve columns so_id, currency_code, gross_amount and created_at.
Task 2: Create DDL annotation AbapCatalog.sqlViewName 1.
Use the quick fix functionality in the ABAP Development Tools to create the sqlViewName annotation. The final sqlViewName should be ZHA400_CDS_1_##
2.
Save and activate the DDL source.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
229
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 3: Display the “Create Statement” of the SQL view 1.
Navigate to your corresponding SQL view and open the view.
2.
Open the create statement for your Core Data Services view.
Task 4: Open the Data Preview to display the content 1.
Open the Data Preview to fetch data from the database
Task 5: Create an advanced DDL Source using JOINS and built-in functions 1.
Create a new DDL source ZHA400_DDL_ADVANCED_## in your ABAP package ZHA400_##. Hint: Use eclipse shortcut ALT+LEFT
2.
In this source, define a new DDL view name zha400_ddl_advanced_##, SQL view name zha400_cds_2_## and implement the select clause to fetch data from the sales order table SNWD_SO and use alias name so for the sales order table.
3.
Implement an inner join with the business partner SNWD_BPA table on columns buyer_guid and node_key.
4.
Implement a left outer join to the sales order invoice header table SNWD_SO_INV_HEAD on columns node_key and so_guid to display all sales orders which do not have an invoice yet. Hint: Do not forget to add the where clause for the left outer join.
5.
Specify the projection list of the DDL source for columns company_name, currency_code and gross_amount.
6.
Calculate the sum of the gross amount from the table SNWD_SO using the aggregation function sum. Hint: An alias name is required for the result of an aggregate function.
Continued on next page
230
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
7.
Use annotations to indicate that column currency_code contains the currency code for aggregated column gross_amount
8.
Use a built-in function substring to shorten the column company name
9.
Save and activate your DDL source.
10. Open the Data Preview to display your result.
Task 6: Create a report and understand the template, call the Core Data Services view using OpenSQL and display the data.
2014
1.
Create a copy of report HA400_CDS_T1 in your package ZHA400_## (suggested name: ZHA400_##_CDS).
2.
Implement an Open SQL statement calling either the SQL view or the DDL view of the previous task.
3.
Activate and execute the program.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
231
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Solution 13: Core Data Services in ABAP Task 1: Create a simple DDL Source 1.
2.
3.
Create a new DDL source ZHA400_DDL_SIMPLE_## in your corresponding ABAP package ZHA400_##. a)
Open the ABAP perspective if not yet opened.
b)
Go to the Project Explorer and navigate to your package ZHA400_## (where ## represents your group number).
c)
Create a new DDL Source entity. Right-click your package and select the context menu item New → Other ABAP Repository Object.
d)
Expand node Dictionary and choose item DDL Source.
e)
In the dialog, fill in the name ZHA400_DDL_SIMPLE_## and maintain a description for your new DDL Source object
f)
Press Next and Finish.
In the DDL Source, define a new DDL view name zha400_ddl_simple_## and implement the select clause to fetch data from the sales order table SNWD_SO and use alias name so for the sales order table. a)
Begin with the statement DEFINE VIEW followed by the name of the CDS view entity zha400_ddl_simple_## and a simple AS SELECT FROM statement with the table SNWD_SO.
b)
Specify an alias name, e.g. SO, for the table SNWD_SO.
Specify the projection list of the DDL source: the view should only retrieve columns so_id, currency_code, gross_amount and created_at. a)
Define select list between curly brackets
b)
Define the first field SO.SO_ID of the select list between curly brackets and mark it as key field using the keyword KEY. Hint: You can make use the code completion feature (CTRL+SPACE). Hint: Use the alias SO as prefix for the columns in the projection list.
Continued on next page
232
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Task 2: Create DDL annotation AbapCatalog.sqlViewName 1.
Use the quick fix functionality in the ABAP Development Tools to create the sqlViewName annotation. The final sqlViewName should be ZHA400_CDS_1_## a)
You should see an error message: “Name of SQl View missing; annotation AbapCatalog.sqlViewName must be specified ” Hint: Hover your mouse over the error icon in order to read the long error message. Hint: When defining a CDS view, the name of the associated SQL view must be specified. This is done using a specific annotation.
2.
b)
Add the missing SQL view name to the CDS view definition. Set the cursor to the underlined statement View (or click on the warning icon) and use the Quick Fix feature (CTRL+1) for the correction. The Editor will create an annotation with the name of the associated SQL view.
c)
Replace the proposed sqlViewName ZHA400_DDL_SIMP with the desired name ZHA400_CDS_1_##.
Save and activate the DDL source. a)
Save your DDL Source object.
b)
Check and activate it.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
233
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 3: Display the “Create Statement” of the SQL view 1.
Navigate to your corresponding SQL view and open the view. a)
After the activation was successful, an additional ABAP Dictionary object will be generated: It is the associated DDL SQL view. You can have a look at it in the Views folder. Hint: You may have to refresh your package in order to see the object. Select your package and press F5.
b)
Double-click on your view ZHA400_CDS_1_##.
c)
The ABAP Data Dictionary (SE11) is now opened and you can see the generated Dictionary entity. Hint: The DDL SQL view is fully managed by the ABAP Dictionary. It cannot be edited, and the semantic information maintained in the DDL Source is not available. Hint: The client field MANDT was generated automatically.
2.
Open the create statement for your Core Data Services view. Check the generated SQL Source. Therefore select menu path Menu → Extras → CREATE Statement. The definition of the database view is displayed in the corresponding pop-up window.
a)
Task 4: Open the Data Preview to display the content 1.
Open the Data Preview to fetch data from the database a)
Navigate back to your DDL Source
b)
Right-click your ABAP DDL Source in the Project Explorer and select the context menu item Open Data Preview.
Continued on next page
234
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Task 5: Create an advanced DDL Source using JOINS and built-in functions 1.
Create a new DDL source ZHA400_DDL_ADVANCED_## in your ABAP package ZHA400_##. Hint: Use eclipse shortcut ALT+LEFT
2.
3.
a)
Right-click the Dictionary folder and select the context menu item New → DDL Source.
b)
In the dialog, fill in the name ZHA400_DDL_ADVANCED_## and maintain a description for your new DDL Source object.
c)
Press Next and Finish.
In this source, define a new DDL view name zha400_ddl_advanced_##, SQL view name zha400_cds_2_## and implement the select clause to fetch data from the sales order table SNWD_SO and use alias name so for the sales order table. a)
Start your Implementation and start with the statement DEFINE VIEW followed by the name of the CDS view entity zha400_ddl_advanced_##.
b)
Add a simple AS SELECT FROM statement from table SNWD_SO.
c)
Specify the alias SO for the table SNWD_SO.
d)
Add the INNER JOIN and LEFT OUTER JOIN conditions as described below.
Implement an inner join with the business partner SNWD_BPA table on columns buyer_guid and node_key. a) inner join snwd_bpa as bp on so.buyer_guid = bp.node_key
4.
Implement a left outer join to the sales order invoice header table SNWD_SO_INV_HEAD on columns node_key and so_guid to display all sales orders which do not have an invoice yet. Hint: Do not forget to add the where clause for the left outer join. a) left outer join snwd_so_inv_head on so.node_key
as so_inv
= so_inv.so_guid
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
235
Unit 4: Optimizing ABAP On Primary Database SAP HANA
5.
HA400
Specify the projection list of the DDL source for columns company_name, currency_code and gross_amount. a)
Define select list between curly brackets after the Join statements and use following columns: COMPANY_NAME (mark it as key field) CURRENCY_CODE GROSS_AMOUNT
Hint: The field COMPANY_NAME is from the table SNWD_BPA and requires the alias BP. The other fields are from the table SNWD_SO and required the alias SO. b) key bp.company_name, so.currency_code, so.gross_amount
Continued on next page
236
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
6.
Calculate the sum of the gross amount from the table SNWD_SO using the aggregation function sum. Hint: An alias name is required for the result of an aggregate function. a)
In the select list, replace the field so.gross_amount with SUM(so.gross_amount) and specified sum_gross_amount as alias sum(so.gross_amount) as sum_gross_amount
Hint: An alias name is required for the result of an aggregate function. b)
An error is displayed in your CDS view definition. Move your mouse over the error icon in order to read the long error message. Hint: If you use aggregation functions all selected fields except those used in aggregate functions have to be specified in the GROUP BY clause.
c)
Add the GROUP BY clause in your coding. Hint: You can use the Quick Fix (CTRL+1) feature to create the GROUP BY clause.
d)
Use Quick Fix (CTRL+1) again, to add the sqlViewName annotation. Change the suggested SQL view name to zha400_cds_2_##.
e)
Your CDS view should only retrieve those sales orders where no invoice exists. Add a WHERE condition after the select list and before the GROUP BY clause in order to exclude the sales orders with invoices.
f) where so_inv.node_key is null group by bp.company_name, so.currency_code
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
237
Unit 4: Optimizing ABAP On Primary Database SAP HANA
7.
Use annotations to indicate that column currency_code contains the currency code for aggregated column gross_amount a)
8.
HA400
Add annotation @Semantics.currencyCode before column so.currency_code , and annotation @Semantics.amount.currencyCode:'SO.CURRENCY_CODE' before column sum(so.gross_amount)
Use a built-in function substring to shorten the column company name a) key substring(bp.company_name, 0, 10) as name,
9.
Save and activate your DDL source. a)
Save your DDL Source object.
b)
Check and activate it.
10. Open the Data Preview to display your result. a)
After the activation was successful, open the Data Preview.
Task 6: Create a report and understand the template, call the Core Data Services view using OpenSQL and display the data. 1.
Create a copy of report HA400_CDS_T1 in your package ZHA400_## (suggested name: ZHA400_##_CDS). a)
Right click the report and choose Duplicate.
b)
Change the package to your package ZHA400_##.
c)
Enter a name e.g. ZHA400_##_CDS and finish the wizard.
Continued on next page
238
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
2.
Implement an Open SQL statement calling either the SQL view or the DDL view of the previous task. a)
Declare a variable to store the data.
b) DATA lt_data TYPE TABLE OF zha400_ddl_advanced_##.
c)
Implement your SQL query to fetch the data from either the SQL View or the DDL View.
d) SELECT * FROM zha400_ddl_advanced_## INTO TABLE @lt_data.
Hint: You have to use the new SQL syntax in order to be able to fetch data from the DDL view. e)
Use method CL_DEMO_OUT=>DISPLAY_DATA to quickly display the result.
f) cl_demo_output=>display_data( name
= 'Total sales per customer.'
value = lt_data ).
3.
Activate and execute the program. a)
–
Result Source code extract from the solution (DDL Source HA400_DDL_SIMPLE_S1) @AbapCatalog.sqlViewName: 'HA400_CDS_S1' define view ha400_ddl_simple_s1 as select from snwd_so as so { key so.so_id, so.currency_code, so.gross_amount, so.created_at }
(DDL Source HA400_DDL_ADVANCED_S2)
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
239
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
@AbapCatalog.sqlViewName: 'HA400_CDS_S2' define view ha400_ddl_advanced_s2 as select from snwd_so
as so
inner join snwd_bpa as bp on so.buyer_guid = bp.node_key left outer join snwd_so_inv_head on so.node_key
as so_inv
= so_inv.so_guid
{ key substring(bp.company_name, 0, 10) as name, @Semantics.currencyCode so.currency_code, @Semantics.amount.currencyCode:'SO.CURRENCY_CODE' sum(so.gross_amount) as sum_gross_amount } where so_inv.node_key is null group by bp.company_name, so.currency_code
(Program HA400_CDS_S1) REPORT ha400_cds_s1. * *** Declare your variable either the SQL view or DDL source *** DATA lt_data TYPE TABLE OF ha400_ddl_advanced_s2. * *** Implement your SQL Query *** SELECT * FROM ha400_ddl_advanced_s2 INTO TABLE @lt_data. ** *** Write and display the data *** cl_demo_output=>display_data( name
= 'Total sales per customer.'
value = lt_data ).
240
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Core Data Services in ABAP
Lesson Summary You should now be able to: • Define database views using Core Data Services (CDS) in ABAP • Use expressions, joins and unions in CDS-based view definitions • Use aggregation and grouping in CDS-based view definitions • Use Open SQL to select data based on CDS views
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
241
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Lesson: Associations in Core Data Services Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Use associations in Core Data Services
Business Example –
Figure 139: Associations – Need and Syntax
Core Data Services 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. 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 re-used.
242
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Associations in Core Data Services
Core Data Services treat relationships, called associations in CDS, as first-class citizens: • •
•
Associations can be defined within CDS views and be exposed via the projection list. This can simplify defining views on top of other views Path expressions can be used to “navigate” along associations. These expressions can be used in all places where column names or tables names can be used. They are automatically translated into join clauses. – Path steps in the from clause translate to inner joins – All other path steps translate to left outer joins ABAP CDS also support associations in SELECT-, FROM-, WHERE- and HAVING-clauses and to define “filter conditions” in associations
The figure shows an extract from DDL source HA400_DDL_SO_WITH_NOTES for the full source. View the full source to also see the definition of the associations used.
Figure 140: When to use Enhanced Open SQL vs. CDS Views
With the introduction of enhancements to Open SQL on one hand and Core Data Services on the other hand, the question arises how they relate and when to favor which of these two options. Open SQL and CDS view definition capabilities complement each other. As of now, they do not provide the same level of features in queries, e.g. Open SQL does not support UNION or using path expressions, whereas CDS views dont support using system fields. But SAP aims at providing a common set of features in Open SQL queries and CDS views over time.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
243
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Best practice is to • •
244
Use an Open SQL-based query including joins, calculations etc., if the query is needed once only, in the sense of: in a single piece of code. Use CDS views in cases where the base query serves several pieces of code that can apply different projections or WHERE clauses on top.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Associations in Core Data Services
Exercise 14: Use Associations in Core Data Services in ABAP Exercise Objectives After completing this exercise, you will be able to: • Define a Core Data Services View in ABAP that uses associations.
Business Example You have a CDS view combining sales order information with corresponding sales order notes, and a CDS view combining basic customer data with the corresponding address information. You now want to extend the first CDS view to include customer information as well. Template: DDL Source HA400_DDL_SO_WITH_CUST_T1 DDL Source HA400_DDL_CUSTOMERS Solution: DDL Sources: HA400_DDL_SO_WITH_CUST_S1
Task 1: Copy and understand template Create a new DDL source, open the template DDL source, copy its code into your new DDL source and adjust the relevant names. 1.
Create a new DDL source. Suggested name is ZHA400_DDL_SO_WITH_CUST_## .
2.
Open the template DDL source HA400_DDL_SO_WITH_CUST_T1 and copy its code into your new DDL source.
3.
Activate your DDL source and perform a data preview.
4.
Understand your DDL source: The CDS view is primarily based on table and exposes some of the table's columns. The view already includes an to another CDS view called , and this way to table , holding sales order header notes. But the view does not explicitly expose the sales header notes yet. Fill in the blanks to complete the sentence.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
245
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 2: Extend your DDL source Extend your DDL source to make it explicitly expose the English sales order header note. In addition, extend it with an association to DDL source HA400_DDL_CUSTOMERS toinclude the customer ID, company name and country and allow further DDL sources built on top to access any column of DDL source HA400_DDL_CUSTOMERS
246
1.
Extend your DDL source to make it explicitly expose the English sales order header note.
2.
Add association to DDL source HA400_DDL_CUSTOMERS. Note that a sales order can only have one customer.
3.
Making use of the association, expose the customer ID and company name.
4.
Making use of the fact the CDS view HA400_DDL_CUSTOMERS includes an association to the customer address, also expose the customer country.
5.
Enable DDL sources defined on top of your new DDL source to access any column of DDL source HA400_DDL_CUSTOMERS.
6.
Activate your DDL source and perform a data preview.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Associations in Core Data Services
Solution 14: Use Associations in Core Data Services in ABAP Task 1: Copy and understand template Create a new DDL source, open the template DDL source, copy its code into your new DDL source and adjust the relevant names. 1.
Create a new DDL source. Suggested name is ZHA400_DDL_SO_WITH_CUST_## . a)
2.
3.
Open the template DDL source HA400_DDL_SO_WITH_CUST_T1 and copy its code into your new DDL source. a)
Press toolbar button Open ABAP Development Object or press CTRL-SHFT-A.
b)
Start typing the template DDL source name HA400_DDL_SO ... into the search field and double-click the DDL source in the matching items list. Make sure to select the template DDL source.
c)
Select the complete source code text and copy and paste it into the editor view of your new DDL source.
d)
In your DDL source, adjust the @AbapCatalog.sqlViewName, e.g. to ZHA400_CDS_3_##, and the CDS name (following the define view key words), e.g. to ZHA400_DDL_SO_WITH_CUST_##.
Activate your DDL source and perform a data preview. a)
4.
Complete this step as before.
Complete this step as before.
Understand your DDL source: The CDS view is primarily based on table SNWD_SO (Sales Orders) and exposes some of the table's columns. The view already includes an association to another CDS view called HA400_DDL_NOTES, and this way to table SNWD_TEXTS, holding sales order header notes. But the view does not explicitly expose the sales header notes yet. Answer: SNWD_SO (Sales Orders), association, HA400_DDL_NOTES, SNWD_TEXTS
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
247
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Task 2: Extend your DDL source Extend your DDL source to make it explicitly expose the English sales order header note. In addition, extend it with an association to DDL source HA400_DDL_CUSTOMERS toinclude the customer ID, company name and country and allow further DDL sources built on top to access any column of DDL source HA400_DDL_CUSTOMERS 1.
Extend your DDL source to make it explicitly expose the English sales order header note. a)
2.
Add association to DDL source HA400_DDL_CUSTOMERS. Note that a sales order can only have one customer. a)
3.
Add lines customer.bp_id as customer_id, customer.company_name as customer_name, ,to the column list, see source code extract from model solution.
Making use of the fact the CDS view HA400_DDL_CUSTOMERS includes an association to the customer address, also expose the customer country. a)
5.
Add lines association [0..1] to ha400_ddl_customers as customer on buyer_guid = customer.customer_key to the from clause, see source code extract from model solution.
Making use of the association, expose the customer ID and company name. a)
4.
Add line so_note[ language = 'E' ].text as so_note to the column list, see source code extract from model solution.
Add line customer.address.country as customer_country, to the column list, see source code extract from model solution.
Enable DDL sources defined on top of your new DDL source to access any column of DDL source HA400_DDL_CUSTOMERS. a)
Add line customer, to the column list, see source code extract from model solution.
Continued on next page
248
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Associations in Core Data Services
6.
Activate your DDL source and perform a data preview. a)
Complete this step as before.
Result
Source code extract from the solution (DDL Source HA400_DDL_SO_WITH_CUST_S1) @AbapCatalog.sqlViewName: 'HA400_CDS_S3' define view ha400_ddl_so_with_cust_s1 as select from snwd_so association [0..1] to ha400_ddl_customers as customer on buyer_guid = customer.customer_key association [0..*] to h400_ddl_notes as so_note on note_guid = so_note.note_key { node_key as sales_order_guid, // must be included for the association to customer buyer_guid, // must be included for the association to note note_guid as so_note_key, @Semantics.amount.currencyCode: 'CURRENCY_CODE'
gross_amount,
@Semantics.currencyCode
currency_code,
customer, customer.bp_id as customer_id, customer.company_name as customer_name, customer.address.country as customer_country, so_note[ language = 'E' ].text
as so_note
}
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
249
Unit 4: Optimizing ABAP On Primary Database SAP HANA
HA400
Lesson Summary You should now be able to: • Use associations in Core Data Services
250
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Unit Summary
Unit Summary You should now be able to: • Describe code-to-data approaches possible with ABAP 7.4 SP05 • Use the new Open SQL syntax for simple SELECT statements • Use expressions in Open SQL SELECT statements • Define database views using Core Data Services (CDS) in ABAP • Use expressions, joins and unions in CDS-based view definitions • Use aggregation and grouping in CDS-based view definitions • Use Open SQL to select data based on CDS views • Use associations in Core Data Services
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
251
Unit Summary
252
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 5 Using ABAP-managed Database Procedures Unit Overview This unit is designed to teach you the following topics: • • •
Developing SAP HANA database procedures embedded into ABAP code Calling such ABAP-managed database procedures Debugging ABAP-managed database procedures
Unit Objectives After completing this unit, you will be able to: • • • • •
Understand the benefits of using ABAP Managed Database Procedures Create ABAP-managed database procedures Call ABAP-managed database procedures in ABAP Describe the authorizations required and user accounts involved to debug ABAP-managed database procedures Debug ABAP-managed database procedures
Unit Contents Lesson: ABAP-Managed Database Procedures............................254 Exercise 15: Create and call an ABAP-Managed Database Procedure....................................................................261 Lesson: Debugging ABAP-managed Database Procedures..............271 Exercise 16: Debug an ABAP-managed Database Procedure.......275
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
253
Unit 5: Using ABAP-managed Database Procedures
HA400
Lesson: ABAP-Managed Database Procedures Lesson Overview This lesson explains the benefits of and how to develop and use ABAP-managed database procedures.
Lesson Objectives After completing this lesson, you will be able to: • • •
Understand the benefits of using ABAP Managed Database Procedures Create ABAP-managed database procedures Call ABAP-managed database procedures in ABAP
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system is on release 7.4 SP05 or higher and uses SAP HANA as primary database. You realize that the performance improvement you aim for cannot be reached using native SQL or information models alone.
Motivation for ABAP-managed Database Procedures
Figure 141: Using Stored Procedures in ABAP < 7.40
254
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
As other database systems support stored procedures as well, calling and creating them in ABAP is possible since a long time. Besides the fact that stored procedures are database-specific, using them lead to two questions: •
How to call the stored procedures in ABAP code? The answer to this question before ABAP 7.4 is: native SQL. Using the ABAP Database Connectivity API for this purpose is preferable because it supports where-used analyses, exception handling and more. As seen earlier, calling a procedure this way may not be easy, especially since the SQL syntax cannot be checked at compile time.
•
How and where to manage the stored procedure code itself? –
You could decide for the “bottom-up” approach and manage the lifecycle of the stored procedure outside the ABAP stack. In this case, you had to to make sure that the database procedure was deployed into the corresponding database systems. In addition, you had to take care of different ABAP database schema names, for example in the ABAP development, test and production systems.
–
Alternatively, you could decide for the “top-down” approach and create the stored procedure using the ABAP stack, that is also using native SQL in an ABAP program. This removed the ABAP schema name and transport issues, but meant that creating the procedure in ABAP was not easy, again because of a lack of native SQL checks at compile time.
Figure 142: ABAP 7.4 SP05: ABAP-Managed Database Procedures
To remedy these shortcomings, starting with ABAP 7.4 SP05 SAP considerably improved using the top-down approach specifically for SAP HANA database procedures, through the introduction of ABAP-managed database procedures.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
255
Unit 5: Using ABAP-managed Database Procedures
HA400
Using the new ABAP Managed Database Procedures (AMDP), the editing, activation, transport and lifecycle management of the database procedures are performed on the ABAP application server. • • •
AMDP manages SQLScript source code in AS ABAP AMDP integrates SQLScript syntax check in ABAP syntax check AMDP creates and manages stored procedure runtime objects on HDB in the ABAP AS database schema
Using ABAP-managed database procedures is thus the recommended way of using SAP HANA database procedures in ABAP applications.
Creating AMDPs
Figure 143: AMDPs: Integration of Database Procedures Into ABAP
The implementation of ABAP Managed Database Procedures is achieved using methods of ABAP classes. Whether a method is implemented in ABAP or native code e.g. SQL Script, is determined in the method implementation part, and not in the method definition part of the ABAP class. However, in order to create an AMDP method there are some pre-requisites which must be fulfilled in the class definition part, before a method can be used as an AMDP method.
256
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
Figure 144: AMDPs: Prerequisites in Class Definition
Classes which will act as a container for AMDPs have to implement a so called Marker Interface IF_AMDP_MARKER_HDB. AMDP method parameters can be Importing, Exporting or Changing parameters. Returning parameters cannot be used. In addition to this rule, all AMDP method parameters have to be passed by value, and must be of either table or scalar types. Also note that any table parameter line types can only have elementary components as there is no support for nested tables. Scalar importing parameters can have default values. If ABAP Dictionary structures are used for typing, the method cannot be implemented as an AMDP. 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.
Figure 145: Implementation of AMDP Methods
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
257
Unit 5: Using ABAP-managed Database Procedures
HA400
AMDP methods are identified with the syntax BY DATABASE PROCEDURE. The database system (e.g. HDB) and language (e.g. SQLSCRIPT) must also be specified. Optionally, the AMDP method can be marked as a READ-ONLY database procedure. It is also necessary to list all ABAP Dictionary tables, views and other procedures used in the procedure body in the USING clause. The method body can then be implemented using native SQL Script source code. Almost the full SQL Script reference can be used in the method body except the CE function CE_COLUMN_TABLE. “--” can be used in the method body as a SQL Script comment, but “*” is also possible at position 1 in each line, just like in ABAP.
Figure 146: AMDP Method – SQLScript Example
All ABAP Dictionary tables or views, and other AMDP methods which 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 prefix. AMDP methods called inside an AMDP body have to be declared with their full names (i.e. 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 upper case. Any objects outside of the SAP schema are not ABAP managed, and therefore they are not part of the USING clause. Developers have to make sure that they are available at runtime.
258
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
Figure 147: AMDP Methods – Syntax Error Handling
AMDP can detect 3 types of syntax errors in active or inactive source code: • • •
Database independent syntax errors: Parameters not passed by value, wrong parameter types or cyclic method calls 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 that the syntax checks depend on the underlying database system → No SQLScript checks on other database platforms. AMDP syntax check result looks almost like ABAP syntax check result, including error positioning. AMDP provides detailed long text information. Use the ABAP Development Tools for full AMDP support: • • •
Semantic code completion for the ABAP part Syntax coloring for SQLScript Customizable shading of native SQL code via Window → Preferences → General → Appearance → Colors and Fonts
The classical SAPGUI ABAP Workbench provides restricted support only. AMDP methods can be edited using the source based editor only.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
259
Unit 5: Using ABAP-managed Database Procedures
HA400
Using AMDPs
Figure 148: Calling AMDP Methods
An AMDP method is called like any ABAP method. • •
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: • • • •
260
The database procedure is created at first use (lazy approach) In the SAP schema A new version of the database procedure is created each time the source code or dependent objects change Obsolete versions are deleted asynchronously
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
Exercise 15: Create and call an ABAP-Managed Database Procedure Exercise Objectives After completing this exercise, you will be able to: • Create ABAP-managed database procedures • Call an ABAP-managed database procedure
Business Example Template: Report HA400_AMDP_CLASSIFY_T1 Class CL_HA400_AMDP_CLASSIFY_T1 Solution: Report HA400_AMDP_CLASSIFY_S1 Class CL_HA400_AMDP_CLASSIFY_S1
Task 1: Simple customer classification Create an ABAP managed database procedure to perform a simple customer classification. 1.
Create a copy of class CL_HA400_ AMDP_CLASSIFY_T1 in your package ZHA400_## (suggested name: ZCL_HA400_ AMDP_CLASSIFY_ ##, where ## is your group number).
2.
Implement the marker interface IF_AMDP_MARKER_HDB in the public section of your class.
3.
Define the parameter interface of method CLASSIFY_SIMPLE. Use an internal table it_bp_id (type tt_bp_id) and a field iv_client (type sy-mandt) as importing parameters and internal table et_classification (type tt_bp_classification) as exporting parameter.
4.
Implement the method CLASSIFY_SIMPLE as an ABAP managed database procedure for database system HDB and database language SQLScript.
5.
Implement the SQLScript coding within the method CLASSIFY_SIMPLE. Select the customer id (bp_id), the company name (company_name), the literal constant 3 as category, and the constant ‘Standard’ as category_txt
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
261
Unit 5: Using ABAP-managed Database Procedures
HA400
from the business partner table snwd_bpa. Select only results for the given client (input parameter iv_client) and the given list of customers (input table it_bp_id). Sort the result set by customer ids and company name. 6.
Save and activate the class.
7.
Create a copy of report HA400_AMDP_CLASSIFY_T1 in your package ZHA400_## (suggested name: ZHA400_ AMDP_CLASSIFY_##, where ## is your group number).
8.
Analyze the report. Declare a variable lo_classifier of type reference to your class ZCL_HA400_ AMDP_CLASSIFY_ ##. Create an instance of the class. Implement the call of method CLASSIFY_SIMPLE. Hint: The internal table lt_bp_id contains the list of customers subject to the customer classification procedure and can be used as input parameter for CLASSIFY_SIMPLE.
9.
Save, activate, and execute the report.
Task 2: More advanced customer classification Create an ABAP managed database procedure to perform a customer classification based on the number of sales order invoices per customer. This task is very similar to the previous task but uses a more evolved SQLScript implementation in the ABAP managed database procedure. 1.
Navigate to class ZCL_HA400_ AMDP_CLASSIFY_ ## and define the parameter interface of method CLASSIFY_BY_INVC. Use the internal table it_bp_id (type tt_bp_id) and the variable iv_client (type sy-mandt) as importing parameters and the internal table et_classification (type tt_bp_classification) as exporting parameter. Hint: The parameter interfaces of method CLASSIFY_BY_INVC and CLASSIFY_SIMPLE are identical; you may just use copy and paste.
2.
Implement the method CLASSIFY_ BY_INVC as an ABAP managed database procedure for database system HDB and database language SQLScript.
3.
Implement the SQLScript coding within the method CLASSIFY_ BY_INVC. Select the customer id (bp_id), the company name (company_name), and the number of sales order invoices (count on a column of table snwd_so_inv_head). Use an inner join between table snwd_bpa and Continued on next page
262
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
snwd_so_inv_head. Select only results for the given client (input parameter iv_client) and the given list of customers (input table it_bp_id). Sort the result set by customer ids and company name. The result set (suggested name: lt_inv_count) of this first query is used in a second select statement. Use a case statement to classify the customers based on the number of invoices according to the following metric: • Category 1 / “Low revenue”: Customers with less than 1.000 invoices • Category 2 / “Premium”: Customers with more than 15.000 invoices • Category 3 / “Standard”: all others 4.
Save and activate the class.
5.
Navigate to your report ZHA400_ AMDP_CLASSIFY _##. Implement the call of method CLASSIFY_BY_INVC. Hint: As the parameter interfaces of CLASSIFY_SIMPLE and CLASSIFY_BY_INVC are identical, the method calls are identical as well.
6.
2014
Save, activate, and execute the report.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
263
Unit 5: Using ABAP-managed Database Procedures
HA400
Solution 15: Create and call an ABAP-Managed Database Procedure Task 1: Simple customer classification Create an ABAP managed database procedure to perform a simple customer classification. 1.
2.
Create a copy of class CL_HA400_ AMDP_CLASSIFY_T1 in your package ZHA400_## (suggested name: ZCL_HA400_ AMDP_CLASSIFY_ ##, where ## is your group number). a)
In the ABAP perspective of the SAP HANA Studio, open in the package HA400_PRIMDB_EXERCISE, navigate to Source Library → Classes → CL_HA400_ AMDP_CLASSIFY_T1. Right-click on the class and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the class name ZCL_HA400_ AMDP_CLASSIFY_## (## is your group number). Press Next.
Implement the marker interface IF_AMDP_MARKER_HDB in the public section of your class. a)
3.
Define the parameter interface of method CLASSIFY_SIMPLE. Use an internal table it_bp_id (type tt_bp_id) and a field iv_client (type sy-mandt) as importing parameters and internal table et_classification (type tt_bp_classification) as exporting parameter. a)
4.
Remove the comments in the method declaration prepared.
Implement the method CLASSIFY_SIMPLE as an ABAP managed database procedure for database system HDB and database language SQLScript. a)
5.
Implement the interface if_amdp_marker_hdb in the public section of the class.
In the class implementation part, enhance the method implementation of CLASSIFY_SIMPLE with the ‘by database procedure for hdb language sqlscript options read-only using snwd_bpa’ clause.
Implement the SQLScript coding within the method CLASSIFY_SIMPLE. Select the customer id (bp_id), the company name (company_name), the literal constant 3 as category, and the constant ‘Standard’ as category_txt
Continued on next page
264
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
from the business partner table snwd_bpa. Select only results for the given client (input parameter iv_client) and the given list of customers (input table it_bp_id). Sort the result set by customer ids and company name. a)
See the source code extract from the sample solution. Hint: More information on the SQLScript syntax can be found in http://help.sap.com/hana/SAP_HANA_SQL_Script_Reference_en.pdf
6.
Save and activate the class. a)
7.
8.
Click on the save button (shortcut CTRL+S) and the activate button (shortcut CTRL+F3).
Create a copy of report HA400_AMDP_CLASSIFY_T1 in your package ZHA400_## (suggested name: ZHA400_ AMDP_CLASSIFY_##, where ## is your group number). a)
In the Project Explorer, navigate to Source Library → Programs → HA400_AMDP_CLASSIFY_T1. Right-click on the program and choose Duplicate from the context menu.
b)
Enter the package name ZHA400_## and the program name ZHA400_AMDP_CLASSIFY_## (## is your group number). Press Next.
Analyze the report. Declare a variable lo_classifier of type reference to your class ZCL_HA400_ AMDP_CLASSIFY_ ##. Create an instance of the class. Implement the call of method CLASSIFY_SIMPLE. Hint: The internal table lt_bp_id contains the list of customers subject to the customer classification procedure and can be used as input parameter for CLASSIFY_SIMPLE.
9.
a)
Declare lo_classifier as reference to your class ZCL_HA400_AMDP_CLASSIFY_##. Just remove the comment and adapt the class name.
b)
Remove the comment for CREATE OBJECT lo_classifier.
c)
Implement the method call of CLASSIFY_SIMPLE, export lt_bp_id and sy-mandt (alternatively cl_abap_syst=>get_client( ) ) and import the result into the internal table lt_classification.
Save, activate, and execute the report. a)
Complete this step as you learned to do in previous exercises. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
265
Unit 5: Using ABAP-managed Database Procedures
HA400
Task 2: More advanced customer classification Create an ABAP managed database procedure to perform a customer classification based on the number of sales order invoices per customer. This task is very similar to the previous task but uses a more evolved SQLScript implementation in the ABAP managed database procedure. 1.
Navigate to class ZCL_HA400_ AMDP_CLASSIFY_ ## and define the parameter interface of method CLASSIFY_BY_INVC. Use the internal table it_bp_id (type tt_bp_id) and the variable iv_client (type sy-mandt) as importing parameters and the internal table et_classification (type tt_bp_classification) as exporting parameter. Hint: The parameter interfaces of method CLASSIFY_BY_INVC and CLASSIFY_SIMPLE are identical; you may just use copy and paste.
2.
a)
In the project explorer, open the class ZCL_HA400_ AMDP_CLASSIFY_## (## is your group number).
b)
Complete the definition of method CLASSIFY_BY_INVC (analog to the parameter interface of CLASSIFY_SIMPLE), i.e. define the importing by value parameter it_bp_id (type tt_bp_id) and iv_client (type sy-mandt) and the exporting parameter et_classification (type tt_bp_classification).
Implement the method CLASSIFY_ BY_INVC as an ABAP managed database procedure for database system HDB and database language SQLScript. a)
3.
In the class implementation part, enhance the method implementation of CLASSIFY_ BY_INVC with the ‘by database procedure for hdb language sqlscript options read-only using snwd_bpa snwd_so_inv_head’ clause.
Implement the SQLScript coding within the method CLASSIFY_ BY_INVC. Select the customer id (bp_id), the company name (company_name), and the number of sales order invoices (count on a column of table snwd_so_inv_head). Use an inner join between table snwd_bpa and snwd_so_inv_head. Select only results for the given client (input parameter iv_client) and the given list of customers (input table it_bp_id). Sort the result set by customer ids and company name. The result set (suggested name: lt_inv_count) of this first query is used in a second select statement. Use a case statement to classify the customers based on the number of invoices according to the following metric: Continued on next page
266
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
• Category 1 / “Low revenue”: Customers with less than 1.000 invoices • Category 2 / “Premium”: Customers with more than 15.000 invoices • Category 3 / “Standard”: all others a) 4.
See the source code extract from the sample solution.
Save and activate the class. a)
5.
Complete this step as you learned to do in previous exercises.
Navigate to your report ZHA400_ AMDP_CLASSIFY _##. Implement the call of method CLASSIFY_BY_INVC. Hint: As the parameter interfaces of CLASSIFY_SIMPLE and CLASSIFY_BY_INVC are identical, the method calls are identical as well.
6.
a)
In the project explorer, open your report ZHA400_ AMDP_CLASSIFY_## (## is your group number).
b)
Implement the method call of CLASSIFY_BY_INVC, export lt_bp_id and sy-mandt (alternatively cl_abap_syst=>get_client( ) ) and import the result into the internal table lt_classification.
Save, activate, and execute the report. a)
Complete this step as you learned to do in previous exercises.
Result Source code extract from model solution (Class CL_HA400_AMDP_CLASSIFY_S1) CLASS cl_ha400_amdp_classify_s1 DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES if_amdp_marker_hdb. " structure and table type for business partner node key: TYPES: BEGIN OF ty_bp_id, bp_id TYPE snwd_bpa-bp_id, END OF ty_bp_id . TYPES:
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
267
Unit 5: Using ABAP-managed Database Procedures
HA400
tt_bp_id TYPE STANDARD TABLE OF ty_bp_id . " structure and table type for classification: TYPES: BEGIN OF ty_bp_classification, bp_id
TYPE snwd_bpa-bp_id,
company_name TYPE snwd_company_name, category
TYPE sepm_oia_bp_category,
category_txt TYPE char20, END OF ty_bp_classification . TYPES: tt_bp_classification TYPE STANDARD TABLE OF ty_bp_classification WITH EMPTY KEY. "execute simple classification: METHODS classify_simple IMPORTING VALUE(it_bp_id)
TYPE tt_bp_id
VALUE(iv_client)
TYPE sy-mandt
EXPORTING VALUE(et_classification) TYPE tt_bp_classification. "execute classification by invoices assignment: METHODS classify_by_invc IMPORTING VALUE(it_bp_id)
TYPE tt_bp_id
VALUE(iv_client)
TYPE sy-mandt
EXPORTING VALUE(et_classification) TYPE tt_bp_classification. ENDCLASS.
CLASS cl_ha400_amdp_classify_s1 IMPLEMENTATION. METHOD classify_simple BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT OPTIONS READ-ONLY USING snwd_bpa. -- read customer and set "Standard" classification category: et_classification = SELECT bp_id, company_name, 3 AS category, 'Standard' as category_txt FROM snwd_bpa WHERE client
= :iv_client
AND bp_id IN ( select bp_id from :it_bp_id )
Continued on next page
268
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP-Managed Database Procedures
ORDER BY bp_id, company_name; ENDMETHOD. METHOD classify_by_invc BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT OPTIONS READ-ONLY USING snwd_so_inv_head snwd_bpa. -- get number of invoice per customer: lt_inv_count = SELECT bpa.bp_id as bp_id, bpa.company_name as company_name, COUNT(inv.node_key) as invoice_number FROM snwd_bpa as bpa INNER JOIN snwd_so_inv_head as inv ON inv.client
= bpa.client
AND inv.buyer_guid = bpa.node_key WHERE bpa.client = :iv_client AND bpa.bp_id IN ( select bp_id from :it_bp_id ) GROUP BY bpa.bp_id, bpa.company_name; -- replace invoice counter by classification code for customer et_classification = SELECT bp_id, company_name, CASE WHEN invoice_number <
1000 THEN 1
WHEN invoice_number >
15000 THEN 2
ELSE 3
--low revenue --premium --standard
END AS category, CASE WHEN invoice_number < WHEN invoice_number > ELSE 'Standard'
1000 THEN 'Low revenue' 15000 THEN 'Premium'
--low revenue --premium --standard
END AS category_txt FROM :lt_inv_count ORDER BY bp_id, company_name; ENDMETHOD. ENDCLASS.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
269
Unit 5: Using ABAP-managed Database Procedures
HA400
Lesson Summary You should now be able to: • Understand the benefits of using ABAP Managed Database Procedures • Create ABAP-managed database procedures • Call ABAP-managed database procedures in ABAP
270
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Debugging ABAP-managed Database Procedures
Lesson: Debugging ABAP-managed Database Procedures Lesson Overview This lesson covers how to debug ABAP-managed database procedures.
Lesson Objectives After completing this lesson, you will be able to: • •
Describe the authorizations required and user accounts involved to debug ABAP-managed database procedures 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. 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. As the procedures themselves can only be executed on the SAP HANA layer, procedures can only be debugged using 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 prerequisite:
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
271
Unit 5: Using ABAP-managed Database Procedures
HA400
Figure 149: Involved User Accounts and Authorizations
•
•
The ABAP user (ABAPDEV on the figure) executing the ABAP application needs the usual authorizations on ABAP level, i.e. 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 on the figure) who can access the database and perform the database debugging needs the authorizations to – – –
•
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 user.
The SAP user used by the ABAP system to access the database (SAPT85 on the figure). This user initiates executing the database procedure. Only the SAP user can grant the HANADEBUG user the permission to attach a debugger to SAP 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 user) for ABAP-managed database procedure AMDP_NAME in ABAP system SAPT85 are GRANT DEBUG ON "SAPT85"."AMDP_NAME" TO HANADEBUG; GRANT EXECUTE ON "SAPT85"."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 SAPT85 are:
272
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Debugging ABAP-managed Database Procedures
GRANT DEBUG ON SCHEMA "SAPT85" TO HANADEBUG; GRANT EXECUTE ON SCHEMA "SAPT85" TO HANADEBUG; GRANT ATTACH DEBUGGER to HANADEBUG;
Figure 150: Setting Up External Session Debugging in SAP HANA
To prepare the debugging session, perform the following steps:. •
•
• • •
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. Use one of the SAP HANA perspectives in the SAP HANA Studio (e.g. the Modeler perspective) to locate the database procedure in the database catalog. The procedure belongs to the ABAP system schema. Open the procedure named exactly like the method in the ABAP system. Additional procedures with extended names are generated stubs only. Set breakpoints as needed. 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 user, SAPT85 in the example. – Application User: The ABAP user, ABAPDEV in the example. Start a Debug thread
–
•
The debug thread doesn't 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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
273
Unit 5: Using ABAP-managed Database Procedures
HA400
Figure 151: 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. Else the SAP HANA system will keep waiting for sessions to attach a debugger to.
274
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Debugging ABAP-managed Database Procedures
Exercise 16: Debug an ABAP-managed Database Procedure Exercise Objectives After completing this exercise, you will be able to: • Create a Debug Configuration for External Session Debugging in the SAP HANA Studio. • Debug an ABAP-managed database procedure.
Business Example You want to debug an ABAP-managed Database Procedure because an ABAP application calling it does not return the expected results. ABAP Report and AMDP to be debugged: Report HA400_AMDP_CLASSIFY_S1 Database Procedure CL_HA400_AMDP_CLASSIFY_S1=>CLASSIFY_BY_INVC . If you finished the AMDP exercise successfully, use your own report ZHA400_ AMDP_CLASSIFY_## and AMDP ZCL_HA400_ AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC. If you did not finish the ADMP exercise, use the corresponding exercise's sample solution report HA400_AMDP_CLASSIFY_S1 and database procedure CL_HA400_AMDP_CLASSIFY_S1=>CLASSIFY_BY_INVC. Make sure to execute the report once before beginning with this exercise. Else the database procedure may not be generated in SAP HANA yet,
Task 1: Prepare External Session Debugging for the ABAP-managed database procedure. 1.
Locate ABAP-managed database procedure ZCL_HA400_AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC in the SAP HANA Studio.
2.
Set breakpoints in the database procedure
3.
Create a new Debug Configuration for SAP HANA Stored Procedures (suggested name: SAPT85).
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
275
Unit 5: Using ABAP-managed Database Procedures
4.
HA400
Configure External Session Debugging. To do so so, select , the SAP HANA System connection of and Set Filter Attributes. Enter the technical SAP User as and ABAP user as . Fill in the blanks to complete the sentence.
5.
Start the debugging thread.
Task 2: Debug ABAP-managed database procedure ZCL_HA400_ AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC 1.
Execute the ABAP application calling the database procedure
2.
Look at the values of the variables: View lists scalar input parameter with value and input parameter . Because the latter is a table, only the is shown. Fill in the blanks to complete the sentence.
276
3.
Inspect the value of input parameter IT_BP_ID.
4.
Resume execution until the ABAP application displays a result.
5.
Terminate the debugging session
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Debugging ABAP-managed Database Procedures
Solution 16: Debug an ABAP-managed Database Procedure Task 1: Prepare External Session Debugging for the ABAP-managed database procedure. 1.
2.
3.
4.
Locate ABAP-managed database procedure ZCL_HA400_AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC in the SAP HANA Studio. a)
Switch to the Modeler perspective in the SAP HANA Studio.
b)
In the Systems view, expand the node of the system connection and its Catalog sub-node.
c)
Expand the node representing the ABAP system schema, SAPT85, and its sub-node Procedures
Set breakpoints in the database procedure a)
Double-click item ZCL_HA400_AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC to open the procedure in an editor view.
b)
In the editor view, double-click in the grey bar and a few lines left of the code.
Create a new Debug Configuration for SAP HANA Stored Procedures (suggested name: SAPT85). a)
Open the Debug perspective in the SAP HANA Studio
b)
Press button Debug As → Debug Configurations or select menu item Run → Debug As ... → Debug Configurations
c)
Select SAP HANA Stored Procedure. Open the item's context menu and press New
d)
Enter a Name for the new Debug Configuration, e.g. SAPT85
e)
Select Debug an External Session
Configure External Session Debugging. To do so so, select Debug an External Session , the SAP HANA System connection of your SAP HANA user and Set Filter Attributes. Enter the technical SAP User SAPT85 as HANA User and your ABAP user as Application User. Answer: Debug an External Session, your SAP HANA user, SAPT85, HANA User, your, Application User
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
277
Unit 5: Using ABAP-managed Database Procedures
5.
HA400
Start the debugging thread. Press the Debug button. This closes the Debug configuration dialog and starts a debugging thread.
a)
Hint: Once the configuration is created, you can also start debug threads by pressing the Debug button and selecting the configuration from the drop-down listbox
Task 2: Debug ABAP-managed database procedure ZCL_HA400_ AMDP_CLASSIFY_##=>CLASSIFY_BY_INVC 1.
2.
Execute the ABAP application calling the database procedure a)
Switch to the ABAP perspective or an SAP GUI. Start report ZHA400_AMDP_CLASSIFY_## as usual.
b)
On the selection screen, select Classify by number of invoices to make sure the correct procedure is called.
c)
Switch back to the SAP HANA Studio, Debug perspective.
Look at the values of the variables: View Variables lists scalar input parameter IV_CLIENT with value 800 and input parameter IT_BP_ID. Because the latter is a table, only the number of rows is shown. Answer: Variables, IV_CLIENT, 800, IT_BP_ID, number of rows
3.
Inspect the value of input parameter IT_BP_ID. a)
4.
Resume execution until the ABAP application displays a result. a)
5.
Press F8 or button Resume.
Terminate the debugging session a)
278
Select variable IT_BP_ID and its context menu item Open Data Preview. The rows with the values are shown in a dedicated view as a result.
Press the Terminate button.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Debugging ABAP-managed Database Procedures
Lesson Summary You should now be able to: • Describe the authorizations required and user accounts involved to debug ABAP-managed database procedures • Debug ABAP-managed database procedures
Related Information • •
2014
See http://scn.sap.com/docs/DOC-51790 for a tutorial how to debug ABAP-managed database procedures SAP HANA stored procedures developed on the SAP HANA level (e.g. using the wizard in the Modeler perspective or SQL statements) can be debugged similarly.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
279
Unit Summary
HA400
Unit Summary You should now be able to: • Understand the benefits of using ABAP Managed Database Procedures • Create ABAP-managed database procedures • Call ABAP-managed database procedures in ABAP • Describe the authorizations required and user accounts involved to debug ABAP-managed database procedures • Debug ABAP-managed database procedures
280
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 6 SAP HANA Proxy Objects Unit Overview This unit is designed to teach the following topics: • •
Working with SAP HANA proxy objects to ease consumption of existing SAP HANA content Transporting existing SAP HANA content via an ABAP system
Unit Objectives After completing this unit, you will be able to: • • • • • • • • • •
Describe the bottom-up approaches to the code-to-data paradigm possible with ABAP 7.4 SP02 Create external views in the ABAP Dictionary Explain the mapping of SAP HANA data types and ABAP Dictionary types Adjust data type mappings Select from an external view with Open SQL Explain the use of Delivery Units Create delivery units and assign packages Explain the usage of HANA Transport Containers Create HANA Transport Containers and assign delivery units Use database procedure proxies in ABAP.
Unit Contents Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views .............................................................................283 Exercise 17: Create an External View for SAP HANA View and Use it in an Open SQL SELECT .................................................291 Lesson: Transport of SAP HANA Objects ...................................298 Exercise 18: Create HANA Transport Container for a Delivery Unit.303 Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies ...........................................................................308
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
281
Unit 6: SAP HANA Proxy Objects
HA400
Exercise 19: Call a Database Procedure Proxy for a SAP HANA Procedure in an ABAP Program ..........................................315
282
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • • •
Describe the bottom-up approaches to the code-to-data paradigm possible with ABAP 7.4 SP02 Create external views in the ABAP Dictionary Explain the mapping of SAP HANA data types and ABAP Dictionary types Adjust data type mappings Select from an external view with Open SQL
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system has been migrated to SAP HANA as its primary database, and runs on an ABAP release 7.4 SP02 or higher.
Code-to-Data with ABAP 7.4 ≥ SP02
Figure 152: Bottom-Up Approach with AS ABAP 7.4 ≥ SP02
The top-down approach to the code-to-data paradigm, using extended Open SQL, Core Data Services and ABAP-managed database procedures, is fully available starting with ABAP 7.4 SP05 only. When working on a lower release, you have to revert to the bottom up approach.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
283
Unit 6: SAP HANA Proxy Objects
HA400
Starting with ABAP 7.4 SP02, using the bottom-up approach is simplified. You can use existing SAP HANA artefacts natively in ABAP by: •
Exposing native SAP HANA column views as so called External Views in the ABAP Data Dictionary. Hint: This may also be helpful in ABAP 7.4 SP05 and higher, when Core Data Services in ABAP do not support all computations possible with calculated columns in SAP HANA column views or when an existing column view can be reused.
•
Exposing SAP HANA database procedures in the ABAP Data Dictionary as so called database procedure proxies. Caution: Actively using database procedure proxies is not recommended, as the feature becomes obsolete with ABAP 7.4 SP05. It is covered in the course only in case you encounter such proxies in your ABAP system.
External Views As of NetWeaver 7.4 a new repository object type called External View is available in the ABAP Dictionary.
What are External Views?
Figure 153: What is an External View?
External Views can be created in an ABAP System using SAP HANA as primary database and represent an SAP HANA view on the ABAP side. In other words, an External View is a proxy in the ABAP Dictionary for an SAP HANA view. The existence of such a proxy makes the view and its field list visible to the ABAP stack. This allows accessing the SAP HANA view via Open SQL and performing a syntax check.
284
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
External views have many things in common with ordinary 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.
Figure 154: Reminder: Database View in ABAP Dictionary
But while Database Views completely define their corresponding objects on the database, External Views are just proxies for the SAP HANA views they represent and, for example, don’t contain the information about the underlying tables and the join conditions.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
285
Unit 6: SAP HANA Proxy Objects
HA400
Figure 155: 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.
Create External Views in ABAP Development Tools (ADT)
Figure 156: Create External View – New ABAP Repository Object
To create an External View, you have to use the ABAP Development Tools. External Views are not supported by the ABAP Workbench.
286
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
In the ABAP project, open the context menu and choose item New → Other or New → Other ABAP Repository Object, open folder Dictionary and select Dictionary View. Specify • • • •
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.
Figure 157: Create External View – Adjust Dictionary Types
As a next step, you can adjust the mapping from the SAP HANA types used in the SAP HANA column view to the ABAP types used in the ABAP representation.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
287
Unit 6: SAP HANA Proxy Objects
HA400
Data Type Mapping between SAP HANA and ABAP Dictionary
Figure 158: Mapping of HANA Types and Dictionary Types
Using SAP HANA Views in Select Statements
Figure 159: 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.
288
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Figure 160: External Views: Things to Keep in Mind
Caution: The lifecycle management drawbacks of the bottom-up approach remain with External Views: • •
• •
2014
You have to make sure that the SAP HANA column view is available at runtime, although ABAP and SAP HANA have separate transport policies You also have to make sure that the SAP HANA view interface matches the ABAP external view structure at runtime. The latter is not adjusted automatically when the SAP HANA view interface is changed, but has to be synchronized manually. You need a SAP HANA database user to develop column views in the SAP HANA Studio You cannot use a where-used mechanism in the SAP HANA Studio to determine which ABAP External Views have been created for the view.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
289
Unit 6: SAP HANA Proxy Objects
290
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Exercise 17: Create an External View for SAP HANA View and Use it in an Open SQL SELECT Exercise Objectives After completing this exercise, you will be able to: • Create external views in the ABAP Dictionary to access SAP HANA views • Use external views in the FROM clause of Open SQL SELECTs
Business Example Template: Report HA400_EXT_VIEW_T1 Solution: Report HA400_EXT_VIEW_S1 External View HA400_OPENDAYS
Task 1: Copy and understand template Log on to the system that has SAP HANA as its primary database. Create a copy of report HA400_EXT_VIEW_T1 in your package ZHA400_## (suggested name: ZHA400_##_EVIEW_1, where ## is your group number). Activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. 1.
Log on to the system that has SAP HANA as primary database.
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task.
3.
Activate and execute the program.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
291
Unit 6: SAP HANA Proxy Objects
HA400
Task 2: Create an external view In the system that is related to the ABAP system with SAP HANA as 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 that is used in your program via native SQL. Adjust the suggested dictionary types to match the dictionary types used in your program. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database.
2.
In your package, create a new view, as External View and let it point to the SAP HANA view.
3.
Open the definition of the external view. Use the drop down lists in column DDIC Type to adjust the suggested type where necessary. Hint: Have a look at the definition of transparent tables SNWD_BPA and SNWD_SO_INV_HEAD and at the local structure type ts_customer and navigate into the relevant data elements.
4.
Save and activate the external view.
Task 3: Use the External View in an Open SQL Select Edit your program. In subroutine get_data_solution, use an Open SQL SELECT statement to fill 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.
292
1.
In subroutine get_data_solution, 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.
2.
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Solution 17: Create an External View for SAP HANA View and Use it in an Open SQL SELECT Task 1: Copy and understand template Log on to the system that has SAP HANA as its primary database. Create a copy of report HA400_EXT_VIEW_T1 in your package ZHA400_## (suggested name: ZHA400_##_EVIEW_1, where ## is your group number). Activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. 1.
Log on to the system that has SAP HANA as primary database. a)
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
3.
Complete this step as you learned to do in previous classes. Log on data are provided by your instructor.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Create an external view In the system that is related to the ABAP system with SAP HANA as 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 that is used in your program via native SQL. Adjust the suggested dictionary types to match the dictionary types used in your program. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database. a)
Complete this step as before.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
293
Unit 6: SAP HANA Proxy Objects
2.
3.
HA400
In your package, create a new view, as External View and let it point to the SAP HANA view. a)
Right Click on the project 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 and enter the name (and path) of the SAP HANA View. Then press Enter.
d)
Confirm the transport request and press Finish.
Open the definition of the external view. Use the drop down lists in column DDIC Type to adjust the suggested type where necessary. Hint: Have a look at the definition of transparent tables SNWD_BPA and SNWD_SO_INV_HEAD and at the local structure type ts_customer and navigate into the relevant data elements.
4.
a)
Double click the newly created external view in the Project Explorer.
b)
There is no need to adjust ABAP Dictionary types in this case.
Save and activate the external view. a)
Press button Activate.
Task 3: Use the External View in an Open SQL Select Edit your program. In subroutine get_data_solution, use an Open SQL SELECT statement to fill 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.
In subroutine get_data_solution, 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)
2.
See source code extract from model solution.
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.
Continued on next page
294
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Result
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( ). * 2. Create statement object CREATE OBJECT lo_sql EXPORTING con_ref = lo_con. * 3. assemble SQL statement lv_sql = |SELECT "BP_ID", "COMPANY_NAME", | && | && |
AVG("DAYS_OPEN") AS AVG_DAYS_OPEN | FROM "_SYS_BIC"."ha400.secdb.demo/AT_OPEN_INVOICES"
|
&& | GROUP BY "BP_ID", "COMPANY_NAME" | && | ORDER BY "BP_ID" |.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
295
Unit 6: SAP HANA Proxy Objects
HA400
* 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 bp_id company_name AVG( days_open ) AS avg_days_open FROM ha400_opendays INTO TABLE ct_customers GROUP BY bp_id company_name ORDER BY bp_id. ENDFORM.
296
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Accessing SAP HANA Views via ABAP Dictionary External Views
Lesson Summary You should now be able to: • Describe the bottom-up approaches to the code-to-data paradigm possible with ABAP 7.4 SP02 • Create external views in the ABAP Dictionary • Explain the mapping of SAP HANA data types and ABAP Dictionary types • Adjust data type mappings • Select from an external view with Open SQL
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
297
Unit 6: SAP HANA Proxy Objects
HA400
Lesson: Transport of SAP HANA Objects Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • •
Explain the use of Delivery Units Create delivery units and assign packages Explain the usage of HANA Transport Containers Create HANA Transport Containers and assign delivery units
Business Example You implemented performance improvements of an ABAP application by making use of SAP HANA column views and calling them in ABAP code. You now want to make sure that the ABAP code and the SAP HANA content it depends on can be transported consistently from the development to the test and production systems.
HANA Transport Containers
Figure 161: SAP HANA Transport Containers
Consuming SAP HANA Views, or database procedures, in ABAP code creates dependencies between the ABAP code and the SAP HANA artefacts. This holds true when consuming the artefacts using native SQL, and is made more
298
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Transport of SAP HANA Objects
evident when working with external views. A consequence is that transporting the dependent ABAP code such that it can be imported into target systems successfully requires that the referenced SAP HANA content be transported before or with the ABAP code. One way to achieve this is to transport the SAP HANA Delivery Units using the Enhanced Change and Tranpsort System (CTS+). An easier way may be to make use of SAP HANA Transport Containers. To create an SAP HANA Transport Container, use the ABAP Development Tools for SAP NetWeaver: • • •
In the context menu of the ABAP Project or of an ABAP package, select menu item 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). In the New HANA Transport Container dialog, specify the ABAP package and the name of the 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.
Figure 162: HANA Transport Container – The Principle
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
299
Unit 6: SAP HANA Proxy Objects
HA400
Using HANA Transport Containers properly
Figure 163: How does a HANA Transport Container work?
Figure 164: Maintaining HANA Transport Container
Figure 165: HANA Transport Container – Snapshots
300
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Transport of SAP HANA Objects
Figure 166: HANA Transport Container – Unpacking in Target System
Figure 167: HANA Transport Container: Things to Keep in Mind
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
301
Unit 6: SAP HANA Proxy Objects
302
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Transport of SAP HANA Objects
Exercise 18: Create HANA Transport Container for a Delivery Unit Exercise Objectives After completing this exercise, you will be able to: • Create a HANA Transport Container for a SAP HANA Delivery Unit • Refresh the Snapshot of SAP HANA objects
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.
Task 1: Create a HANA Transport Container In the ABAP system that has SAP HANA as the primary database, create a HANA Transport Container for your Delivery Unit ZHA400_##, where ## is your group number. Assign the transport container to your repository package and transport request. Finally, activate the new repository object. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database.
2.
In your package, create a new repository object of type HANA Transport Container and let it refer to your delivery unit.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
303
Unit 6: SAP HANA Proxy Objects
HA400
3.
Where does the name of the transport container come from?
4.
In the project explorer, expand your package so that you can see the icon of your HANA transport container. Then press the Activate button in the toolbar. What happens to the icon of the object?
Task 2: Take a Snapshot of SAP HANA Objects Refresh the snapshot of SAP HANA objects and, if necessary, activate the transport container again.
304
1.
Refresh the snapshot of SAP HANA objects inside your transport container.
2.
What happens to the icon of the transport container?
3.
Activate the transport container again.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Transport of SAP HANA Objects
Solution 18: Create HANA Transport Container for a Delivery Unit Task 1: Create a HANA Transport Container In the ABAP system that has SAP HANA as the primary database, create a HANA Transport Container for your Delivery Unit ZHA400_##, where ## is your group number. Assign the transport container to your repository package and transport request. Finally, activate the new repository object. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database. a)
2.
Complete this step as before.
In your package, create a new repository object of type HANA Transport Container and let it refer to your delivery unit. a)
Right Click on the project and choose New → ABAP Repository Object. Expand node Others and double click HANA Transport Container.
b)
Enter the name of your package and the name of your delivery unit (see exercise 2) and press Next >. Hint: To enter the full name of your delivery unit, you can enter its name and then use Content Assist to let the ABAP Development Tools add the vendor information correctly.
c) 3.
Confirm the transport request and press Finish.
Where does the name of the transport container come from? Answer: The name is taken from the name of the delivery unit.
4.
In the project explorer, expand your package so that you can see the icon of your HANA transport container. Then press the Activate button in the toolbar. What happens to the icon of the object? Answer: The icon changes. While an inactive version of the object exists, the icon contains a small lock symbol. This lock disappears during activation.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
305
Unit 6: SAP HANA Proxy Objects
HA400
Task 2: Take a Snapshot of SAP HANA Objects Refresh the snapshot of SAP HANA objects and, if necessary, activate the transport container again. 1.
Refresh the snapshot of SAP HANA objects inside your transport container. a)
Open the HANA transport container. Click on link Take Snapshot and Save.
2.
What happens to the icon of the transport container? Answer: Refreshing the snapshot saves a new inactive version of the object.
3.
Activate the transport container again. a)
306
Perform this step as before.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Transport of SAP HANA Objects
Lesson Summary You should now be able to: • Explain the use of Delivery Units • Create delivery units and assign packages • Explain the usage of HANA Transport Containers • Create HANA Transport Containers and assign delivery units
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
307
Unit 6: SAP HANA Proxy Objects
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Use database procedure proxies in ABAP.
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system use SAP HANA as primary database. You realize that the performance improvement you aim for cannot be reached using native SQL or information models alone.
Database Procedure Proxies
Figure 168: Using Stored Procedures in ABAP 7.40 SP02 – SP04
ABAP-managed database procedures are only supported starting with ABAP 7.4 SP05. But ABAP release 7.4 supports another - now out-dated - way to simplify the bottom-up approach of consuming SAP HANA database procedures with the introduction of a new ABAP Dictionary object type called Database Procedure Proxy.
308
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
How do Database Procedure Proxies Work?
Figure 169: Database Procedure Proxy in ABAP Dictionary
Database Procedure Proxies are a new type of ABAP Dictionary object introduced with ABAP 7.40. It represents, inside the ABAP system, a Database Procedure that exists outside and independent of an ABAP system . It has import and export parameters that are mapped to the parameters of the procedure. A Database Procedure Proxy allows calling the database procedure it represents without using native SQL. A new ABAP statement CALL DATABASE PROCEDURE is introduced for this purpose.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
309
Unit 6: SAP HANA Proxy Objects
HA400
Database Procedure Proxies in ABAP Development Tools (ADT)
Figure 170: Create Database Procedure Proxy – Using ABAP Development Tools
To create a Database Procedure Proxy, you have to use the ABAP Development Tools. Database Procedure Proxies are not supported by the ABAP Workbench. In the ABAP project, open the context menu and choose item New → Other or New → Other ABAP Repository Object, open folder Dictionary and select Database Procedure Proxy. Specify • • •
•
310
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.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
Figure 171: Create Database Procedure Proxy – Adjust Types
As a next step, you can 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 172: Mapping of HANA Types and ABAP Built-in Types
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
311
Unit 6: SAP HANA Proxy Objects
HA400
Calling Database Procedure Proxies in ABAP
Figure 173: 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 important and exporting parameters, use ABAP variables typed with the types defined in the ABAP OO interface generated for the procedure proxy.
Figure 174: Procedure Proxies: Things to Keep in Mind
312
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
Caution: The lifecycle management drawbacks of the bottom-up approach remain with database procedure proxies: • •
• •
You have to make sure that a stored procedure is available at runtime, although ABAP and SAP HANA have separate transport policies You also have to make sure that the stored procedure interface matches the ABAP database procedure proxy interface at runtime. The latter is not adjusted automatically when the stored procedure interface is changed, but has to be synchronized manually. You need a SAP HANA database user to develop stored procedures in the SAP HANA Studio There is no extensibility mechanism to consider custom fields and no encapsulation in the sense that many proxies can access the same database procedure at the same time.
Summary: Code-to-Data Techniques
Figure 175: Summary: Which Code-to-Data Technique to Use?
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
313
Unit 6: SAP HANA Proxy Objects
314
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
HA400
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
Exercise 19: Call a Database Procedure Proxy for a SAP HANA Procedure in an ABAP Program Exercise Objectives After completing this exercise, you will be able to: • Create database procedure proxies to access SAP HANA procedures • Call database procedure proxies in ABAP
Business Example Template: Report HA400_PROC_PROXY_T1 Solution: Report HA400_PROC_PROXY_S1 Database Procedure Proxy HA400_EARLY_AND_LATE
Task 1: Copy and understand template Log on to the system that has SAP HANA as primary database. Create a copy of report HA400_PROC_PROXY_T1 in your package ZHA400_## (suggested name: ZHA400_##_PROXY_1, where ## is your group number). Activate and execute the program. Hint: Copying a complete report (including its screens, text pool etc.) is not yet supported in eclipse. Therefore you need to do this particular step in ABAP workbench (SE80). 1.
Log on to the system that has SAP HANA as primary database.
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task.
3.
Activate and execute the program.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
315
Unit 6: SAP HANA Proxy Objects
HA400
Task 2: Display a database procedure proxy In the ABAP system that has SAP HANA as its primary database, open database procedure proxy HA400_EARLY_AND_LATE 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database.
2.
Open Database Procedure Proxy HA400_EARLY_AND_LATE.
3.
Inspect the definition of the procedure proxy: the database procedure proxy represents SAP HANA stored procedure The stored procedure determines the customers that on average pay earliest or latest. It has scalar input parameter(s) to control how many customers are returned, and table-like output parameter(s) representing the early and late payers. Fill in the blanks to complete the sentence.
4.
In what way has the type mapping of the output tables' components has been adjusted?
Task 3: Call the database procedure proxy in an ABAP program Edit your program. Implement subroutine get_data_solution with a call of the database procedure proxy.
316
1.
In subroutine get_data_solution, implement a call of the database procedure proxy HA400_EARLY_AND_LATE.
2.
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
Solution 19: Call a Database Procedure Proxy for a SAP HANA Procedure in an ABAP Program Task 1: Copy and understand template Log on to the system that has SAP HANA as primary database. Create a copy of report HA400_PROC_PROXY_T1 in your package ZHA400_## (suggested name: ZHA400_##_PROXY_1, where ## is your group number). Activate and execute the program. Hint: Copying a complete report (including its screens, text pool etc.) is not yet supported in eclipse. Therefore you need to do this particular step in ABAP workbench (SE80). 1.
Log on to the system that has SAP HANA as primary database. a)
2.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
3.
Complete this step as you learned to do in previous classes. Log on data are provided by your instructor.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Display a database procedure proxy In the ABAP system that has SAP HANA as its primary database, open database procedure proxy HA400_EARLY_AND_LATE 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database. a)
2.
Complete this step as before.
Open Database Procedure Proxy HA400_EARLY_AND_LATE. a)
Press button Open ABAP Development Object (or CTRL+SHIFT+A) and start typing the name of the proxy.
b)
When the proxy is listed in the matching items, select it and press OK.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
317
Unit 6: SAP HANA Proxy Objects
3.
HA400
Inspect the definition of the procedure proxy: the database procedure proxy represents SAP HANA stored procedure h400.primdb.demo.DP_EARLY_AND_LATE_PAYERS. The stored procedure determines the customers that on average pay earliest or latest. It has1 scalar input parameter(s) IV_NUMBER to control how many customers are returned, and two table-like output parameter(s) representing the early and late payers. Answer: h400.primdb.demo.DP_EARLY_AND_LATE_PAYERS, 1, IV_NUMBER, two
4.
In what way has the type mapping of the output tables' components has been adjusted? a)
The type mapping of the output tables' components has been adjusted as follows: Parameter (Component) Name
DDIC Type Override
BP_ID
SNWD_PARTNER_ID
COMPANY_NAME
SNWD_COMPANY_NAME
DAYS_OPEN
HA400_AVGND
Task 3: Call the database procedure proxy in an ABAP program Edit your program. Implement subroutine get_data_solution with a call of the database procedure proxy. 1.
In subroutine get_data_solution, implement a call of the database procedure proxy HA400_EARLY_AND_LATE. a)
2.
See source code extract from model solution.
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.
Result
Source code extract from model solution (Program HA400_PROC_PROXY_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------*
Continued on next page
318
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
FORM get_data_template USING
pv_number TYPE i
CHANGING ct_cust_early TYPE ty_t_customers ct_cust_late
TYPE ty_t_customers.
* Declarations **************** * type for result overview TYPES: BEGIN OF lty_s_overview, param TYPE string, value TYPE string, END OF lty_s_overview. * Data objects for result overview DATA: lt_overview TYPE TABLE OF lty_s_overview, ls_overview TYPE
lty_s_overview.
* Processing ******************************** CLEAR: ct_cust_early, ct_cust_late. TRY. * See report HA400_EXPR_ADBC_T2 or HA400_PROCEDURE_S1 for equivalent code that makes * little or no use of expressions, i.e. uses classical ABAP code style. * Create statement object (primary DB connection) DATA(lo_sql) = NEW cl_sql_statement(
).
* Call Procedure with Overview (fill lt_overview) DATA(lo_result) = lo_sql->execute_query( |CALL _SYS_BIC."ha400.primdb.demo/DP_EARLY_AND_LATE_PAYERS"( | && |{ pv_number }, null , null ) WITH OVERVIEW | ). lo_result->set_param_table( REF #( lt_overview ) ). lo_result->next_package( ). lo_result->close( ). * Retrieve first result (Parameter et_early) lo_result = lo_sql->execute_query( |SELECT * FROM { lt_overview[ param = 'ET_EARLY' ]-value } | ). lo_result->set_param_table( REF #( ct_cust_early ) ). lo_result->next_package( ).
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
319
Unit 6: SAP HANA Proxy Objects
HA400
lo_result->close( ). * Retrieve second result (Parameter et_late) lo_result = lo_sql->execute_query( |SELECT * FROM { lt_overview[ param = 'ET_LATE' ]-value } | ). lo_result->set_param_table( REF #( ct_cust_late ) ). lo_result->next_package( ). lo_result->close( ). * Exception handling CATCH cx_sql_exception INTO DATA(lx_sql_exc). "Excpt. Class for SQL Error MESSAGE lx_sql_exc TYPE 'E'. ENDTRY. 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.
DATA: lt_cust_early TYPE TABLE OF if_ha400_early_and_late=>et_early, lt_cust_late
TYPE TABLE OF if_ha400_early_and_late=>et_late.
CALL DATABASE PROCEDURE ha400_early_and_late EXPORTING iv_number = pv_number IMPORTING et_early = lt_cust_early et_late
= lt_cust_late.
ct_cust_early = lt_cust_early. ct_cust_late ENDFORM.
320
= lt_cust_late. "
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Calling SAP HANA Procedures via ABAP Database Procedure Proxies
Lesson Summary You should now be able to: • Use database procedure proxies in ABAP.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
321
Unit Summary
HA400
Unit Summary You should now be able to: • Describe the bottom-up approaches to the code-to-data paradigm possible with ABAP 7.4 SP02 • Create external views in the ABAP Dictionary • Explain the mapping of SAP HANA data types and ABAP Dictionary types • Adjust data type mappings • Select from an external view with Open SQL • Explain the use of Delivery Units • Create delivery units and assign packages • Explain the usage of HANA Transport Containers • Create HANA Transport Containers and assign delivery units • Use database procedure proxies in ABAP.
322
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 7 Advanced Topics Unit Overview This unit is designed to teach you the following topics: • • •
Using SAP HANA fuzzy search in ABAP Enable type-ahead search for input fields SAP List Viewer (ALV) with integrated access to SAP HANA
Unit Objectives After completing this unit, you will be able to: • • • • • • • • •
Describe when fuzzy search can be used Configure a table column for fuzzy search Write a SELECT statement that uses fuzzy search Enable an input field on an SAP GUI screen for type-ahead with fuzzy search Understand the benefits of SAP List Viewer (ALV) optimized for HANA Describe the differences between ALV for HANA and classical ALV Display data in ALV for HANA Use select options in the data retrieval of ALV for HANA Supply values for input parameters of external view
Unit Contents Lesson: Using SAP HANA Full Text Search ................................324 Exercise 20: Implement a Fuzzy Search ................................337 Exercise 21: Implement Type-Ahead with Fuzzy Search .............345 Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA 351 Exercise 22: Use ALV Optimized for SAP HANA ......................363
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
323
Unit 7: Advanced Topics
HA400
Lesson: Using SAP HANA Full Text Search Lesson Overview This lesson teaches you 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.
Lesson Objectives After completing this lesson, you will be able to: • • • •
Describe when fuzzy search can be used Configure a table column for fuzzy search Write a SELECT statement that uses fuzzy search Enable an input field on an SAP GUI screen for type-ahead with fuzzy search
Business Example Your company ITeLO wants you to improve the performance of some ABAP application considerably, by making use of SAP HANA. The ABAP system has been migrated to use SAP HANA as its primary database already. In particular, your company wants you to improve the usability of searches in string-like database columns.
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.
324
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Figure 176: Fuzzy Search – Sometimes Equals Is Not Enough
The above search with equals returns none of the listed table entries. 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 – is it SAP Deutschland or SAP Germany?
Figure 177: Fuzzy Search – Sometimes LIKE Is Not Enough
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
325
Unit 7: Advanced Topics
HA400
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 search term enclosed in wildcards exactly. 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 1/3. 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 mis-spellings 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 (language-specific) search.
Figure 178: 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.
326
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Figure 179: Prerequisites For Fuzzy Search
To be able to use to Fuzzy Search with good performance (and to be able to use all other SAP HANA Text Search features), full text indexes are required for the relevant table and columns. In order 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.
Creating a Full-Text Index for Fuzzy Search
Figure 180: Creating the Index
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
327
Unit 7: Advanced Topics
HA400
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 creating the index. Activating a full text index with synchronous update mode for a table containing many entries already may thus take a while.
Figure 181: Creating the index in an ABAP 7.4 system
328
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
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. Check 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 the index 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 check 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.
Using the Fuzzy Search You implement a fuzzy search using the CONTAINS() function in the WHERE clause of your SELECT statement.
Figure 182: The CONTAINS() Function
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
329
Unit 7: Advanced Topics
HA400
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. Note also that 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) are only available in Native SQL. A further function that can be useful in the fuzzy search is SCORE().
Figure 183: The SCORE() Function
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 you can use it in the background in the ORDER BY clause to ensure that the best hits appear at the top of the list.
330
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Linguistic Search
Figure 184: Linguistic Search
While the fuzzy search is very useful for entities such as names, it is sometimes more useful to perform a linguistic search, e.g. 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.
Creating a 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 using native SQL. When indexing a record for linguistic search, you must specify the language of the record (unless everything should be interpreted as being 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 2-character ISO code, you can use the function module CONVERT_SAP_LANG_TO_ISO_LANG
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
331
Unit 7: Advanced Topics
HA400
Figure 185: 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 – 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. Note that fast preprocessing is switched on by default when creating a full text index using the SAP HANA Studio.
Figure 186: Text Analysis Options
332
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Using the Linguistic Search
Figure 187: Using the Linguistic Search
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.
Using Full Text Search And Type-Ahead Input Fields
Figure 188: Search Helps with Type-Ahead and Fuzzy Search
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
333
Unit 7: Advanced Topics
HA400
Starting with ABAP 7.4 SP03, ABAP Dictionary search helps can be enhanced to support so-called type-ahead search. If this is enabled for an input field on a screen, the system automatically proposes matching values when an end user enters a few characters. You can identify input fields with type-ahead easily: the system displays a magnifying glass in them (the usual value help button may shadow this if the cursor is placed in the field already). Type-ahead can be used on all database systems supported by ABAP. However, it provides most value if fuzzy search is used in addition. Fuzzy search is only supported on SAP HANA as of this writing. Prerequisites for enabling type-ahead are 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 may override the search help attached to the field. To enable type-ahead for an input field on a screen, perform the following steps:
Figure 189: Enabling Type-Ahead With Fuzzy Search for SAP GUI
Identify the ABAP Dictionary Search Help attached to the field, e.g. using Field Help, navigating to the Technical Information and on to the Dictionary. In case you find a collective search help attached, navigate to the first suitable elementary search help contained in the collective search help.
334
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Adjust the elementary search help: •
•
Switch on Proposal Search for Input Fields to enable type-ahead. 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 Full Text Fuzzy Search to use Fuzzy Search to determine value proposals when running on SAP HANA. Hint: Additional prerequisite: The Search Help must be based on a column store table or on a CDS view.
•
Adjust the Accuracy Value for Error-Tolerant Full Text Search if necessary.
In ABAP systems of release 7.4 SP05, you also have to enable type-ahead explicitly in the screen, by using a PBO module and a call of method cl_dsh_dynpro_properties=>enable_type_ahead(...) therein, or by adding an attribute typeahead with value “X” directly to the custom properties of the input field. In ABAP 7.4 SP06 and higher, this is required in exceptional cases only. Starting with ABAP 7.4 SP06, all input fields that are attached to a type-ahead enabled search help or use domain-fixed values are automatically enabled for the type-ahead search.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
335
Unit 7: Advanced Topics
336
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Exercise 20: Implement a Fuzzy Search Exercise Objectives After completing this exercise, you will be able to: • Implement a fuzzy search in ABAP using Native SQL • Requirements for fuzzy search in SAP HANA
Business Example Template: Report HA400_FUZZY_T1 Solution: Report HA400_FUZZY_S1
Task 1: Copy and understand the template 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 the report. Place it in your package ZHA400_## and assign it to your workbench task.
2.
Activate and execute the program using the default values. How many data records are displayed?
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
337
Unit 7: Advanced Topics
HA400
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?
4.
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 lower case 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 answer(s).
□ □ □ □
A B C D
Extension Index Full-Text Index Unique Index Hashed Index
2.
Examine, in the ABAP Dictionary, the index 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 and indexes the column SCUSTOM. A full text index is switched . The update mode . for the index is set to Fill in the blanks to complete the sentence.
Continued on next page
338
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Task 3: Use a fuzzy search to implement a more 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.
2014
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 and test the program. Enter various search terms and compare the result of the two subroutines.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
339
Unit 7: Advanced Topics
HA400
Solution 20: Implement a Fuzzy Search Task 1: Copy and understand the template 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 the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Activate and execute the program using the default values. How many data records are displayed? a)
3.
Complete this step as you learned to do in previous classes.
Complete this step as you learned to do in previous classes. No data is displayed.
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? Answer: The first letter is in upper-case and there are two wildcard characters.
4.
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 lower case letters? Answer: For the wildcard, you can use LIKE '%Maier%'. However, this would not match a search pattern containing all upper case or all lower case 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? Answer: B The table requires a full-text index to allow for fuzzy search.
Continued on next page
340
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
2.
3.
Examine, in the ABAP Dictionary, the index 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)
Open the definition of the table in the ABAP Dictionary.
b)
Open the Indexes ....
c)
Look at the list of indexes. Choose the index with a name in the DB index name column, respectively with value “I” in the Inclusion/Exclusion column.
d)
The Display Index screen shows which columns and database systems is created on.
e)
Open menu item Goto → Full Text Index
The index is called FTN and indexes the column SCUSTOM-NAME. A full text index is switched on. The update mode for the index is set to asynchronous. Answer: FTN, NAME, on, asynchronous
Task 3: Use a fuzzy search to implement a more 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. a)
2.
See source code extract from the model solution.
Activate and test the program. Enter various search terms and compare the result of the two subroutines. a)
perform this step as before.
Result
Source code extract from model solution (Program HA400_FUZZY_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------* FORM get_data_template USING pv_name TYPE scustom-name
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
341
Unit 7: Advanced Topics
HA400
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,
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
Continued on next page
342
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
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.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
343
Unit 7: Advanced Topics
344
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Exercise 21: Implement Type-Ahead with Fuzzy Search Exercise Objectives After completing this exercise, you will be able to: • Use fuzzy search and type-ahead to provide a more user-friendly value help.
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. YTemplate Objects: Search Help: SCUSTOM Search Help: SCUSTOM_NAME REPORT: HA400_FUZZY_T2 Solution Objects: Search Help: HA400_SCUSTOM Search Help: HA400_SCUSTOM_NAME Report: HA400_FUZZY_S2
Task 1: Copy and understand the template objects Create a copy of template report HA400_FUZZY_T2 (suggested name: ZHA400_##_FUZZY_2) and of the two search helps SCUSTOM (suggested name: ZHA400_##_SCUSTOM) and SCUSTOM_NAME (suggested name: ZHA400_##_SCUSTOM_NAME). 1.
Create a copy of report HA400_FUZZY_T2. Place it in your package ZHA400_## and assign it to your workbench task.
2.
Activate your copy, execute it and understand its selection screen.
3.
The report selection screen comprises a single of type . Using forward navigation in the source code, you can see that this type has an explicit search help attached. The attached search help is . To enable type-ahead for the input field, the attached search help (or if it is a collective search help an elementary search help it contains) has to be adjusted. Fill in the blanks to complete the sentence.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
345
Unit 7: Advanced Topics
HA400
4.
Create a copy of search help SCUSTOM. Place it in your package ZHA400_## and assign it to your workbench task.
5.
Create a copy of search help SCUSTOM_NAME. Place it in your package ZHA400_## and assign it to your workbench task.
6.
Understand the two search helps:.your copy of SCUSTOM is a search help. It includes two search helps, one of which is
.
Fill in the blanks to complete the sentence.
Task 2: Adjust the search helps to make them support type-ahead and fuzzy search. Adjust the definition of your search help copies such that both support type-ahead and fuzzy search. 1.
Adjust the definition of your search help ZHA400_##_SCUSTOM_NAME to make it support type-ahead and fuzzy search..
2.
Adjust the definition of your search help ZHA400_##_SCUSTOM and replace included search help SCUSTOM_NAME with your copy.
Task 3: Adjust your report to make use of your search helps Your report still uses the original search help, because you cannot change the binding from table SCUSTOM to the original search help. As a work around, use appropriate options of the PARAMETERS statement to explicitly refer to your collective search help.
346
1.
Open your copy of the template report and extend the PARAMETERS statement with the option to use your collective search help
2.
Activate and test the program. Enter various search terms and see how the system automatically suggests values.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
Solution 21: Implement Type-Ahead with Fuzzy Search Task 1: Copy and understand the template objects Create a copy of template report HA400_FUZZY_T2 (suggested name: ZHA400_##_FUZZY_2) and of the two search helps SCUSTOM (suggested name: ZHA400_##_SCUSTOM) and SCUSTOM_NAME (suggested name: ZHA400_##_SCUSTOM_NAME). 1.
Create a copy of report HA400_FUZZY_T2. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Activate your copy, execute it and understand its selection screen. a)
3.
Complete this step as you learned to do in previous classes.
Activate the report as you learned to do in previous classes.
The report selection screen comprises a single PARAMETER of type SCUSTOM-ID. Using forward navigation in the source code, you can see that this type has an explicit search help attached. The attached search help is SCUSTOM. To enable type-ahead for the input field, the attached search help (or if it is a collective search help an elementary search help it contains) has to be adjusted. Answer: PARAMETER, SCUSTOM-ID, SCUSTOM
4.
5.
6.
Create a copy of search help SCUSTOM. Place it in your package ZHA400_## and assign it to your workbench task. a)
To copy the search help, open the search help (e.g. using the Open ABAP Development Object button in the ABAP Development Tools). Press the Other Object ... button in the toolbar, then the Copy button.
b)
Place the search help in your package ZHA400_## and assign it to your workbench task.
Create a copy of search help SCUSTOM_NAME. Place it in your package ZHA400_## and assign it to your workbench task. a)
Copy the search help as in the previous step.
b)
Place the search help in your package ZHA400_## and assign it to your workbench task.
Understand the two search helps:.your copy of SCUSTOM is a collective search help. It includes two elementary search helps, one of which is SCUSTOM_NAME. Answer: collective, elementary, SCUSTOM_NAME Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
347
Unit 7: Advanced Topics
HA400
Task 2: Adjust the search helps to make them support type-ahead and fuzzy search. Adjust the definition of your search help copies such that both support type-ahead and fuzzy search. 1.
2.
Adjust the definition of your search help ZHA400_##_SCUSTOM_NAME to make it support type-ahead and fuzzy search.. a)
Open the search help and switch to change mode.
b)
In frame Enhanced Options, mark check boxes Proposal Search for Input Fields and Full Text Fuzzy Search
c)
Activate the search help.
Adjust the definition of your search help ZHA400_##_SCUSTOM and replace included search help SCUSTOM_NAME with your copy. a)
Open the search help and switch to change mode.
b)
Open tab Included search helps.
c)
Replace entry SCUSTOM_NAME with the ZHA400_##_SCUSTOM_NAME.
d)
Select the entry and press Param. assignment. You can accept the proposal.
e)
Activate the search help.
Task 3: Adjust your report to make use of your search helps Your report still uses the original search help, because you cannot change the binding from table SCUSTOM to the original search help. As a work around, use appropriate options of the PARAMETERS statement to explicitly refer to your collective search help. 1.
Open your copy of the template report and extend the PARAMETERS statement with the option to use your collective search help a)
See source code extract from the model solution.
Continued on next page
348
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Using SAP HANA Full Text Search
2.
Activate and test the program. Enter various search terms and see how the system automatically suggests values. a)
Perform this step as before.
Result
Source code extract from model solution (Report HA400_FUZZY_S2) REPORT ha400_fuzzy_s2 MESSAGE-ID ha400. * Structure for Result TYPES: BEGIN OF ty_s_booking_count, carrid
TYPE scarr-carrid,
name
TYPE scarr-carrname,
bookings TYPE i, END OF ty_s_booking_count. TYPES: ty_t_bookings TYPE STANDARD TABLE OF ty_s_booking_count WITH NON-UNIQUE KEY carrid. * Data Objects * Table for Result DATA: gt_bookings
TYPE ty_t_bookings.
* selection screen SELECTION-SCREEN BEGIN OF BLOCK cus WITH FRAME TITLE text-cus. PARAMETERS pa_cust TYPE scustom-id MATCHCODE OBJECT HA400_SCUSTOM. SELECTION-SCREEN END OF BLOCK cus. ENDFORM.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
349
Unit 7: Advanced Topics
HA400
Lesson Summary You should now be able to: • Describe when fuzzy search can be used • Configure a table column for fuzzy search • Write a SELECT statement that uses fuzzy search • Enable an input field on an SAP GUI screen for type-ahead with fuzzy search
350
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • • • • •
Understand the benefits of SAP List Viewer (ALV) optimized for HANA Describe the differences between ALV for HANA and classical ALV Display data in ALV for HANA Use select options in the data retrieval of ALV for HANA Supply values for input parameters of 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.
SAP ABAP List Viewer 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. This variation of the ALV is optimized for use with SAP HANA.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
351
Unit 7: Advanced Topics
HA400
Basic Principles and Advantages
Figure 190: What is SALV IDA – SAP ABAP List Viewer – Integrated Data Access
How it Works
Figure 191: ALV Optimized for HANA
The SAP List Viewer with Integrated Data Access 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. It is based on the following principles:
352
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Try to only select the data in the database that’s really 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. 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 shown here illustrates how these principles are quite different from how the 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 the data 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, but more complex conditions can be expressed as well. As a result, the data is retrieved much faster on SAP HANA, and you also need far less memory on the ABAP stack.
Figure 192: Classical ALV – How Does it Work
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
353
Unit 7: Advanced Topics
HA400
The figure shows the approach to displaying data using the classical ALV. The steps shown provide an example of what the ABAP application would typically do: • • • • •
The application performs authorization checks and extracts relevant data from the database into an internal table Business data such as calculated fields can then be added to the internal table contents UI information (icons, links, etc.) may also be added The internal table is passed to the ALV services which then manipulate the data according to user requirements Finally, the required data is displayed on the screen
Difference between ALV for SAP HANA and Classical ALV Technical Difference
Figure 193: 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 classic 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.
354
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
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 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.
Figure 194: The New Approach – ALV Optimized for HANA
The ALV optimized for HANA is significantly different to the classic ALV. Authority checks, table functions, and other processes which 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 Optimized for HANA.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
355
Unit 7: Advanced Topics
HA400
End User Perspective
Figure 195: ALV for HANA – End User Perspective
The ALV optimized for HANA will look and feel familiar to end-users who have worked with the classic ALV, but there are some small differences in functionality and behaviour.
356
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Figure 196: Availability of Features in ALV for HANA I
Figure 197: Availability of Features in ALV for HANA II
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
357
Unit 7: Advanced Topics
HA400
Implementing ALV for SAP HANA Using Select Options
Figure 198: Coding Example – Instantiation of ALV Optimized for HANA
The example shows how you can display the content of a table from SAP HANA using the ALV with IDA in a report. As with the classic ALV, a container instance is created first, but then the factory method CREATE of CL_SALV_GUI_TABLE_IDA is called to generate the instance of the new ALV optimized for HANA. Notice 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 parameter IV_TABLE_NAME. 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 copied from the 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.
358
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Figure 199: Restricting Data Display
Referencing Data Elements When an External View is derived from a SAP HANA view, the columns in the Dictionary view are not described using data elements, instead they are directly typed. Method SET_DATA_ELEMENT of CL_SALV_GUI_FIELD_CATALOG_IDA can be called to reference data elements to be used for each column – the data element will be then be used to determine the column heading in the ALV.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
359
Unit 7: Advanced Topics
HA400
Figure 200: Referencing Data Elements for ALV Columns
External Views with Input Parameters The ALV optimized for HANA can work with external views which have been published to the ABAP Dictionary. The HANA view which the external view is based on may have input parameters which are used as filters, in calculations, or in scripted logic. 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. The query engine transforms these into suitable HANA placeholders and uses them during selection.
360
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Figure 201: ALV Using External View with Parameters
Using Fuzzy Search You may want to provide a selection screen in the ABAP application which 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.
Figure 202: Fuzzy Search Functionality with ALV for HANA
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
361
Unit 7: Advanced Topics
HA400
This type of search was not possible with the classic ALV.
Things to keep in Mind
Figure 203: ALV for HANA: Things to Keep in Mind
362
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Exercise 22: Use ALV Optimized for SAP HANA Exercise Objectives After completing this exercise, you will be able to: • Use the ALV Optimized for SAP HANA to display data.
Business Example Your company has a report listing, for a range of customers to be specified on the selection screen, the open invoices with the number of days each invoice is open. End users typically use the report to see the average age of the open invoices grouped by customer, using the SAP List Viewer's aggregation and drill-down features. The report is partially optimized because it makes use of an External View, and you want to improve its user experience further by making use of the SAP List Viewer with Integrated Data Access. Template: Report HA400_HANA_ALV_T1 Solution: Report HA400_HANA_ALV_S1
Task 1: Copy and understand template Create a copy of report HA400_HANA_ALV_T1 via transaction SE80 in your package ZHA400_## (suggested name: ZHA400_##_ALV1, where ## is your group number). Analyze the program to get an idea of the functionality. Activate and execute the program. 1.
Create a copy of the report, making sure to copy all sub-objects too (including the screen and GUI Status). Place it in your package ZHA400_## and assign it to your workbench task. Hint: To copy the report including screens, GUI status etc. using the ABAP Development Tools, use context menu item Duplicate.
2.
Analyze the source code of the program. Which are the two main parts of the data processing? In which processing blocks are they encapsulated?
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
363
Unit 7: Advanced Topics
3.
HA400
Depending on the value of selection screen parameter , either subroutine or subroutine are called. The first subroutine first retrieves data using external view and buffers the result in internal table . The classic ALV grid is then used to display the table, sorted by and . The second subroutine is not fully implemented yet. Fill in the blanks to complete the sentence.
4.
Analyze screen 100 of the program, and pay attention to the name of the Custom Control Area on the screen which has been created for the ALV grid. What is the name of the Custom Control Area?
5.
Activate and execute the program.
Task 2: Use the ALV Optimized for HANA to display the data Edit your program. Complete the implementation of subroutine DISPLAY_SOLUTION so that the data is displayed in the new ALV optimized for HANA. 1.
Declare a reference variable of type REF TO IF_SALV_GUI_TABLE_IDA (or use a corresponding inline data declaration) and use it to receive the object from the factory method CREATE of class CL_SALV_GUI_TABLE_IDA. This method creates and returns an instance of the HANA-optimized ALV. Supply the container reference GO_CONTAINER for the parameter IO_GUI_CONTAINER, and the name of the external view which will supply the data, HA400_OPENDAYS, for the parameter IV_TABLE_NAME.
2.
To ensure that only the data chosen by the user on the selection screen is displayed, the details about what data should be retrieved must be supplied to the ALV object. Declare a reference variable of type ref to CL_SALV_RANGE_TAB_COLLECTOR (or use a corresponding inline data declaration), and then create an instance of this class.
Continued on next page
364
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
3.
Call the method ADD_RANGES_FOR_NAME for the above object, once for each select-option on the selection screen. Pass the select-option internal table for the parameter IT_RANGES, and the field name from external view HA400_OPENDAYS for the parameter IV_NAME.
4.
Call method GET_COLLECTED_RANGES which exports an internal table of type if_salv_service_types=>yt_named_ranges with the select-options combined into one range.
5.
Call method SET_SELECT_OPTIONS for the ALV object retrieved in step 1, passing the internal table from the last step to parameter IT_RANGES.
6.
Use method FIELD_CATALOG of the ALV object created in step 1 to retrieve a reference to the ALV grid's field catalog. You can use an inline data declaration to save the upfront declaration of a variable of type REF TO IF_SALV_GUI_FIELD_CATALOG_IDA.
7.
Call the field catalog object's method SET_DATA_ELEMENT method four times, to specify the data elements from which column headings and data types can be derived for the four fields COMPANY_NAME, BP_ID, SO_ID and DAYS_OPEN.
8.
Call the field catalog object's method SET_AVAILABLE_FIELDS to specify that only the columns BP_ID, COMPANY_NAME, SO_ID and DAYS_OPEN should be displayed.
9.
Activate and test the report.
10. Use method DEFAULT_LAYOUT of the ALV object created in step 1, and method SET_SORT_ORDER of the object retrieved this way, to sort the table displayed by COMPANY_NAME in ascending order and by DAYS_OPEN in descending order, and to group the records by COMPANY_NAME before they are displayed. Hint: You can chain the method calls, and use the new VALUE operator to construct the table-like input parameter without having to declare an internal table first and append lines to it. Refer to method DISPLAY_TEMPLATE and how the field catalog and sort order are constructed there using the VALUE operator. 11. Activate and test the report again.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
365
Unit 7: Advanced Topics
HA400
Solution 22: Use ALV Optimized for SAP HANA Task 1: Copy and understand template Create a copy of report HA400_HANA_ALV_T1 via transaction SE80 in your package ZHA400_## (suggested name: ZHA400_##_ALV1, where ## is your group number). Analyze the program to get an idea of the functionality. Activate and execute the program. 1.
Create a copy of the report, making sure to copy all sub-objects too (including the screen and GUI Status). Place it in your package ZHA400_## and assign it to your workbench task. Hint: To copy the report including screens, GUI status etc. using the ABAP Development Tools, use context menu item Duplicate. a)
2.
Analyze the source code of the program. Which are the two main parts of the data processing? In which processing blocks are they encapsulated? a)
3.
Complete this step as before.
Open the source code in the editor.
Depending on the value of selection screen parameter P_CLSSC, either subroutine DISPLAY_TEMPLATE or subroutine DISPLAY_SOLUTION are called. The first subroutine first retrieves data using external view HA400_OPENDAYS and buffers the result in internal table GT_INVOICES. The classic ALV grid is then used to display the table, sorted by COMPANY_NAME and DAYS_OPEN. The second subroutine is not fully implemented yet. Answer: P_CLSSC, DISPLAY_TEMPLATE, DISPLAY_SOLUTION, HA400_OPENDAYS, GT_INVOICES, COMPANY_NAME, DAYS_OPEN
4.
Analyze screen 100 of the program, and pay attention to the name of the Custom Control Area on the screen which has been created for the ALV grid. What is the name of the Custom Control Area? Answer: The name of the Custom Control Area is ALV_AREA.
5.
Activate and execute the program. a)
Perform this step as before.
Continued on next page
366
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Task 2: Use the ALV Optimized for HANA to display the data Edit your program. Complete the implementation of subroutine DISPLAY_SOLUTION so that the data is displayed in the new ALV optimized for HANA. 1.
Declare a reference variable of type REF TO IF_SALV_GUI_TABLE_IDA (or use a corresponding inline data declaration) and use it to receive the object from the factory method CREATE of class CL_SALV_GUI_TABLE_IDA. This method creates and returns an instance of the HANA-optimized ALV. Supply the container reference GO_CONTAINER for the parameter IO_GUI_CONTAINER, and the name of the external view which will supply the data, HA400_OPENDAYS, for the parameter IV_TABLE_NAME. a)
2.
To ensure that only the data chosen by the user on the selection screen is displayed, the details about what data should be retrieved must be supplied to the ALV object. Declare a reference variable of type ref to CL_SALV_RANGE_TAB_COLLECTOR (or use a corresponding inline data declaration), and then create an instance of this class. a)
3.
See source code extract from model solution.
Call method SET_SELECT_OPTIONS for the ALV object retrieved in step 1, passing the internal table from the last step to parameter IT_RANGES. a)
6.
See source code extract from model solution.
Call method GET_COLLECTED_RANGES which exports an internal table of type if_salv_service_types=>yt_named_ranges with the select-options combined into one range. a)
5.
See source code extract from model solution.
Call the method ADD_RANGES_FOR_NAME for the above object, once for each select-option on the selection screen. Pass the select-option internal table for the parameter IT_RANGES, and the field name from external view HA400_OPENDAYS for the parameter IV_NAME. a)
4.
See source code extract from model solution.
See source code extract from model solution.
Use method FIELD_CATALOG of the ALV object created in step 1 to retrieve a reference to the ALV grid's field catalog. You can use an inline data declaration to save the upfront declaration of a variable of type REF TO IF_SALV_GUI_FIELD_CATALOG_IDA. a)
See source code extract from model solution, or un-comment the line of code prepared in the code. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
367
Unit 7: Advanced Topics
7.
HA400
Call the field catalog object's method SET_DATA_ELEMENT method four times, to specify the data elements from which column headings and data types can be derived for the four fields COMPANY_NAME, BP_ID, SO_ID and DAYS_OPEN. a)
8.
Un-comment the corresponding two lines of code prepared, and copy and adjust it three times for the three remaining fields. See source code extract from model solution.
Call the field catalog object's method SET_AVAILABLE_FIELDS to specify that only the columns BP_ID, COMPANY_NAME, SO_ID and DAYS_OPEN should be displayed. a)
9.
Un-comment the corresponding lines of code prepared. See source code extract from model solution.
Activate and test the report. a)
Perform this step as before.
10. Use method DEFAULT_LAYOUT of the ALV object created in step 1, and method SET_SORT_ORDER of the object retrieved this way, to sort the table displayed by COMPANY_NAME in ascending order and by DAYS_OPEN in descending order, and to group the records by COMPANY_NAME before they are displayed. Hint: You can chain the method calls, and use the new VALUE operator to construct the table-like input parameter without having to declare an internal table first and append lines to it. Refer to method DISPLAY_TEMPLATE and how the field catalog and sort order are constructed there using the VALUE operator. a)
See source code extract from model solution.
11. Activate and test the report again. a)
Perform this step as before.
Result
Source code extract from model solution (Program HA400_HANA_ALV_S1) *&---------------------------------------------------------------------* *&
Form
display_solution
*&---------------------------------------------------------------------* FORM display_solution USING pt_range_id
LIKE so_bp_id[]
Continued on next page
368
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
pt_range_name LIKE so_name[]. DATA lt_field_names TYPE if_salv_gui_types_ida=>yts_field_name. CHECK go_container IS NOT BOUND. * Create Container go_container = NEW #( 'ALV_AREA' ). * classical style: *
CREATE OBJECT go_container EXPORTING container_name = 'ALV_AREA'.
* Create ALV instance DATA(lo_salv) = cl_salv_gui_table_ida=>create( io_gui_container
= go_container
iv_table_name
= 'HA400_OPENDAYS'
). * classical style: *
DATA lo_salv TYPE REF TO if_salv_gui_table_ida.
*
lo_salv = cl_salv_gui_table_ida=>create(
*
io_gui_container
= go_container
*
iv_table_name
= 'HA400_OPENDAYS'
*
).
* transform ranges to one range table DATA(lo_range_collector) = NEW cl_salv_range_tab_collector( ). * classical style: *
DATA lo_range_collector TYPE REF TO cl_salv_range_tab_collector.
*
CREATE OBJECT lo_range_collector. lo_range_collector->add_ranges_for_name( iv_name
= 'BP_ID'
it_ranges = pt_range_id ). lo_range_collector->add_ranges_for_name( iv_name
= 'COMPANY_NAME'
it_ranges = pt_range_name ). lo_range_collector->get_collected_ranges( IMPORTING et_named_ranges = DATA(lt_named_ranges) ). * set select options in ALV lo_salv->set_select_options( it_ranges = lt_named_ranges ). * Set column headers / field catalog in ALV DATA(lo_fcat) = lo_salv->field_catalog( ). lo_fcat->set_data_element( iv_field_name
= 'COMPANY_NAME'
iv_data_element_name = 'SNWD_COMPANY_NAME' ).
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
369
Unit 7: Advanced Topics
HA400
lo_fcat->set_data_element( iv_field_name
= 'BP_ID'
iv_data_element_name = 'SNWD_PARTNER_ID' ). lo_fcat->set_data_element( iv_field_name
= 'SO_ID'
iv_data_element_name = 'SNWD_SO_ID' ). lo_fcat->set_data_element( iv_field_name
= 'DAYS_OPEN'
iv_data_element_name = 'HA400_DAYS' ). APPEND 'BP_ID'
TO lt_field_names.
APPEND 'COMPANY_NAME' TO lt_field_names. APPEND 'DAYS_OPEN'
TO lt_field_names.
APPEND 'SO_ID'
TO lt_field_names.
lo_fcat->set_available_fields( lt_field_names
).
* Set grouping and sort order in ALV lo_salv->default_layout( )->set_sort_order( VALUE #( ( field_name = 'COMPANY_NAME' descending = abap_false is_grouped = abap_true ) ( field_name = 'DAYS_OPEN' descending = abap_true ) ) ). * classical style: *
DATA: lt_sort_order TYPE if_salv_gui_types_ida=>yt_sort_rule,
*
ls_sort_order TYPE if_salv_gui_types_ida=>ys_sort_rule.
*
ls_sort_order-field_name = 'COMPANY_NAME'.
*
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 = 'DAYS_OPEN'.
*
ls_sort_order-descending = abap_true.
*
ls_sort_order-is_grouped = abap_false.
*
APPEND ls_sort_order TO lt_sort_order.
*
lo_salv->default_layout( )->set_sort_order( lt_sort_order ).
ENDFORM.
370
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: ABAP List Viewer (ALV) with Integrated Access to SAP HANA
Lesson Summary You should now be able to: • Understand the benefits of SAP List Viewer (ALV) optimized for HANA • Describe the differences between ALV for HANA and classical ALV • Display data in ALV for HANA • Use select options in the data retrieval of ALV for HANA • Supply values for input parameters of external view
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
371
Unit Summary
HA400
Unit Summary You should now be able to: • Describe when fuzzy search can be used • Configure a table column for fuzzy search • Write a SELECT statement that uses fuzzy search • Enable an input field on an SAP GUI screen for type-ahead with fuzzy search • Understand the benefits of SAP List Viewer (ALV) optimized for HANA • Describe the differences between ALV for HANA and classical ALV • Display data in ALV for HANA • Use select options in the data retrieval of ALV for HANA • Supply values for input parameters of external view
372
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 8 Case Study: Optimize a Report on Flight Customer Revenue Unit Overview This unit is designed to give you an example on how a calculation intensive report on flight customer revenue can be optimized for SAP HANA. In a first step you will push down the currency conversion and aggregation onto the database layer by creating an analytic view. In a second step you will replace the classical ALV Grid Control with the new, ABAP List Viewer optimized for SAP HANA.
Unit Objectives After completing this unit, you will be able to: •
Create an Analytic view
Unit Contents Lesson: Creating an Analytic View ...........................................374 Exercise 23: Case Study Part 1: Create a SAP HANA Analytic View ................................................................................379 Exercise 24: Case Study Part 2: Use ALV optimized for SAP HANA 389
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
373
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Lesson: Creating an Analytic View Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: •
Create an Analytic 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.
Figure 204: Creating Analytic View
374
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Figure 205: Creating Analytic View – Set Properties
Figure 206: Creating Analytic View – Data Foundation – Table Join
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
375
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Figure 207: Creating Analytic View – Logical Join
Figure 208: Example: Define Restricted Column
376
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Figure 209: Example: Define Calculated Measure
Figure 210: Creating Analytic View – Semantics
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
377
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Figure 211: Creating Analytic View – Save and Activate
Figure 212: Creating Analytic View – Data Preview
378
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Exercise 23: Case Study Part 1: Create a SAP HANA Analytic View Exercise Objectives After completing this exercise, you will be able to: • Optimize a report that does currency conversions and aggregations of revenues • Create an analytic view on SAP HANA • Understand and use the SAP HANA built-in currency conversion • Create an external view and use it in Open SQL
Business Example Template: Report HA400_CASE_STUDY_T1 Solution: Analytic view ha400.primdb.solution/AN_CUST_WITH_CONVAM Calculation view ha400.primdb.solution/CA_CUST_WITH_CONVAM External view HA400_CUS_CONVAM Report HA400_CASE_STUDY_S1
Task 1: Copy and understand template 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. 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.
3.
What is calculated in the loop over the customer's flight bookings? How is this done?
4.
Activate and execute the program. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
379
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Task 2: Create an analytic view In the SAP HANA Studio, create a view that contains the complete analysis found in subroutine get_data. Make use of the fact that SAP HANA supports currency conversions and aggregations in analytic views. 1.
Go to the SAP HANA Studio. In the Navigator, search for the content package you created earlier in this course.
2.
In your package, create a new analytic view (suggested name: AN_CUST_WITH_CONVAM).
3.
In the Data Foundation, define a referential join of ABAP system T85 tables SCUSTOM and SBOOK with a suitable join condition.
4.
Add all required fields to the views output (See template program). Set a filter on column CANCELLED to make sure only non-cancelled bookings are considered.
5.
In the Semantics of the view, declare currency amount FORCURAM to be of type Measure and all other columns to be of type Attribute.
6.
In the Logical Join of the view, define a calculated column (suggested name: CONVAM) of suitable type that converts the content of column FORCURAM to currency USD. Use the same exchange type (= TYPE_OF_RATE) and conversion date used for the function module in the template program.
7.
Save and Activate your view.
8.
The system automatically generates an additional currency column for the calculated column. Because the generated column's data type can't be mapped to an ABAP Dictionary type reliably, no external view can be created based on the analytical view. To work around this, create a graphical Calculation View of data category Dimension in your package (suggested name: CA_CUST_WITH_CONVAM). The Caluclation View should be a projection of the analytical view, including all columns except the generated column CONVAM.CURENCY.
Task 3: Create an External View Create an external view (suggested name: ZHA400_##_CONVAM, where ## stands for your group number) based on the analytic view you just created. Activate and test it. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database.
2.
In your package, create a new view, as External View and let it point to the SAP HANA calculation view. Continued on next page
380
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
3.
Open the definition of the external view. Use the drop down 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.
4.
Save and activate the external view.
Task 4: Use the external view to optimize the data retrieval of the program Edit your program. Optimize the data retrieval in subroutine get_data by replacing the coding with just one select from your external view. Hint: Make use of aggregation function SUM( ).
2014
1.
In subroutine get_data, implement an Open SQL SELECT that reads data from the external view you just created. Make the select read into data object ct_customers directly.
2.
Activate and test your program.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
381
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Solution 23: Case Study Part 1: Create a SAP HANA Analytic View Task 1: Copy and understand template 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. 1.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Analyze the source code of subroutine get_data. a)
3.
Complete this step as you learned to do in previous classes.
Complete this step as you learned to do in previous classes.
What is calculated in the loop over the customer's flight bookings? How is this done? Answer: The payment in local currency is converted to US Dollar. This is done via function module CONVERT_TO_LOCAL_CURRENCY. The payments are then summed up per customer.
4.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Create an analytic view In the SAP HANA Studio, create a view that contains the complete analysis found in subroutine get_data. Make use of the fact that SAP HANA supports currency conversions and aggregations in analytic views. 1.
Go to the SAP HANA Studio. In the Navigator, search for the content package you created earlier in this course. a)
2.
Perform this step as before.
In your package, create a new analytic view (suggested name: AN_CUST_WITH_CONVAM). a)
Right click on the package and choose New → Analytic View....
b)
Enter the name of the view and a description, then press Finish
Continued on next page
382
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
3.
4.
In the Data Foundation, define a referential join of ABAP system T85 tables SCUSTOM and SBOOK with a suitable join condition. a)
Press the Add Objects button of the Data Foundation box.
b)
Enter the name of table SCUSTOM, select the matching item belonging to schema SAPT85, and press OK. Repeat the same for table SBOOK.
c)
Use the Drag & Drop-function to join field SCUSTOM.MANDT with SBOOK.MANDT and SCUSTOM.ID with SBOOK.CUSTOMID.
d)
Click on one of the join lines and, on the lower right, check the join type and cardinality. Adjust the properties if necessary.
Add all required fields to the views output (See template program). Set a filter on column CANCELLED to make sure only non-cancelled bookings are considered. a)
Click on the grey bullet next to a table field to add it to the output (the bullet's color will then change to orange). The required fields are: • • • • • • • • •
b) 5.
SCUSTOM.MANDT SCUSTOM.ID SCUSTOM.NAME SCUSTOM.POSTCODE SCUSTOM.CITY SCUSTOM.COUNTRY SBOOK.ORDER_DATE SBOOK.FORCURAM SBOOK.FORCURKEY
Right click on field SBOOK.CANCELLED and choose Apply filter to set the filter.
In the Semantics of the view, declare currency amount FORCURAM to be of type Measure and all other columns to be of type Attribute. a)
In the Scenario window on the left, click on Semantics.
b)
On the list of columns edit the type of the columns.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
383
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
6.
7.
In the Logical Join of the view, define a calculated column (suggested name: CONVAM) of suitable type that converts the content of column FORCURAM to currency USD. Use the same exchange type (= TYPE_OF_RATE) and conversion date used for the function module in the template program. a)
In the Scenario window on the left, click on Logical Join to switch to the definition of the view logic.
b)
In the Output window on the right, right-click on node Calculated Columns and Choose New...
c)
Enter a name and a description for the calculated column and set the data type to DECIMAL with dimension = 16 and scale = 2
d)
Change the column type from Attribute to Measure to allow conversion logic and aggregation.
e)
In the Expression Editor, just add the column to be converted (FORCURAM).
f)
Switch to tab Semantics to define the currency conversion rule. Set the type to Amount with Currency and choose Enable for Conversion.
g)
Left-click on the value-help button next to input field Source Currency, choose Column and assign the column with the source currency code (FORCURKEY).
h)
Set Schema for Conversion to HA400_PRIMDB(SAPT85)), Client for Currency Conversion to Session Client. Enter Target Currency “USD” and Exchange Type “M”. For Conversion Date assign column ORDER_DATE.
i)
Finally, close the definition of the calculated column by clicking on OK.
Save and Activate your view. a)
8.
HA400
On the toolbar that shows the name of the view, choose button Save and Activate. Check the Job Log window on the bottom. Make sure it reports a successful activation.
The system automatically generates an additional currency column for the calculated column. Because the generated column's data type can't be mapped to an ABAP Dictionary type reliably, no external view can be created based on the analytical view. To work around this, create a graphical Calculation View of data category Dimension in your package (suggested
Continued on next page
384
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
name: CA_CUST_WITH_CONVAM). The Caluclation View should be a projection of the analytical view, including all columns except the generated column CONVAM.CURENCY. a)
Right click on the package and choose New → Calculation View ....
b)
Enter the name of the view and a description. Select Sub-Type: Graphical and Data Category: Dimension, then press Finish.
c)
Drag your analytical view and drop it onto the calculation view's Projection node.
d)
Add all columns but column CONVAM.CURENCY to the output of the projection node
e)
Save and activate the calculation view.
Task 3: Create an External View Create an external view (suggested name: ZHA400_##_CONVAM, where ## stands for your group number) based on the analytic view you just created. Activate and test it. 1.
Open ABAP Development Tools (perspective ABAP in your Eclipse Session) and go to the project related to the ABAP system that has SAP HANA as primary database. a)
2.
Complete this step as before.
In your package, create a new view, as External View and let it point to the SAP HANA calculation view. a)
Right Click on the project 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 and enter the name (and path) of the SAP HANA calculation view. Then press Enter.
d)
Confirm the transport request and press Finish.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
385
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
3.
HA400
Open the definition of the external view. Use the drop down 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.
4.
a)
Double click the newly created external view in the Project Explorer.
b)
Adjust the dictitonary types as follows: DDIC NAME
DDIC Type
MANDT
CLNT
ID
NUMC
NAME
CHAR
POSTCODE
CHAR
CITY
CHAR
COUNTRY
CHAR
ORDER_DATE
DATS
FORCURKEY
CHAR
FORCURAM
DEC
CONVAM
DEC
ROW_COUNT
DEC
Save and activate the external view. a)
Press button Activate.
Task 4: Use the external view to optimize the data retrieval of the program Edit your program. Optimize the data retrieval in subroutine get_data by replacing the coding with just one select from your external view. Hint: Make use of aggregation function SUM( ). 1.
In subroutine get_data, implement an Open SQL SELECT that reads data from the external view you just created. Make the select read into data object ct_customers directly. a)
See source code extract from model solution. Continued on next page
386
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
2.
Activate and test your program. a)
Complete this step as you learned to do in previous classes.
Result
Source code extract from model solution (Program HA400_CASE_STUDY_S1) *&---------------------------------------------------------------------* *&
Form
get_data
*&---------------------------------------------------------------------* FORM get_data USING pt_range_id
LIKE so_id[]
pt_range_name LIKE so_name[] CHANGING ct_customers
TYPE ty_t_customers.
* Processing ***************** CLEAR ct_customers. SELECT id name postcode city country SUM( convam ) AS convam FROM ha400_cus_convam INTO TABLE ct_customers WHERE id
IN pt_range_id
AND name IN pt_range_name GROUP BY id name postcode city country. ENDFORM.
2014
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
387
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
388
HA400
Lesson: Creating an Analytic View
Exercise 24: Case Study Part 2: Use ALV optimized for SAP HANA Exercise Objectives After completing this exercise, you will be able to: • Optimize a report that does currency conversions and aggregations of revenues • Replace a classical ALV with ALV for HANA • Use more features of ALV for HANA
Business Example Template: Analytic view ha400.primdb.solution/AN_CUST_WITH_CONVAM External view HA400_CUS_CONVAM Report HA400_CASE_STUDY_S1 Solution: Report HA400_CASE_STUDY_S2
Task 1: Copy and understand template 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. Hint: If you completed the previous exercise you may skip this task and continue working on your previous solution ZHA400_##_CSTUDY_1. 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. Where does the data come from?
3.
Activate and execute the program. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
389
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Task 2: Replace the classical ALV with ALV optimized for SAP HANA Edit your program. Comment out the call of subroutines GET_DATA and DISPLAY, and replace it with a call of a new subroutine (suggested name: GET_DATA_AND_DISPLAY). Implement this subroutine so that the data is displayed in ALV optimized for HANA. 1.
Define a new subroutine GET_DATA_AND_DISPLAY for the display with ALV optimized for HANA. Choose the same parameters as in subroutine GET_DATA but without the changing parameter for exporting the data.
2.
Comment out the call of subroutines GET_DATA and DISPLAY, and instead call the subroutine GET_DATA_AND_DISPLAY.
3.
Copy the source code of subroutine DISPLAY to subroutine GET_DATA_AND_DISPLAY.
4.
In subroutine GET_DATA_AND_DISPLAY, change the type of reference variable lo_salv to type ref to IF_SALV_GUI_TABLE_IDA. Replace the call of factory method CL_SALV_TABLE=>FACTORY with a call of factory method CREATE of the class CL_SALV_GUI_TABLE_IDA. Supply the container reference for the parameter IO_GUI_CONTAINER, and the name of the external view which will supply the data, for the parameter IV_TABLE_NAME.
5.
To ensure that only the data chosen by the user on the selection screen is displayed, the details about what data should be retrieved must be supplied to the ALV object. Declare a reference variable of type ref to CL_SALV_RANGE_TAB_COLLECTOR, and then create an instance of this class.
6.
Call the method ADD_RANGES_FOR_NAME for the above object, once for each select-option on the selection screen. Pass the select-option internal table for the parameter IT_RANGES, and the field name from table SCUSTOM for the parameter IV_NAME.
7.
Call method GET_COLLECTED_RANGES which exports an internal table of type if_salv_service_types=>yt_named_ranges with the select-options combined into one range.
8.
Call method SET_SELECT_OPTIONS for the ALV object retrieved in step 4, passing the internal table from the last step to parameter IT_RANGES.
9.
Activate and test the report.
Continued on next page
390
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Task 3: Hide unwanted fields and add headings Improve the display of the data. Hide any fields that are part of the view but should not be displayed in ALV. Provide headings for the remaining fields by setting appropriate data elements. 1.
Define an internal table of type if_salv_gui_types_ida=>yt_field_name. Fill it with the names of the fields that should be displayed
2.
Call method DEFAULT_LAYOUT of your ALV instance to get access to the layout object. For this object call method SET_VISIBLE_FIELDS and provide the internal table. Hint: By changing the sequence of the field names you can change the sequence in which of the columns are displayed.
3.
Define a reference variable of TYPE REF TO IF_SALV_GUI_FIELD_CATALOG_IDA. Call method FIELD_CATALOG for your ALV instance, and use this reference variable to receive the field catalog object from this method.
4.
Now call method SET_DATA_ELEMENT for the field catalog object, once for each column to be displayed in the ALV. Supply suitable values for the parameters IV_FIELD_NAME (for the field name of the external view) and IV_DATA_ELEMENT_NAME (for the data element whose description should be used for the ALV column header) as follows:
5.
FIELD
DATA_ELEMENT
ID
S_CUSTOMER
NAME
S_CUSTNAME
POSTCODE
POSTCODE
CITY
CITY
COUNTRY
S_COUNTRY
CONVAM
S_SUM
Activate and test the report.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
391
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Task 4: Optional: Sort order and grouping Pre-sort the display by country, city, customer id and name and establish a grouping by country and city.
392
1.
Define an internal table of type if_salv_gui_types_ida=>yt_sort_rule. Fill it with an entry for each column you want to be sorted. Make sure to set the sort direction (field descending). In addition, set the grouping flag (field is_grouped) to abap_true for those columns you want to be grouped.
2.
Activate and test the report.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Solution 24: Case Study Part 2: Use ALV optimized for SAP HANA Task 1: Copy and understand template 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. Hint: If you completed the previous exercise you may skip this task and continue working on your previous solution ZHA400_##_CSTUDY_1. 1.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Complete this step as you learned to do in previous classes.
Analyze the source code of subroutine get_data. Where does the data come from? Answer: The subroutine selects from external view HA400_CUS_CONVAM, which points to SAP HANA Analytic view AN_CUST_WITH_CONVAM in package ha400.primdb.solution.
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 optimized for SAP HANA Edit your program. Comment out the call of subroutines GET_DATA and DISPLAY, and replace it with a call of a new subroutine (suggested name: GET_DATA_AND_DISPLAY). Implement this subroutine so that the data is displayed in ALV optimized for HANA. 1.
Define a new subroutine GET_DATA_AND_DISPLAY for the display with ALV optimized for HANA. Choose the same parameters as in subroutine GET_DATA but without the changing parameter for exporting the data. a)
2.
See source code extract from model solution.
Comment out the call of subroutines GET_DATA and DISPLAY, and instead call the subroutine GET_DATA_AND_DISPLAY. a)
See source code extract from model solution.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
393
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
3.
Copy the source code of subroutine DISPLAY to subroutine GET_DATA_AND_DISPLAY. a)
4.
See source code extract from model solution.
Call method SET_SELECT_OPTIONS for the ALV object retrieved in step 4, passing the internal table from the last step to parameter IT_RANGES. a)
9.
See source code extract from model solution.
Call method GET_COLLECTED_RANGES which exports an internal table of type if_salv_service_types=>yt_named_ranges with the select-options combined into one range. a)
8.
See source code extract from model solution.
Call the method ADD_RANGES_FOR_NAME for the above object, once for each select-option on the selection screen. Pass the select-option internal table for the parameter IT_RANGES, and the field name from table SCUSTOM for the parameter IV_NAME. a)
7.
See source code extract from model solution.
To ensure that only the data chosen by the user on the selection screen is displayed, the details about what data should be retrieved must be supplied to the ALV object. Declare a reference variable of type ref to CL_SALV_RANGE_TAB_COLLECTOR, and then create an instance of this class. a)
6.
See source code extract from model solution.
In subroutine GET_DATA_AND_DISPLAY, change the type of reference variable lo_salv to type ref to IF_SALV_GUI_TABLE_IDA. Replace the call of factory method CL_SALV_TABLE=>FACTORY with a call of factory method CREATE of the class CL_SALV_GUI_TABLE_IDA. Supply the container reference for the parameter IO_GUI_CONTAINER, and the name of the external view which will supply the data, for the parameter IV_TABLE_NAME. a)
5.
HA400
See source code extract from model solution.
Activate and test the report. a)
Perform this step as before.
Continued on next page
394
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
Task 3: Hide unwanted fields and add headings Improve the display of the data. Hide any fields that are part of the view but should not be displayed in ALV. Provide headings for the remaining fields by setting appropriate data elements. 1.
Define an internal table of type if_salv_gui_types_ida=>yt_field_name. Fill it with the names of the fields that should be displayed a)
2.
See source code extract from model solution.
Call method DEFAULT_LAYOUT of your ALV instance to get access to the layout object. For this object call method SET_VISIBLE_FIELDS and provide the internal table. Hint: By changing the sequence of the field names you can change the sequence in which of the columns are displayed. a)
3.
See source code extract from model solution.
Define a reference variable of TYPE REF TO IF_SALV_GUI_FIELD_CATALOG_IDA. Call method FIELD_CATALOG for your ALV instance, and use this reference variable to receive the field catalog object from this method. a)
4.
Now call method SET_DATA_ELEMENT for the field catalog object, once for each column to be displayed in the ALV. Supply suitable values for the parameters IV_FIELD_NAME (for the field name of the external view) and IV_DATA_ELEMENT_NAME (for the data element whose description should be used for the ALV column header) as follows: FIELD
DATA_ELEMENT
ID
S_CUSTOMER
NAME
S_CUSTNAME
POSTCODE
POSTCODE
CITY
CITY
COUNTRY
S_COUNTRY
CONVAM
S_SUM
a) 5.
See source code extract from model solution.
See source code extract from model solution.
Activate and test the report. a)
Perform this step as before. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
395
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Task 4: Optional: Sort order and grouping Pre-sort the display by country, city, customer id and name and establish a grouping by country and city. 1.
Define an internal table of type if_salv_gui_types_ida=>yt_sort_rule. Fill it with an entry for each column you want to be sorted. Make sure to set the sort direction (field descending). In addition, set the grouping flag (field is_grouped) to abap_true for those columns you want to be grouped. a)
2.
See source code extract from model solution.
Activate and test the report. a)
Perform this step as before.
Result
Source code extract from model solution (Program HA400_CASE_STUDY_S2) *&---------------------------------------------------------------------* *&
Form
get_data_and_display
*&---------------------------------------------------------------------* FORM get_data_and_display USING pt_range_id
LIKE so_id[]
pt_range_name LIKE so_name[]. * control specific: DATA: lo_cont TYPE REF TO cl_gui_custom_container, 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 lt_visible_fields TYPE if_salv_gui_types_ida=>yt_field_name. DATA: lo_fcat
TYPE REF TO if_salv_gui_field_catalog_ida,
lo_exc
TYPE REF TO cx_salv_ida_contract_violation.
* DATA: lt_sort_order TYPE if_salv_gui_types_ida=>yt_sort_rule, ls_sort_order LIKE LINE OF lt_sort_order. * Create Container *-------------------* CREATE OBJECT lo_cont
Continued on next page
396
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
EXPORTING repid
= sy-repid
dynnr
= '0100'
container_name = 'ALV_AREA' EXCEPTIONS others
= 1.
IF sy-subrc 0. MESSAGE a010(yha400). ENDIF. * Create ALV Instance *----------------------* lo_salv = cl_salv_gui_table_ida=>create( io_gui_container
= lo_cont
iv_table_name
= 'HA400_CUS_CONVAM'
). * 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 ). lo_salv->set_select_options( EXPORTING it_ranges
= lt_named_ranges
). * Hide unwanted fields *-----------------------* APPEND 'COUNTRY'
TO lt_visible_fields.
APPEND 'CITY'
TO lt_visible_fields.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
397
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
APPEND 'POSTCODE'
HA400
TO lt_visible_fields.
APPEND 'ID'
TO lt_visible_fields.
APPEND 'NAME'
TO lt_visible_fields.
APPEND 'CONVAM'
TO lt_visible_fields.
lo_salv->default_layout( )->set_visible_fields( lt_visible_fields ). * Set Data Elements *--------------------* TRY. lo_fcat = lo_salv->field_catalog( ). lo_fcat->set_data_element( iv_field_name
= 'ID'
iv_data_element_name = 'S_CUSTOMER' ). lo_fcat->set_data_element( iv_field_name
= 'NAME'
iv_data_element_name = 'S_CUSTNAME' ). lo_fcat->set_data_element( iv_field_name
= 'POSTCODE'
iv_data_element_name = 'POSTCODE' ). lo_fcat->set_data_element( iv_field_name
= 'CITY'
iv_data_element_name = 'CITY' ). lo_fcat->set_data_element( iv_field_name
= 'COUNTRY'
iv_data_element_name = 'S_COUNTRY' ). lo_fcat->set_data_element( iv_field_name
= 'CONVAM'
iv_data_element_name = 'S_SUM' ). * * Optional: Preset sort order and grouping *------------------------------------------* 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 = 'ID'.
Continued on next page
398
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Creating an Analytic View
ls_sort_order-descending = abap_false. ls_sort_order-is_grouped = abap_false. APPEND ls_sort_order TO lt_sort_order. ls_sort_order-field_name = 'NAME'. ls_sort_order-descending = abap_false. ls_sort_order-is_grouped = abap_false. APPEND ls_sort_order TO lt_sort_order. lo_salv->default_layout( )->set_sort_order( lt_sort_order ). * Exception Handling *--------------------* CATCH cx_salv_ida_contract_violation INTO lo_exc. MESSAGE lo_exc TYPE 'I'. ENDTRY. * Finally, Display_screen *-------------------------* CALL SCREEN 100. ENDFORM.
2014
"get_data_and_display
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
399
Unit 8: Case Study: Optimize a Report on Flight Customer Revenue
HA400
Lesson Summary You should now be able to: • Create an Analytic view
400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Unit Summary
Unit Summary You should now be able to: • Create an Analytic view
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
401
Unit Summary
402
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Unit 9 Appendix Unit Overview This unit contains an optional lesson and exercises. They cover ABAP language enhancements that are especially useful when working with native SQL calls and ADBC.
Unit Objectives After completing this unit, you will be able to: • •
Use inline data declarations in ABAP code Use string and table expressions in ABAP code
Unit Contents Lesson: Additional ABAP Language Enhancements ......................404 Exercise 25: Use ABAP Expressions and Inline Data Declarations to Simplify Native SQL Calls .................................................409 Exercise 26: Use Table Expressions to Simplify Native SQL Calls ..415
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
403
Unit 9: Appendix
HA400
Lesson: Additional ABAP Language Enhancements Lesson Overview –
Lesson Objectives After completing this lesson, you will be able to: • •
Use inline data declarations in ABAP code Use 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.
Figure 213: Helpful ABAP Language Improvements: Expressions in ABAP 7.4
404
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
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. 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 run time and returns a result. It can therefore be used in program statements in places where youd 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 sub-sequent statements. The situation has improved considerably over the last 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 to express more what you want to calculate, less the “How” to calculate. You dont have to write a statement for each intermediate step in a calculation and this way need fewer local variables used once only.
Figure 214: String Expressions and String Templates
The first example 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.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
405
Unit 9: Appendix
HA400
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: • • • •
Use the pipe symbol to define so-called string templates. Mix in the values of variables or even expressions, enclosing them in curly braces. Simply use single quotes within the string templates, as the string templates are not delimited by single quotes. Use the string expression directly as parts of statements, e.g. as parameter of a method call. You dont have to assign the string to a local variable first.
Figure 215: Inline Declarations and Constructor Expressions
406
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
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: • • •
•
•
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 ( ), 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 ( ), 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 ( ), 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.
Figure 216: Table Expressions
Another helpful type of expressions are 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
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
407
Unit 9: Appendix
HA400
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.
408
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
Exercise 25: Use ABAP Expressions and Inline Data Declarations to Simplify Native SQL Calls Exercise Objectives After completing this exercise, you will be able to: • Use string expressions to simplify ADBC calls • Use inline data declarations, the NEW and REF operators to simplify ADBC calls.
Business Example Template: Report HA400_EXPR_ADBC_T1 Solution: Report HA400_EXPR_ADBC_S1
Task 1: Copy and understand template Create a copy of report HA400_EXPR_ADBC_T1 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_EXPR_1, where ## is your group number). Analyze the source code, activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. 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.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
409
Unit 9: Appendix
HA400
Task 2: Simplify the ABAP code by making use of expressions Simplify the ABAP code by removing one-off variables lr_data and lv_sql, and by using inline data declarations for the remaining variables.
410
1.
Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution, remove local variable lv_sql: remove its declaration and replace the reference to the variable in the later method call by the string expression assigned to the local variable. Remove the line containing the assignment to lv_sql.
2.
Also remove local variable lr_data. Replace its use in the later method call by a REF operator, using table ct_customers as argument.
3.
Remove the explicit declarations of local variables lo_sql and lo_result and of exception lx_sql_exc. Use inline data declarations (operator DATA() to declare lo_result and exception lx_sql_exc where these variables are needed first. Use the DATA() operator to declare lo_sql where the variable is needed first, and the NEW operator to replace the CREATE OBJECT statement.
4.
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
Solution 25: Use ABAP Expressions and Inline Data Declarations to Simplify Native SQL Calls Task 1: Copy and understand template Create a copy of report HA400_EXPR_ADBC_T1 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_EXPR_1, where ## is your group number). Analyze the source code, activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. 1.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Simplify the ABAP code by making use of expressions Simplify the ABAP code by removing one-off variables lr_data and lv_sql, and by using inline data declarations for the remaining variables. 1.
Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution, remove local variable lv_sql: remove its declaration and replace the reference to the variable in the later method call by the string expression assigned to the local variable. Remove the line containing the assignment to lv_sql. a)
2.
See source code extract from model solution.
Also remove local variable lr_data. Replace its use in the later method call by a REF operator, using table ct_customers as argument. a)
See source code extract from model solution.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
411
Unit 9: Appendix
HA400
Remove the explicit declarations of local variables lo_sql and lo_result and of exception lx_sql_exc. Use inline data declarations (operator DATA() to declare lo_result and exception lx_sql_exc where these variables are needed first. Use the DATA() operator to declare lo_sql where the variable is needed first, and the NEW operator to replace the CREATE OBJECT statement.
3.
a) 4.
See source code extract from model solution.
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.
Result
Source code extract from model solution (Program HA400_EXPR_ADBC_S1) *&---------------------------------------------------------------------* *&
Form
get_data_template
*&---------------------------------------------------------------------* FORM get_data_template 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 **************************** CLEAR ct_customers. TRY. * 1. Create statement object CREATE OBJECT lo_sql.
Continued on next page
412
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
* 2. assemble SQL statement lv_sql = |SELECT "BP_ID", "COMPANY_NAME", AVG("DAYS_OPEN") AS AVG_DAYS_OPEN | && |
FROM "_SYS_BIC"."ha400.secdb.demo/AT_OPEN_INVOICES"
| &&
| GROUP BY "BP_ID", "COMPANY_NAME" | && | ORDER BY "BP_ID" |. * 3. Execute Query lo_result = lo_sql->execute_query( lv_sql ). * 4. Assign target variable GET REFERENCE OF ct_customers INTO lr_data. lo_result->set_param_table( lr_data ). * 5. Read result into internal Table lo_result->next_package( ). * 6. 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. * Processing **************************** CLEAR ct_customers. TRY. * 1. Create statement object DATA(lo_sql) = NEW cl_sql_statement( ). * 2. assemble SQL statement and execute query in one step DATA(lo_result) = lo_sql->execute_query( |SELECT "BP_ID", "COMPANY_NAME", AVG("DAYS_OPEN") AS AVG_DAYS_OPEN | && |
FROM "_SYS_BIC"."ha400.secdb.demo/AT_OPEN_INVOICES"
| &&
| GROUP BY "BP_ID", "COMPANY_NAME" | && | ORDER BY "BP_ID" | ).
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
413
Unit 9: Appendix
HA400
* 3. Assign target variable *
GET REFERENCE OF ct_customers INTO lr_data. lo_result->set_param_table( REF #( ct_customers ) ).
* 4. Read result into internal Table lo_result->next_package( ). * 5. Close connection lo_result->close( ). * Exception handling CATCH cx_sql_exception INTO DATA(lx_sql_exc). "Excpt. Class for SQL Error MESSAGE lx_sql_exc TYPE 'E'. ENDTRY. ENDFORM.
414
"
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
Exercise 26: Use Table Expressions to Simplify Native SQL Calls Exercise Objectives After completing this exercise, you will be able to: • Use table expressions to simplify ADBC calls • Use inline data declarations, the NEW and REF operators to simplify ADBC calls.
Business Example Template: Report HA400_EXPR_ADBC_T2 Solution: Report HA400_EXPR_ADBC_S2
Task 1: Copy and understand template Create a copy of report HA400_EXPR_ADBC_T2 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_EXPR_2, where ## is your group number). Analyze the source code, activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. Hint: The report calls a SAP HANA database procedure using native SQL and ADBC, a topic covered in another lesson only. You don't have to understand exactly how the report works at this point. Focus on simplifying it using table expressions. 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.
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
415
Unit 9: Appendix
HA400
Task 2: Simplify the ABAP code by making use of table expressions Simplify the ABAP code by removing one-off variable lr_data and variable lr_overview.
416
1.
Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution, remove local variable lr_data. Replace its use in the later method calls by a REF operator, using the appropriate internal table as argument.
2.
Analyze how internal table lt_overview and reference variable lr_overview are used. Use table expressions in the string templates used in the second and third method call lo_sql->execute_query( ... ) to remove local variable lr_overview and the corresponding READ TABLE statements.
3.
Activate and test your program. Make sure the two subroutines deliver exactly the same data.
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
Solution 26: Use Table Expressions to Simplify Native SQL Calls Task 1: Copy and understand template Create a copy of report HA400_EXPR_ADBC_T2 in the system in which SAP HANA is the primary database. Use your package ZHA400_## (suggested name: ZHA400_##_EXPR_2, where ## is your group number). Analyze the source code, activate and execute the program. Hint: To copy the report using the ABAP Development Tools, use context menu item Duplicate. Hint: The report calls a SAP HANA database procedure using native SQL and ADBC, a topic covered in another lesson only. You don't have to understand exactly how the report works at this point. Focus on simplifying it using table expressions. 1.
Create a copy of the report. Place it in your package ZHA400_## and assign it to your workbench task. a)
2.
Complete this step as you learned to do in previous classes.
Activate and execute the program. a)
Complete this step as you learned to do in previous classes.
Task 2: Simplify the ABAP code by making use of table expressions Simplify the ABAP code by removing one-off variable lr_data and variable lr_overview. 1.
Edit your program. Copy the source code of subroutine get_data_template to subroutine get_data_solution. In subroutine get_data_solution, remove local variable lr_data. Replace its use in the later method calls by a REF operator, using the appropriate internal table as argument. a)
2.
See source code extract from model solution.
Analyze how internal table lt_overview and reference variable lr_overview are used. Use table expressions in the string templates used in the second and third method call lo_sql->execute_query( ... ) to remove local variable lr_overview and the corresponding READ TABLE statements. a)
See source code extract from model solution. Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
417
Unit 9: Appendix
HA400
3.
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.
Result
Source code extract from model solution (Program HA400_EXPR_ADBC_S2) *&---------------------------------------------------------------------* *&
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.
* Declarations **************** * ADBC Objects and Variables DATA:
lr_data TYPE REF TO data.
* type for result overview TYPES: BEGIN OF lty_s_overview, param TYPE string, value TYPE string, END OF lty_s_overview. * Data objects for result overview DATA: lt_overview TYPE TABLE OF lty_s_overview, lr_overview TYPE REF TO
lty_s_overview.
* Processing ******************************** CLEAR: ct_cust_early, ct_cust_late. TRY. * Create statement object (primary DB connection) DATA(lo_sql) = NEW cl_sql_statement(
).
* Call Procedure with Overview (fill lt_overview) DATA(lo_result) = lo_sql->execute_query(
Continued on next page
418
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
|CALL _SYS_BIC."ha400.primdb.demo/DP_EARLY_AND_LATE_PAYERS"( | && |{ pv_number }, null , null ) WITH OVERVIEW | ). GET REFERENCE OF lt_overview INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). lo_result->close( ). * Retrieve first result (Parameter et_early) READ TABLE lt_overview REFERENCE INTO lr_overview WITH KEY param = 'ET_EARLY'. lo_result = lo_sql->execute_query( |SELECT * FROM { lr_overview->value } | ). GET REFERENCE OF ct_cust_early INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). lo_result->close( ). * Retrieve second result (Parameter et_late) READ TABLE lt_overview REFERENCE INTO lr_overview WITH KEY param = 'ET_LATE'. lo_result = lo_sql->execute_query( |SELECT * FROM { lr_overview->value } | ). GET REFERENCE OF ct_cust_late INTO lr_data. lo_result->set_param_table( lr_data ). lo_result->next_package( ). lo_result->close( ). * Exception handling CATCH cx_sql_exception INTO DATA(lx_sql_exc). "Excpt. Class for SQL Error MESSAGE lx_sql_exc TYPE 'E'. ENDTRY. 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.
* Declarations **************** * type for result overview TYPES: BEGIN OF lty_s_overview, param TYPE string, value TYPE string,
Continued on next page
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
419
Unit 9: Appendix
HA400
END OF lty_s_overview. * Data objects for result overview DATA: lt_overview TYPE TABLE OF lty_s_overview. * Processing ******************************** CLEAR: ct_cust_early, ct_cust_late. TRY. * Create statement object (primary DB connection) DATA(lo_sql) = NEW cl_sql_statement(
).
* Call Procedure with Overview (fill lt_overview) DATA(lo_result) = lo_sql->execute_query( |CALL _SYS_BIC."ha400.primdb.demo/DP_EARLY_AND_LATE_PAYERS"( | && |{ pv_number }, null , null ) WITH OVERVIEW | ). lo_result->set_param_table( REF #( lt_overview ) ). lo_result->next_package( ). lo_result->close( ). * Retrieve first result (Parameter et_early) lo_result = lo_sql->execute_query( |SELECT * FROM { lt_overview[ param = 'ET_EARLY' ]-value } | ). lo_result->set_param_table( REF #( ct_cust_early ) ). lo_result->next_package( ). lo_result->close( ). * Retrieve second result (Parameter et_late) lo_result = lo_sql->execute_query( |SELECT * FROM { lt_overview[ param = 'ET_LATE' ]-value } | ). lo_result->set_param_table( REF #( ct_cust_late ) ). lo_result->next_package( ). lo_result->close( ). * Exception handling CATCH cx_sql_exception INTO DATA(lx_sql_exc). "Excpt. Class for SQL Error MESSAGE lx_sql_exc TYPE 'E'. ENDTRY.
420
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Lesson: Additional ABAP Language Enhancements
Lesson Summary You should now be able to: • Use inline data declarations in ABAP code • Use string and table expressions in ABAP code
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
421
Unit Summary
HA400
Unit Summary You should now be able to: • Use inline data declarations in ABAP code • Use string and table expressions in ABAP code
422
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
HA400
Course Summary
Course Summary You should now be able to: • • • • • • • • • •
2014
Understand the technical concepts of SAP HANA Understand how to optimize classic ABAP for SAP HANA Describe the use of analysis tools for performance optimization (Runtime Analysis, Code Inspector, SQL Trace, SQL Performance Tuning Worklist) Understand the SQL performance rules of ABAP for SAP HANA Access SAP HANA from ABAP using native SQL and ADBC (ABAP Database Connectivity) Use enhanced Open SQL Use Core Data Services in ABAP to define advanced views Call SAP HANA stored procedures in ABAP and embed stored procedures in ABAP Consume SAP HANA views in ABAP Create a simple SAP HANA view
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
423
Course Summary
424
HA400
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
2014
Feedback SAP AG has made every effort in the preparation of this course to ensure the accuracy and completeness of the materials. If you have any corrections or suggestions for improvement, please record them in the appropriate place in the course evaluation.
2014
© 2014 SAP AG or an SAP affiliate company. All rights reserved.
425
View more...
Comments