Code Standard S4 HANA
Code Standard S4 HANA
Packages are designed to help developers modularize, encapsulate, and decouple units in SAP
system. In the programmer, one package would be created per work-stream. Any major bespoke
development would have a sub-package created. Every technical specification document should
have the package information. Developments will not be started without appropriate package.
Naming conventions for Transports will be adhered to with Logical Units of work placed into a
Transport/task.
Separate business behaviors in packages with the main goal to replace or delete each package
SAP HANA (High Performance Analytical Appliance) is a revolutionary in-memory technology which
has transformed the way ABAP applications are developed. In order to take advantage of the
Hardware and Software innovations at the least part of the application logic must be executed in the
database.
Traditionally ABAP based applications use the “data-to-code paradigm” wherein the orchestration
and calculation logic are performed in the Application Layer. While using data to code paradigm,
ABAP Programs fetches the data from the database tables and buffers them into the internal tables
of the application server. The logic is applied on the application server and the calculations are
performed and eventually either displayed on the presentation sever. All the calculation logic is
wholly implemented in the application server wherein a substantial amount of data may be
transferred from the Database server to the Application server. This work well for traditional
database applications but not for ABAP on HANA
ABAP applications specifically designed for SAP HANA use the “code-to-data paradigm” where some
of the application logic is executed in the database layer. In extreme cases the entire application
logic can be executed in the database layer. The amount of data transfer to the application server
can be kept to a minimum which fundamentally speeds up the process.
In ABAP for HANA you can push down data intense computations and calculations to the HANA
DB layer instead bringing all the data to the ABAP layer and the processing the data to do
computations. This is what is termed as Code-to-Data paradigm in the context of developing
ABAP applications optimized for HANA.
1.2.2. Code Push Down to HANA from ABAP using Open SQL
1. Start using the new Open SQL syntax.
3. Use arithmetic and string expressions within Open SQL statements instead of looping over
the data fetched to do the arithmetic and string operations.
Arithmetic Expressions
String Expressions
SELECT SINGLE
char1 AS text1,
char2 AS text2,
CONCAT( char1,char2 ) AS concat,
LPAD( char1,10,'x' ) AS lpad,
LENGTH( char1 ) AS length,
LTRIM( char1,' ' ) AS ltrim,
REPLACE( char1,'12',' ' ) AS replace,
RIGHT( char1,3 ) as right,
RTRIM( char1,'3' ) AS rtrim,
SUBSTRING( char1,3,3 ) AS substring
FROM demo_expressions
INTO @DATA(result).
4. Use computed columns in order to push down computations that would otherwise be done in a
long loops
SELECT char1 && '_' && char2 AS
group, MAX( num1 + num2 ) AS
max, MIN( num1 + num2 ) AS min
FROM demo_expressions
GROUP BY char1, char2
HAVING MIN( num1 * num2 ) > 25
ORDER BY group
INTO TABLE @DATA(grouped_having).
5. Use CASE and/or IF..ELSE expressions within the Open SQL in order embed the logic of
conditional expression which in the past would have been done after fetching the results from
the database.
The graphic below provides an overview of the different code pushdown programming techniques
delivered from ABAP 7.4, and enhanced with ABAP 7.5.
The user may vary the spelling slightly in his search requests.
In SAP HANA, you can call the fuzzy search by using the CONTAINS predicate with the FUZZY option
in the WHERE clause of a SELECT statement.
The sequence of the search results is optimized in such a way that results with the highest
probability rate are presented at the top of the list.
Search facets
The search results can be counted and grouped according to specific criteria. For example, when
searching for airlines, you can view the distribution of the airlines per country.
You can extract additional information from texts, which allows you to gain insights on semantical
aspects.
Because the text search function in SAP HANA is not part of the standard features of a traditional
database, the CONTAINS statement is unfortunately not yet supported in Open SQL. However, you
can still employ the text search directly from within ABAP if you use Native SQL.
Using the text search via ADBC is pretty simple. To do this, all you need to do is include the
CONTAINS statement in the Native SQL statement
lv_sql = | SELECT * FROM SCARR | && | WHERE mandt = '{ sy-mandt }' and | && |
CONTAINS(carrname, '{ search }', fuzzy(0.8))|.
TRY. " Prepare SQL connection and statement
DATA(lo_result) =
cl_sql_connection=>get_connection(
)->create_statement(
)->execute_query( lv_sql ).
lo_result->close( ).
CATCH cx_sql_exception.
Similarly, you can also run search requests across attribute views. Although the access via OpenSQL
is not possible here, either—due to the lack of support for the CONTAINS statement—it is
advisable that you first define an external view based on the respective attribute view. This will
facilitate the processing of data types because there is already a representation available in the
ABAP Data Dictionary
You can define an input help in the ABAP Data Dictionary. In general, these input helps can then be
used in both classic Dynpro-based applications and in application interfaces that have been created
using Web Dynpro ABAP or the Floorplan Manager. In this context, you can either create single (so-
called elementary) search helps, or combine multiple input helps into a collective search help. The
individual search helps are then usually displayed on separate tabs. Collective search helps are
particularly useful if you want to extend an existing search help by an optimized variant in SAP HANA
(this variant will then be hidden in other databases).
The data retrieval process in a search help can be modified using a search help exit where fuzzy
search function can be implemented.
Without CDS, Intensive calculations are done on the application layer avoiding costly computations
in the database. This results in rather simple SQL queries between application and database layer.
The drawback is however that lots of data needs to be transferred back and forth between those
two layers. Often, this is very time-consuming. CDS allows for a data centric approach. Intensive
computations are pushed into the database by using complex views and functions. Depending on
the use case,this may dramatically reduce execution time and simplify application coding.
1) Define View.
Define View with Join.
Define View with Association.
Define View with Parameters.
Annotations
2) Extend View.
3) Define Table Function with Parameters.
Define View
Defines a CDS view in the ABAP CDS in a CDS source code. A CDS is implemented using a query select
statement. The annotation AbapCatalog.sqlViewName must be specified before the view itself is
defined using DEFINE VIEW.
Define View with Joins
Defining a join between two data sources of a CDS view in ABAP CDS using join expression.
Defining an association of the name _assoc in a SELECT statement of a CDS view. An association
connects the first elementary data source data source specified as the initial data source
(after FROM using the ON condition cond_exp) to the data source data_source specified as the
target data source (in the definition of the association). The target data source cannot be built using
joins.
Define View with Parameters
Defines Input parameters pname1, pname2 in a CDS View in ABAP CDS in a comma separated list.
Each input parameter must be typed with a data type parameter type.
Extend View
Extend view is used to extend standard or custom CDS view without making any changes to the
original CDS view. In SQL view of original CDS view the classical append view is created as .APPEND in
ABAP Dictionary.(similar as append structure is used to extend DDIC tables.)
A CDS table function is defined in CDS source code of a CDS data definition in the ABAP Development
Tools (ADT) using the statement DEFINE TABLE_FUNCTION in the ABAP Core Data Services
(CDS) DDL.
A CDS table function is declared as a CDS entity using DEFINE TABLE_FUNCTION. As a data
type in ABAP Dictionary, the CDS entity represents a structured type with the elements of
the CDS table function as components and can be used like any CDS entity.
CDS table functions are implemented in Native SQL in an AMDP method and the
implementation is managed as an AMDP function by the AMDP framework in the database
system.
At the start of the project, all developers will agree to use the latest version of the ABAP
Development Tools for SAP NetWeaver (in short: ADT). After that, only update the version when all
developers agree to do so.
The general syntax rules for the CDS DDL and CDS DCL for defining CDS objects in ABAP CDS are as
follows:
Keywords
Keywords must be all uppercase, all lowercase, or in lowercase with an uppercase initial letter. Other
mixes of uppercase and lowercase are not allowed.
Names:
A name can consist of letters, numbers, underscores (_), and slashes (/).
Support lInks:
Link: https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/abencds_annotations.html
https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/ABENCDS.html
https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/ABENABAP_RAP.html
The separator for names with multiple parts is a period (.). Names with multiple parts can be paths,
columns with a prefixed data source, and annotations.
ALL, AND, AS, ASSOCIATION, AVG, CASE, CAST, CROSS, COUNT, DISTINCT, EXISTS, EXTEND, FROM, F
ULL, GROUP, HAVING, INNER, JOIN, KEY, LEFT, MAX, MIN, NOT, NULL, ON, OR, ORDER, RIGHT, SELEC
T, SUM, UNION, VIEW, WHEN, WHERE
Literals: Numeric literals must always be specified in full and a decimal point (.) used as a decimal
separator if necessary.
Comments: Two forward slashes (//) or two hyphens (--) introduce a comment, which continues
until the end of the line.
Comments within lines or that span multiple lines are enclosed by the characters /* and */.
Protected words: Certain keywords are protected and cannot be used as self-defined names. The
reserved names that cannot be used are specified in the database table TRESE.
Note
The closing semicolon after a statement is optional because one piece of CDS source code can
currently only contain a single statement.
Examples
SELECT, select, and select are all valid ways of specifying a keyword. seLect and SeLect, on the other
hand, produce syntax errors.
The structure of such a view is defined by specifying the relevant database tables and the set of
table fields to be used in the view.
A CDS view is defined for existing database tables and views, or for other CDS views in the ABAP
Dictionary, using the DEFINE VIEW DDL statement. A CDS view serves to dene the structure of a CDS
database view and represents a projection onto one or several database tables or database views in
the ABAP Dictionary.
Note
CDS database views and CDS entities are part of one and the same namespace. Therefore, you must
assign different names for a CDS database view and the entity.
ABAP CDS table functions dene table functions that are implemented natively on the database and
can be called in CDS. As such, they support the HANA platform code pushdown capabilities in ABAP
CDS.
Defining ABAP CDS Table Functions
A CDS table function is defined using the ABAP CDS statement DEFINE TABLE FUNCTION and can be
used as the data source in ABAP SQL read statements.
Note: In contrast to the CDS views, the CDS table functions can be implemented using Native SQL.
This implementation is done within an AMDP method of an AMDP class and is managed as an AMDP
function by the AMDP framework in the database system.
• AMDPs are introduced to easily enable us to get the best out of ABAP Development
for HANA.
• AMDPs are allowing developers to write database procedures directly in ABAP environment
using ABAP methods and ABAP data types.
• Push down data intense computations and calculations to the HANA DB layer
• Avoid bringing all the data to the ABAP layer.
AMDP Guidelines
1.
AMDP classes will be
created using ABAP Development tool (ADT) only.
2. If it is an AMDP then must contain the interface tag as INTERFACE
“IF_AMDP_MARKER_HDB”.
3. Should always pass by value and AMDP won’t support pass by reference.
4. Method definition should as follows
METHODS: <Method Name>
IMPORTING:
VALUE (Input value) TYPE <InType>
EXPORTING:
VALUE (Output value) TYPE <OutType>
<Error_Message> = SELECT
‘E’ as MESSAGE_TYPE, “Set Message Type as Error
::SQL_ERROR_CODE as MESSAGE_CODE, “Pass Error code received to Message Code
::SQL_ERROR_MESSAGE as MESSAGE_TEXT “SQL error message to Message text
FROM dummy;
END;
Well below is the example for that in short and sweet manner.
https://community.sap.com/t5/technology-blog-posts-by-members/sap-abap-new-syntax/ba-p/13879225
1.2.5.3.
AMDP: Avoiding DELETE
1.2.5.4. CDS TABLE Function: Avoiding DELETE DUPICATES and pushing calculation to
Database Layer using by CDS TABLE functions.
We can get the unique values of LAND1 irrespective of customer number and name
ADBC – ABAP Database Connectivity
ADBC is an API for the Native SQL interface of the AS ABAP that is based on ABAP
Objects. With ADBC, we can do the following:
Access to entire SQL functionality of underlying DB system.
Dynamic creation and execution of native SQL statements via respective API methods.
Clean concept for multiple DB connections (connections are associated to connection
objects).
Exception handling – API method have well-defined exceptions that can be handled.
Native SQL can be used via EXEC SQL (and related) statements or the ABAP Objects
based ADBC (ABAP Database Connectivity) API.
Class CL_SQL_CONNECTION offers methods like Create, Update and Insert etc. to work
with the underlying database. It is suggested to use ADBC as it works faster than the open
SQL.
Usage of ADBC
of class CL_SQL_STATEMENT
of class CL_SQL_RESULT_SET
of class CL_SQL_RESULT_SET
of class CL_SQL_RESULT_SET
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:
DATA:
connection if necessary)
TRY.
Retrieve result:
Lo_result->set.param_table (lr_flight).
Lo_result->next_package ().
Close Result:
Lo_result->close ().
Handle exceptions:
ENDTRY.
Limitations:
2. No hashed or sorted tables as target and need to use standard table (probably with hashed
or sorted secondary key)
Client handling specify client explicitly in WHERE clauses, join conditions, etc.
Accessing correct database schema
Releasing DB resources (e g. result set)
Proper locking and commit handling -DB transaction t ABAP LUW
ABAP table buffers are bypassed
Syntax differences to Open SQL
1. New syntax
NB: There will be a short dump if you use an inline expression that references a non-existent record.
SAP says you should therefore assign a field symbol and check sy-subrc.
I. Definition
CONV dtype|#( … )
# = compiler must use the context to decide the type to convert to (implicit)
II. Example
Before 7.40
helper = text.
OR
I. Definition
OR
itab = VALUE #( ( ) ( 1 ) ( 2 ) ).
Structured line type (RANGES table):
DATA itab TYPE RANGE OF i.
I. Definition
II. Explanation
This effectively causes a loop at itab. For each loop the row read is assigned to a work area (wa) or
field-symbol(<fs>).
This wa or <fs> is local to the expression i.e. if declared in a subrourine the variable wa or <fs> is a
local variable of
Given:
Example 1
Before 7.40
IV. Example 2
Populate internal table GT_CITYS with the cities from GT_SHIPS where the route is R0001.
Before 7.40
Note: ls_ship does not appear to have been declared but it is declared implicitly.
V. FOR with THEN and UNTIL|WHILE
FOR i = … [THEN expr] UNTIL|WHILE log_exp
TYPES:
BEGIN OF ty_line,
col1 TYPE i,
col2 TYPE i,
col3 TYPE i,
END OF ty_line,
ty_tab TYPE STANDARD TABLE OF ty_line WITH EMPTY KEY.
Before 7.40
j = 1.
DO.
j = j + 10.
IF j > 40. EXIT. ENDIF.
APPEND INITIAL LINE TO gt_itab ASSIGNING <ls_tab>.
<ls_tab>–col1 = j.
<ls_tab>–col2 = j + 1.
<ls_tab>–col3 = j + 2.
ENDDO.
II. Note
While VALUE and NEW expressions can include FOR expressions, REDUCE must include at
least one FOR expression. You can use all kinds of FOR expressions in REDUCE:
Before 7.40
KEY.
gt_itab = VALUE #( FOR j = 1 WHILE j <= 10 ( j ) ).
Before 7.40
Using a class reference – works because “write” method returns reference to instance object
From 7.40 and onwards
output->display( ).
METHOD square. "IMPORTING root TYPE i METHOD square. "IMPORTING root TYPE i
"RETURNING VALUE(r) TYPE i. "RETURNING VALUE(r) TYPE i.
DATA square type i. TRY.
TRY. RETURN ipow( base = root exp = 2 ).
square = ipow( base = root exp = 2 ). CATCH cx_sy_arithmetic_error.
CATCH cx_sy_arithmetic_error. RETURN 0.
square = 0. ENDTRY.
ENDTRY.
ENDMETHOD.
r = square.
ENDMETHOD.
6. Data Types
New Data
Version Description
Type
8-byte integers with signs
Initial value: 0
INT8 Value range: -9,223,372,036,854,775,808
7.50 to +9,223,372,036,854,775,807
Output length: 20
(ABAP & DDIC)
Syntax
Description
Example
planet = earth.
planet = Nebula. "Syntax error: Field "NEBULA" is unknown
Description
Description
For the given source table(s) and filter criteria a structure of index numbers is returned.
These index numbers are in the required order to effectuate the requested sort. This
index structure can be used to create a new (combined) sorted table while leaving the
original table(s) unsorted.
Examples
Single Table
ITAB
CO CO CO CO
L1 L2 L3 L4
6 4 G I
1 7 D F
6 9 A B
2 4 H B
1 4 A H
4 3 I J
10 8 E E
2 1 E D
9 5 C G
1 1 G B
DATA(v_index) = cl_abap_itab_utilities=>virtual_sort(
im_virtual_source = VALUE #(( source = REF
#( itab )
components = VALUE #( ( name = 'col1' ) (
name = 'col2' )
) ) ) ).
"Result: v_index = (10, 5, 2, 8, 4, 6, 1, 3, 9,
7)
v_index = cl_abap_itab_utilities=>virtual_sort(
im_virtual_source = VALUE #(
( source = REF #( itab )
components = VALUE #(
( name = 'col3'
astext = abap_true
descending = abap_true )
( name = 'col4'
astext = abap_true
descending = abap_true ) )
) ) ).
"Result: v_index = (6, 4, 1, 10, 7, 8, 2, 9, 5, 3)
Two tables
For full example see class cl_demo_virtual_sort_combined.
ITAB1 ITAB2
COL1 COL2 COL1 COL2
0 0 X X
1 1 X X
1 1 Y Y
1 1 X Y
0 0 X X
1 0 Y Y
1 0 X Y
1 0 X Y
0 0 Y X
1 1 Y Y
v_index = cl_abap_itab_utilities=>virtual_sort(
im_virtual_source = VALUE #(
( source = REF #( itab1 )
components = VALUE #( ( name = 'col1' )
( name = 'col2' ) ) )
( source = REF #( itab2 )
components = VALUE #( ( name = 'col1'
astext = abap_true
descending = abap_true )
( name = 'col2'
astext = abap_true
descending = abap_true ) ) )
) ).
"Result: v_index = (9, 1, 5, 6, 7, 8, 3, 10, 4, 2)
9. Indicators (7.55)
Syntax
TYPES dtype TYPE struct WITH INDICATORS ind [{TYPE type}]. […AS
BITFIELD from 7.56]
UPDATE dbtab FROM TABLE itab INDICATORS [NOT] SET STRUCTURE set_ind.
Description
When used with “TYPES” it adds a component ind at the end of the structure struc the
same number of first-level components.
This can be used together with UPDATE dbtab to only update the components flagged
for update.
Example
DB table DEMO_UPDATE:
I COL COL COL COL
D 1 2 3 4
A 1 10 100 0
B 2 20 200 0
C 3 30 300 0
D 4 40 400 0
E 5 50 500 0
F 6 60 600 0
ind_tab = VALUE #(
( id = 'D' col2 = 7777 col_ind-col2 = abap_true )
( id = 'E' col3 = 8888 col_ind-col3 = abap_true )
( id = 'F' col4 = 9999 col_ind-col4 = abap_true ) ).
ind_tab:
ID COL1 COL2 COL3 COL4 COL_IND
D 0 7777 0 0 X
E 0 0 8888 0 X
F 0 0 0 9999 X
DB table DEMO_UPDATE:
I
COL1 COL2 COL3 COL4
D
A 1 10 100 0
B 2 20 200 0
C 3 30 300 0
D 4 7777 400 0
E 5 50 8888 0
F 6 60 600 9999
Example
Description
STEP can be used with LOOP, FOR, APPEND, DELETE, INSERT, VALUE and NEW.
For LOOP and FOR, if n is negative, then the loop starts at the last line of the table and
goes backwards with a step size of n.
Example
itab = VALUE #( ( 4 ) ( 3 ) ( 7 ) ( 11 ) ( 1 ) ( 5 ) ).
Syntax
Explanation
Where struc1 is the source structure and s1 is a component of the source structure.
When s1 is supplied the result of the expression (expr) is only assigned if s1 is initial.
Else s1 is assigned.
When s1 is not supplied then the result of the expression is always assigned regardless
of whether s1 is initial.
Example
"Filling structure
struc1 = VALUE #( id1 = 1 a = 'a' b = '' c = 2 d = '' e = 0 ).
struc2 = CORRESPONDING #(
struc1 MAPPING
id2 = id1
b = b DEFAULT 'ha' && 'llo'
c = c DEFAULT 1 + 5
d = d DEFAULT VALUE #( itab1[ 1 ]-d DEFAULT
'hi' )
z = DEFAULT 9.
struc2:
Component Value
ID2 1
a a
b hallo src b is initial
c 2 src c is not initial
itab1[1]-d invalid. Would shortdump without
d hi
DEFAULT
z 9 src e is initial