Initial commit

This commit is contained in:
Daniel Reger
2022-12-05 11:03:16 +01:00
commit 75587a904b
98 changed files with 27377 additions and 0 deletions

20
.abapgit.xml Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DATA>
<MASTER_LANGUAGE>E</MASTER_LANGUAGE>
<STARTING_FOLDER>/src/</STARTING_FOLDER>
<FOLDER_LOGIC>FULL</FOLDER_LOGIC>
<IGNORE>
<item>/.gitignore</item>
<item>/LICENSE</item>
<item>/README.md</item>
<item>/package.json</item>
<item>/.travis.yml</item>
<item>/.gitlab-ci.yml</item>
<item>/abaplint.json</item>
<item>/azure-pipelines.yml</item>
</IGNORE>
</DATA>
</asx:values>
</asx:abap>

31
.reuse/dep5 Normal file
View File

@@ -0,0 +1,31 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: abap-cheat-sheets
Upstream-Contact: SAP Open Source Program Office ospo@sap.com
Source: https://github.com/sap-samples/abap-cheat-sheets
Disclaimer: The code in this project may include calls to APIs (“API Calls”) of
SAP or third-party products or services developed outside of this project
(“External Products”).
“APIs” means application programming interfaces, as well as their respective
specifications and implementing code that allows software to communicate with
other software.
API Calls to External Products are not licensed under the open source license
that governs this project. The use of such API Calls and related External
Products are subject to applicable additional agreements with the relevant
provider of the External Products. In no event shall the open source license
that governs this project grant any rights in or to any External Products,or
alter, expand or supersede any terms of the applicable additional agreements.
If you have a valid license agreement with SAP for the use of a particular SAP
External Product, then you may make use of any API Calls included in this
projects code for that SAP External Product, subject to the terms of such
license agreement. If you do not have a valid license agreement for the use of
a particular SAP External Product, then you may only make use of any API Calls
in this project for that SAP External Product for your internal, non-productive
and non-commercial test and evaluation of such API Calls. Nothing herein grants
you any rights to use or access any SAP External Product, or provide any third
parties the right to use of access any SAP External Product, through API Calls.
Files: *
Copyright: 2022 SAP SE or an SAP affiliate company and abap-cheat-sheets contributors.
License: Apache-2.0

1463
01_Internal_Tables.md Normal file

File diff suppressed because it is too large Load Diff

669
02_Structures.md Normal file
View File

@@ -0,0 +1,669 @@
# Working with Structures
- [Working with Structures](#working-with-structures)
- [Structures ...](#structures-)
- [Creating Structures and Structured Types](#creating-structures-and-structured-types)
- [Variants of Structures](#variants-of-structures)
- [Working with Structures](#working-with-structures-1)
- [Accessing Components of Structures](#accessing-components-of-structures)
- [Filling Structures](#filling-structures)
- [Clearing Structures](#clearing-structures)
- [Structures in Use in the Context of Tables](#structures-in-use-in-the-context-of-tables)
- [Excursion: Including Structures](#excursion-including-structures)
- [More Information](#more-information)
- [Executable Example](#executable-example)
## Structures ...
- (or structured [data
objects](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_object_glosry.htm "Glossary Entry"))
are ABAP variables typed with [structured
types](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenstructured_type_glosry.htm "Glossary Entry").
- are [complex data
types](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencomplex_data_type_glosry.htm "Glossary Entry").
- are composed of a sequence of other data objects which are called
[components](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencomponent_glosry.htm "Glossary Entry").
- have components that can be of any type, that is, they can
themselves be, for example, structures or [internal
tables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninternal_table_glosry.htm "Glossary Entry").
- summarize different pieces of information, that is, data objects,
that belong together. A typical example is the following: an address
has several components like name, street, city, and so on.
- mostly serve as line types of internal tables and [database
tables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendatabase_table_glosry.htm "Glossary Entry").
- are often used to process data sequentially, such as the data stored
in the rows and columns of a database table.
- and structured types can typically be found in the [ABAP Dictionary
(DDIC)](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenabap_dictionary_glosry.htm "Glossary Entry"),
sometimes in [global
classes](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenglobal_class_glosry.htm "Glossary Entry");
or they can be defined locally in ABAP programs.
- Most of the structures that are worked with in ABAP programs may
be globally defined structures in the DDIC.
- Why? Apart from globally defined structures in the DDIC, each
database table or
[view](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenview_glosry.htm "Glossary Entry")
constitutes a structured type. When a database table etc. is
activated, a globally available structured type of the same name
is created, too. Hence, in an ABAP program, a database table's
name is typically used as type name to declare data objects, for
example, structures or internal tables.
- can be addressed as a whole. You can also address the individual
components of structures.
## Creating Structures and Structured Types
> **💡 Note**<br>
> This cheat sheet focuses on locally defined structures and structured types.
The typical syntactical elements are [`BEGIN OF ... END OF ...`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaptypes_struc.htm).
They are used in combination with
[`TYPES`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaptypes.htm)
to create a structured type and
[`DATA`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapdata.htm)
to create a structure.
**Creating structured types**
The structures' components are listed between `... BEGIN OF ...` and `... END OF ...`.
``` abap
TYPES: BEGIN OF struc_type,
         comp1 TYPE ...,
         comp2 TYPE ...,
         comp3 TYPE ...,
         ...,
       END OF struc_type.
```
Alternatively, you could go with the following syntax, however, a chained statement with the colon `:` above is preferable due to
better readability.
``` abap
TYPES BEGIN OF struc_type.
TYPES comp1 TYPE ... .
TYPES comp2 TYPE ... .
TYPES comp3 TYPE ... .
... .
TYPES END OF struc_type.
```
As mentioned above, the components of structures can be of any type.
They can be
[elementary](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenelementary_data_type_glosry.htm "Glossary Entry")
and also complex, that is, a structure component can be a structure or
internal table. Besides this, the components can be [reference
variables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenreference_variable_glosry.htm "Glossary Entry"),
too.
For the components, the additions
[`TYPE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapdata_simple.htm)
and
[`LIKE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapdata_referring.htm)
are possible.
> **💡 Note**<br>
> Setting default values with
[`VALUE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapdata_options.htm)
is - in contrast to the creation of structures using a `DATA`
statement as shown further down - not possible in this case.
``` abap
TYPES: BEGIN OF struc_type,
         comp1 TYPE i,                 "elementary type
         comp2 TYPE c LENGTH 5,         "elementary type
         comp3 TYPE local_structured_type,   "local structured type
         comp4 TYPE itab_type,         "internal table type
         comp5 TYPE ddic_type,         "DDIC type
         comp6 TYPE REF TO i,           "reference
         comp7 LIKE data_object,       "deriving type from a data object
         ...,
       END OF struc_type.
```
**Creating structures**
There are multiple ways to create structures in a program using a `DATA` statement:
- Creating a structure either based on a local type or a globally available type from the DDIC:
``` abap
DATA ls_from_local TYPE struc_type,
     ls_from_global TYPE ddic_type.
```
- Creating a structure by directly specifying the components using `... BEGIN OF ... END OF ...`. The syntax is similar to the `TYPES` statement. Here, default values can be set with
`VALUE`.
``` abap
DATA: BEGIN OF struc,
        comp1 TYPE ...,
        comp2 TYPE ... VALUE ...,
        comp3 TYPE i VALUE 99,
        comp4 TYPE i VALUE IS INITIAL,
        comp5 TYPE local_structured_type,
        ...,
      END OF struc.
```
Alternatively and similar to the `TYPES` statement, you
could use the following syntax, however, a chained statement with the colon `:` as above is preferable due to better
readability.
``` abap
DATA BEGIN OF struc.
DATA comp1 TYPE ... .
DATA comp2 TYPE ... VALUE ... .
... .
DATA END OF struc.
```
- Creating a structure by referring to a local structured data object using `LIKE` or to an internal table using `LIKE LINE OF`.
``` abap
DATA struc1 LIKE other_struc.
DATA struc2 LIKE LINE OF itab.
```
- Creating a structure by inline declaration, e. g. using `DATA( ... )`.
``` abap
"Type is derived from the right-hand structure;
"the content of struc is assigned, too.
DATA(struc1) = struc.
"Using the VALUE operator; structured type is specified before the
"first parenthesis; component values can be assigned, too
DATA(struc2) = VALUE struc_type( comp1 = ... ).
"It is particularly handy for declaring the structure where you actually need it
"without prior extra declaration of the structure in various contexts;
"e. g. SELECT or LOOP AT statements; structured types are automatically
"derived from the context
SELECT SINGLE *
FROM zdemo_abap_fli
WHERE carrid = 'LH'
INTO @DATA(struc3).
LOOP AT itab INTO DATA(wa).
  ...
ENDLOOP.
```
## Variants of Structures
Depending on the component type, the structure can be a [flat
structure](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenflat_structure_glosry.htm "Glossary Entry"),
a [nested
structure](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abennested_structure_glosry.htm "Glossary Entry"),
or a [deep
structure](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendeep_structure_glosry.htm "Glossary Entry").
**Flat structure**
Flat structures contain only elementary types that have a fixed length, that is, there are no internal tables, reference types or strings as components:
``` abap
DATA: BEGIN OF structure,
        comp1 TYPE i,
        comp2 TYPE c LENGTH 15,
        comp3 TYPE p LENGTH 8 DECIMALS 2,
        ...,
      END OF structure.
```
> **💡 Note**<br>
> Nesting does not play a role in this context. Even a nested structure is flat unless a substructure contains a deep component.
**Nested structure**
At least one component of a structure is a
[substructure](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensubstructure_glosry.htm "Glossary Entry"),
that is, it refers to another structure. The following example has
multiple substructures.
``` abap
DATA: BEGIN OF address_n,
        BEGIN OF name,
          title   TYPE string VALUE `Mr.`,
          prename TYPE string VALUE `Duncan`,
          surname TYPE string VALUE `Pea`,
        END OF name,
        BEGIN OF street,
          name   TYPE string VALUE `Vegetable Lane`,
          number TYPE string VALUE `11`,
        END OF street,
        BEGIN OF city,
          zipcode TYPE string VALUE `349875`,
          name    TYPE string VALUE `Botanica`,
        END OF city,
      END OF address_n.
```
**Deep structure**
A deep structure contains at least one internal table, reference type, or string as a component.
``` abap
DATA: BEGIN OF address_d,
        name    TYPE string VALUE `Mr. Duncan Pea`,
        street  TYPE string VALUE `Vegetable Lane 11`,
        city    TYPE string VALUE `349875 Botanica`,
        details TYPE TABLE OF some_table WITH EMPTY KEY,
      END OF address_d.
```
Despite the fact that the following structure looks fairly simple, it is not to be considered a flat structure but a deep structure since it contains strings.
``` abap
DATA: BEGIN OF address,
        name   TYPE string VALUE `Mr. Duncan Pea`,
        street TYPE string VALUE `Vegetable Lane 11`,
        city   TYPE string VALUE `349875 Botanica`,
      END OF address.
```
## Working with Structures
### Accessing Components of Structures
The structure as a whole and also the individual components can be
addressed. To address the components, you use the [structure component
selector](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenstructure_component_sel_glosry.htm "Glossary Entry")
`-`:
``` abap
structure-comp1 ...
address-name ...
```
Nested components can be addressed via chaining:
```
structure-substructure-comp1 ...
address_n-name-title ...
```
> **✔️ Hints**<br>
>- You can refer to structure components when creating new data types and data objects:
> ``` abap
> TYPES: lty_1 TYPE structured_type-comp1,
>        lty_2 LIKE structure-comp1.
>
> DATA: lv_1 TYPE structured_type-comp1,
>       lv_2 LIKE structure-comp1.
> ```
>- ADT and the ABAP Editor provide code completion for structure components after the component selector.
>- When declaring a variable with reference to a structured data object, the object component selector `->` can be used:
`...dref->comp ...` (apart from the needlessly longer syntax `... dref->*-comp ...`).
### Filling Structures
Filling structure components using the component selector.
``` abap
address-name   = `Mr. Duncan Pea`.
address-street = `Vegetable Lane 11`.
address-city   = `349875 Botanica`.
```
Filling structure components using the
[`VALUE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_value.htm)
operator. Value assignments by addressing the structure
components individually can be very bulky. Hence, the use of the
`VALUE` operator is very handy for the value assignment,
especially for filling structure components at [operand position](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenoperand_position_glosry.htm "Glossary Entry").
In the example below, the `#` sign is used before the
parentheses which means that the type of the operand can be implicitly
derived. This is not the case for the example further down in which a
new structure is [declared inline](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_inline.htm).
Hence, the type must be explicitly specified before the parentheses.
Note that components that are not specified and assigned a value remain
initial.
``` abap
address = VALUE #( name   = `Mr. Duncan Pea`
                   street = `Vegetable Lane 11`.
                   city   = `349875 Botanica` ).
```
Using the `VALUE` operator and inline declarations, structures can be created and filled in one go.
``` abap
TYPES address_type LIKE address.
DATA(add2) = VALUE address_type( name   = `Mrs. Jane Pea`
                                 street = `Vegetable Lane 11`.
                                 city   = `349875 Botanica` ).
```
Copying the content of a structure to another one that has the same type. For value assignments, generally
bear in mind that there are special [conversion](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_struc.htm)
and [comparison rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenlogexp_rules_operands_struc.htm)
that apply to assignments involving structures..
``` abap
address = add2.
"When creating a new structure by inline declaration, the type of
"the right-hand structure is derived and the content is assigned.
DATA(add3) = add2.
```
Copying content of a structure to another one that has a different type. You can use statements with
[`MOVE-CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove-corresponding.htm)
and the
[`CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expr_corresponding.htm)
operator. Both are used to assign identically named components of
structures to each other. This syntax also works for structures that
have the same type.
Note the rules mentioned above and consider the result of the value
assignment when using either of the two options with
`MOVE-CORRESPONDING` and the `CORRESPONDING` operator.
See more information and syntax variants in the ABAP Keyword
Documentation:
[`MOVE-CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencorresponding_constr_arg_type.htm)
and
[`CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencorresponding_constr_arg_type.htm).
In the examples below, the focus is only on flat structures.
``` abap
"Moves identically named components; content in other components
"of the targets structure are kept.
MOVE-CORRESPONDING struc TO diff_struc.
"Initializes target structure; moves identically named components
diff_struc = CORRESPONDING #( struc ).
"Same effect as the first MOVE-CORRESPONDING statement;
"addition BASE keeps existing content
diff_struc = CORRESPONDING #( BASE ( diff_struc ) struc ).
"MAPPING addition: Specifying components of a source structure that are
"assigned to the components of a target structure in mapping
"relationships.
diff_struc = CORRESPONDING #( BASE ( diff_struc )
                           struc MAPPING comp1 = compa ).
"EXCEPT addition: Excluding components from the assignment.
diff_struc = CORRESPONDING #( BASE ( diff_struc )
                           struc EXCEPT comp1 ).
```
**Excursion**: Copying content of a deep structure to another deep structure that has a different type. You can use statements with
[`MOVE-CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove-corresponding.htm)
and the
[`CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expr_corresponding.htm)
operator here, too. However, in the context of deep structures, more syntax variants are available. The focus of the following examples is on internal tables as structure components. See the executable example for visualizing the effect.
> **💡 Note**<br>
> Bear in mind that there are special conversion and comparison rules that apply to assignments involving structures and that affect the value assignments in the internal table components.
``` abap
"Nonidentical elementary component types are kept in target
"structure which is true for the below MOVE-CORRESPONDING statements;
"existing internal table content is replaced by content of
"the source table irrespective of identically named components
MOVE-CORRESPONDING deep_struc TO diff_deep_struc.
"Existing internal table content is replaced but the value
"assignment happens for identically named components only.
MOVE-CORRESPONDING deep_struc TO diff_deep_struc
     EXPANDING NESTED TABLES.
"Existing internal table content is kept; table content of the source
"structure are added but the value assignment happens like the first
"MOVE-CORRESPONDING statement without further syntax additions.
MOVE-CORRESPONDING deep_struc TO diff_deep_struc
     KEEPING TARGET LINES.
"Existing internal table content is kept; table content of the source
"structure are added; the value assignment happens like the statement
"MOVE-CORRESPONDING ... EXPANDING NESTED TABLES.
MOVE-CORRESPONDING deep_struc TO diff_deep_struc
    EXPANDING NESTED TABLES KEEPING TARGET LINES.
"Target structure is initialized; the value assignment for an internal
"table happens irrespective of identically named components.
diff_deep_struc = CORRESPONDING #( deep_struc ).
"Target structure is initialized; the value assignment for an internal
"table happens for identically named components only.
diff_deep_struc = CORRESPONDING #( DEEP deep_struc ).
"Nonidentical elementary component types are kept in target structure;
"internal table content is replaced; there, the value assignment
"happens like using the CORRESPONDING operator without addition.
diff_deep_struc = CORRESPONDING #( BASE ( diff_struc ) deep_struc ).
"Nonidentical elementary component types are kept in target structure;
"internal table content is replaced; there, the value assignment
"happens like using the CORRESPONDING operator with the addition DEEP.
diff_deep_struc = CORRESPONDING #( DEEP BASE ( diff_struc ) deep_struc ).
"Nonidentical elementary component types are kept in target structure;
"internal table content is kept, too, and table content of the
"source structure are added; there, the value assignment
"happens like using the CORRESPONDING operator without addition.
diff_deep_struc = CORRESPONDING #( APPENDING BASE ( diff_struc ) deep_struc ).
"Nonidentical elementary component types are kept in target structure;
"internal table content is kept, too, and table content of the
"source structure are added; there, the value assignment
"happens like using the CORRESPONDING operator with the addition DEEP.
diff_deep_struc = CORRESPONDING #( DEEP APPENDING BASE ( diff_struc ) deep_struc ).
```
                                  
## Clearing Structures
You can reset individual components to their initial value and clear the
complete structure using the keyword
[`CLEAR`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapclear.htm).
```
CLEAR structure-component.
CLEAR structure.
```
## Structures in Use in the Context of Tables
Structures are primarily used to process data from tables. In this
context, structures often assume the role of a [work
area](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenwork_area_glosry.htm "Glossary Entry").
**Reading a line from a database table into a structure that has a matching type**. Note that, since database tables are flat, the
target structure must also be flat. In the example below, the addition
[`SINGLE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapselect_single.htm)
reads only a single row into the structure. The first entry that is
found according to the `WHERE` condition is returned.
> **💡 Note**<br>
> See more details on
[`SELECT`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapselect.htm)
statements in the ABAP Keyword Documentation. The ABAP cheat sheet [ABAP
SQL: Working with Persisted Data in Database
Tables](03_ABAP_SQL.md)
also provides information and more code snippets when using
`SELECT` statements.
``` abap
"Creating a structure with a matching type
DATA ls_fli1 TYPE zdemo_abap_fli.
SELECT SINGLE FROM zdemo_abap_fli
    FIELDS *
    WHERE carrid = 'LH'
    INTO @ls_fli1.
"Target structure declared inline
SELECT SINGLE FROM zdemo_abap_fli
    FIELDS *
    WHERE carrid = 'LH'
    INTO @DATA(ls_fli2).
```
**Reading a line from a database table into a structure that has a different type**.
``` abap
SELECT SINGLE FROM zdemo_abap_fli
    FIELDS *
    WHERE carrid = 'AA'
    INTO CORRESPONDING FIELDS OF @ls_fli_diff.
```
**Reading a line from an internal table into a structure** ...
... using a `SELECT` statement. Note the specified alias name and that ABAP variables like internal tables must be escaped using `@`. The addition `INTO CORRESPONDING FIELDS OF` also applies here.
``` abap
SELECT SINGLE FROM @itab AS itab_alias
    FIELDS *
    WHERE ...
    INTO @DATA(ls_struc).
    "INTO CORRESPONDING FIELDS OF @struc.
```
... using a `READ TABLE` statement. The code snippet below shows the reading of one line
into a [work
area](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenwork_area_glosry.htm "Glossary Entry"),
[field
symbol](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfield_symbol_glosry.htm "Glossary Entry")
and a [data reference
variable](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_variable_glosry.htm "Glossary Entry"),
all representing structured data objects and declared inline below. In
the example below, the reading of a line is based on the line number by
specifying `INDEX`. See the section `Determining the target area` in the cheat sheet [Working with Internal Tables](01_Internal_Tables.md#) for more details.
``` abap
READ TABLE itab INTO DATA(wa) INDEX 1.
READ TABLE itab ASSIGNING FIELD-SYMBOL(<fs>) INDEX 2.
READ TABLE itab REFERENCE INTO DATA(dref) INDEX 3.
```
... using a [table
expression](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentable_expression_glosry.htm "Glossary Entry").
The code snippet below shows the reading of one line into a structure
that is declared inline. The index is specified in square brackets.
``` abap
DATA(ls_table_exp) = itab[ 3 ].
```
> **💡 Note**<br>
> See more syntax variants and code snippets for `READ TABLE` statements and statements with table expressions in the ABAP cheat sheet `Working with Internal Tables`.
**Sequentially reading a line from** ...
... a database table into a structure. A `SELECT` loop can be specified by using the syntax `SELECT ... ENDSELECT.`.
In the simple example below, the line that is found and returned in a structure, which is declared inline, can be further processed.
A `SELECT` loop might also have an internal table as data source.
``` abap
SELECT FROM zdemo_abap_fli
    FIELDS *
    WHERE carrid = 'AZ'
    INTO @DATA(ls_sel_loop).
      IF sy-subrc = 0.
        ...
      ENDIF.
ENDSELECT.
```
... an internal table into a structure using a [`LOOP AT`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_variants.htm) statement. There are numerous options for specifying the condition on which the loop is based. The example below covers the option of reading all lines sequentially into a field symbol which is declared inline. When using a field symbol, components can be directly modified, for example.
``` abap
LOOP AT itab ASSIGNING FIELD-SYMBOL(<fs>).
   <fs>-comp1 = ...
   ...
ENDLOOP.
```
**Inserting an individual row from a structure into a database table** using ABAP SQL statements with
[`INSERT`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapinsert_dbtab.htm). The statements below can be considered as alternatives. The third statement demonstrates that the structure might also be created and filled directly instead of inserting a line from an existing structure. Note that a line with a certain key should not be inserted into the database table if a line with the same key already exists there.
``` abap
INSERT INTO dbtab VALUES @structure.
INSERT dbtab FROM @structure.
INSERT dbtab FROM @( VALUE #( comp1 = ... comp2 = ... ) ).
```
**Updating an individual row from a structure in a database table** using ABAP SQL statements with [`UPDATE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapupdate.htm). Note that with this syntax, the whole line and all components are changed.
``` abap
UPDATE dbtab FROM @structure.
UPDATE dbtab FROM @( VALUE #( comp1 = ... comp2 = ... ) ).
```
If you want to update a database table row from a structure by specifying components to be changed without overwriting other components, you might use the following way. First, read the intended line from the database table into a structure. Then, use the `VALUE` operator with the addition `BASE` and specify the components to be changed.
``` abap
SELECT SINGLE *
FROM dbtab
WHERE ...
INTO @DATA(wa).
UPDATE dbtab FROM @( VALUE #( BASE wa comp2 = ... comp4 = ... ) ).
```
**Updating or creating an individual row in a database table from a structure** using ABAP SQL statements with
[`MODIFY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmodify_dbtab.htm). If a line in the database table already exists with the same keys as specified in the structure, the line is updated. If a line does not exist with the keys specified in the structure, a new line is created in the database table.
``` abap
MODIFY dbtab FROM @structure.
MODIFY dbtab FROM @( VALUE #( comp1 = ... comp2 = ... ) ).
```
**Adding rows to and updating individual rows in an internal table from a structure** using statements with `INSERT`,
`APPEND`, and `MODIFY`. Note that all statements, including `INSERT` and `MODIFY`, are ABAP statements in this context, not ABAP SQL statements.
Both `INSERT` and `APPEND` add one line (or more) to an internal table. While `APPEND` adds at the bottom of the
internal table, `INSERT` can be used to add lines at a specific position in tables. If you go without specifying the position, then the lines are added at the bottom of the table, too. However, when using `INSERT`, `sy-tabix` is not set as compared to `APPEND`.
`MODIFY` changes the content of an internal table entry.
Statements using the `VALUE` operator for directly creating and filling the structures are possible, too. For more information and code
snippets, refer to the cheat sheet [Working with Internal Tables](01_Internal_Tables.md#).
``` abap
INSERT structure INTO TABLE itab.
APPEND structure TO itab.
MODIFY TABLE itab FROM structure.
```
### Excursion: Including Structures
Although their use is not recommended according to the ABAP programming
guidelines, you might stumble upon statements with [`INCLUDE TYPE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapinclude_type.htm)
and [`INCLUDE STRUCTURE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapinclude_type.htm)
in the context of local structures. Structured data objects and types
that are created with `... BEGIN OF... END OF ...` can
include the said syntax to integrate components of another structure, no
matter if it is a locally defined or global structure, without the need
to create substructures. `INCLUDE TYPE` can be used to include a
structured type. `INCLUDE STRUCTURE` can be used to include a
structure.
> **💡 Note**<br>
> - They are not additions of `... BEGIN OF ... END OF ...` but individual ABAP statements.
> - If a chained statement is used for the structure declaration with the colon, the inclusion of other structures with these statements interrupts the chained statement, that is, the components of the included structures are included as direct components of the [superstructure](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensuperstructure_glosry.htm "Glossary Entry").
>- Using the optional addition `AS` and the specification of a name, the included components can be addressed by this common name as if the components were actually components of a substructure.
>- Using the optional addition `RENAMING WITH SUFFIX` and the specification of a name, the included components are given a suffix name to avoid naming conflicts with other components.
The example below shows how structured types and data objects are included in another structure. First, three structured types as well as a structured data object based on one of those types are created. Then, the types and the structure are included in the structured type `address_type`. The demonstration class visualizes a structure that includes other structures this way.
``` abap
TYPES: BEGIN OF name_type,
        title   TYPE string,
        prename TYPE string,
        surname TYPE string,
      END OF name_type,
      BEGIN OF street_type,
        name   TYPE string,
        number TYPE string,
      END OF street_type,
      BEGIN OF city_type,
        zipcode TYPE string,
        name    TYPE string,
      END OF city_type.
DATA city_struc TYPE city_type.
TYPES BEGIN OF address_type.
      INCLUDE TYPE name_type AS name.
      INCLUDE TYPE street_type AS street RENAMING WITH SUFFIX _street.
      INCLUDE STRUCTURE city_struc AS city RENAMING WITH SUFFIX _city.
TYPES END OF address_type.
```
## More Information
See the topic
[Structures (F1 docu for standard ABAP)](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abendata_objects_structure.htm)
for more information.
## Executable Example
[zcl_demo_abap_structures](./src/zcl_demo_abap_structures.clas.abap)
Note the steps outlined [here](README.md#🎬-getting-started-with-the-examples) about how to import and run the code.

1499
03_ABAP_SQL.md Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,899 @@
<a name="top"></a>
# Working with Constructor Expressions
- [Working with Constructor Expressions](#working-with-constructor-expressions)
- [Introduction](#introduction)
- [`VALUE`](#value)
- [`CORRESPONDING`](#corresponding)
- [`NEW`](#new)
- [`CONV`](#conv)
- [`EXACT`](#exact)
- [`REF`](#ref)
- [`CAST`](#cast)
- [`COND`](#cond)
- [`SWITCH`](#switch)
- [`FILTER`](#filter)
- [`REDUCE`](#reduce)
- [Iteration Expressions with `FOR`](#iteration-expressions-with-for)
- [`LET Expressions`](#let-expressions)
- [Executable Example](#executable-example)
## Introduction
- [Constructor
expressions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_glosry.htm "Glossary Entry")
include a [constructor
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_operator_glosry.htm "Glossary Entry")
followed by the specification of a [data
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_type_glosry.htm "Glossary Entry")
or [object
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenobject_type_glosry.htm "Glossary Entry")
(or a `#` character that stands for such a type) and
specific parameters specified within parentheses. Example using the
`VALUE` operator:
``` abap
... VALUE string( ... ) ...
... VALUE #( ... ) ...
```
- As the name implies, these expressions construct results of a
specific type and their content. Either the type is specified
explicitly before the first parenthesis or the said `#`
character can be specified if the type can be derived implicitly
from the [operand
position](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenoperand_position_glosry.htm "Glossary Entry").
The `#` character symbolizes the [operand
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenoperand_type_glosry.htm "Glossary Entry").
If no type can be derived from the operand position, for some
constructor operators, the type can also be derived from the
arguments in the parentheses.
- Why use them? Constructor expressions can make your code leaner and
more readable since you can achieve the same with fewer statements.
- Apart from the concept of deriving types from the context, another
concept is very handy particularly in this context: [Inline
declaration](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninline_declaration_glosry.htm "Glossary Entry").
- This means that you can declare a variable using
`DATA(var)` (or an immutable variable
[`FINAL(var)`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfinal_inline.htm))
as an operand in the current [write
position](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenwrite_position_glosry.htm "Glossary Entry").
In doing so, such a variable declared inline can be given the
appropriate type and result of the constructor expression in one
go: `DATA(dec) = VALUE decfloat34( '1.23' )`.
> **✔️ Hint**<br>
> The construction of a result, i. e. a target [data
object](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_object_glosry.htm "Glossary Entry"),
implies that the data object is initialized. However, for some
constructor operators, there is an addition with which the
initialization can be avoided.
<p align="right">(<a href="#top">back to top</a>)</p>
## `VALUE`
- Expressions with the
[`VALUE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_value.htm)
operator construct a result in place based on a data type.
- This result can be initial values for any non-generic data types,
structures or internal tables.
> **💡 Note**<br>
> Elementary data types and reference types cannot be
explicitly specified for the construction of values here.
- Regarding the type specifications before and parameters within the
parentheses:
- No parameter specified within the parentheses: The return value
is set to its type-specific initial value. This is possible for
any non-generic data types. See more information
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenvalue_constructor_params_init.htm).
- Structured and internal table type before the parentheses or
`#` stands for such types: Individual components of
structures can be specified as named arguments while each
component of the return value can be assigned a data object that
has the same data type as the component, or whose data type can
be converted to this data type. See more information
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenvalue_constructor_params_struc.htm).
To construct internal tables, you have multiple options, for
example, you can add individual table lines using an inner pair
of parentheses. More syntax options, for example, using the
additions `BASE` and `FOR` are possible, too.
See more information
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenvalue_constructor_params_itab.htm).
Example: Structure
``` abap
"Creating a structured type
TYPES: BEGIN OF struc_type,
          a   TYPE i,
          b   TYPE c LENGTH 3,
        END OF struc_type.
DATA struc TYPE struc_type. "Structured data object
struc = VALUE #( a = 1 b = 'aaa' ). "Deriving the type using #
```
As mentioned above, the concept of [inline
declarations](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninline_declarations.htm)
enters the picture here, which simplifies ABAP programming. You can
construct a new data object (for example, using `DATA(...)`),
provide the desired type with the constructor expression and assign
values in one go.
``` abap
"Explicit type specification needed
DATA(structure) = VALUE struc_type( a = 2 b = 'bbb' ).
```
Note that initial values can be created by omitting the specification of
components or by providing no content within the parentheses.
``` abap
"Component b not specified, b remains initial
struc = VALUE #( a = 2 ).
"Explicit setting of initial value for a component
struc = VALUE #( a = 1 b = value #( ) ).
"The whole structure is initial
struc = VALUE #( ).
"Creating initial values for an elementary data type
DATA num1 TYPE i.
num1 = VALUE #( ).
"Inline declaration
DATA(num2) = VALUE i( ).
```
Regarding internal tables, the line specifications are enclosed in an
inner pair of parentheses `( ... )`. In the following examples,
three lines are added to a table.
``` abap
"Creating an internal table type and an internal table
TYPES tab_type TYPE TABLE OF struc_type WITH EMPTY KEY.
DATA itab TYPE tab_type.
"Filling the internal table using the VALUE operator with #
itab = VALUE #( ( a = 1 b = 'aaa' )
                ( a = 2 b = 'bbb' )
                ( a = 3 b = 'ccc' ) ).
"Internal table declared inline, explicit type specification
DATA(itab2) = VALUE tab_type( ( a = 1 b = 'aaa' )
                              ( a = 2 b = 'bbb' )
                              ( a = 3 b = 'ccc' ) ).
"Unstructured line types work without component names.
"Here, the internal table type is a string table.
DATA(itab3) = VALUE string_table( ( `abc` ) ( `def` ) ( `ghi` ) ).
```
In case of
[deep](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendeep_structure_glosry.htm "Glossary Entry")
and [nested
structures](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abennested_structure_glosry.htm "Glossary Entry")
or [deep
tables](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abendeep_table_glosry.htm "Glossary Entry"),
the use of `VALUE` expressions is handy. The following example
demonstrates a nested structure.
``` abap
"Creating a nested structure
DATA: BEGIN OF nested_struc,
        a TYPE i,
        BEGIN OF struct,
          b TYPE i,
          c TYPE c LENGTH 3,
        END OF struct,
      END OF nested_struc.
"Filling the deep structure
nested_struc = VALUE #( a = 1 struct = VALUE #( b = 2 c = 'abc' ) ).
```
`BASE` addition: A constructor expression without the
`BASE` addition initializes the target variable. Hence, you can
use the addition if you do not want to construct a structure or internal
table from scratch but keep existing content.
``` abap
"Filling structure
struc = VALUE #( a = 1 b = 'aaa' ).
"struc is not initialized, only component b is modified, value of a is kept
struc = VALUE #( BASE struc b = 'bbb' ).
"Filling internal table with two lines
itab = VALUE #( ( a = 1 b = 'aaa' )
                ( a = 2 b = 'bbb' ) ).
"Two more lines are added instead of initializing the internal table
itab = VALUE #( BASE itab
                ( a = 3 b = 'ccc' )
                ( a = 4 b = 'ddd' ) ).
```
`LINES OF` addition: All or some lines of another table can be included in the target internal table (provided that they have
appropriate line types):
``` abap
itab = VALUE #( ( a = 1 b = 'aaa' )
                ( a = 2 b = 'bbb' )
                ( LINES OF itab2 ) "All lines of itab2
                ( LINES OF itab3 FROM 2 TO 5 ) ). "Specific lines of itab3
```
Using the inline construction of structures and internal tables, you can
avoid the declaration of extra variables in many contexts, for example,
ABAP statements like
[`MODIFY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmodify_itab.htm)
for modifying internal tables or [ABAP
SQL](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenabap_sql_glosry.htm "Glossary Entry")
statements like
[`MODIFY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmodify_dbtab.htm)
(which is not to be confused with the ABAP statement having the same
name) for modifying database tables.
Examples:
``` abap
"ABAP statements
"Modifiying individual internal table entries based on a structure created inline
"Modifying a table line
MODIFY TABLE some_itab FROM VALUE #( a = 1 ... ).
"Inserting a table line
INSERT VALUE #( a = 2 ... ) INTO TABLE some_itab.
"Deleting a table line
DELETE TABLE some_itab FROM VALUE #( a = 3 ).
"ABAP SQL statement
"Modifying multiple database table entries based on an internal table
"constructed inline within a host expression
MODIFY zdemo_abap_carr FROM TABLE @( VALUE #(
( carrid = 'XY'
carrname = 'XY Airlines'
currcode = 'USD'
url =  'some_url' )
( carrid = 'ZZ'
carrname = 'ZZ Airways'
currcode = 'EUR'
url =  'some_url' ) ) ).
```
> **💡 Note**<br>
> Some of the additions and concepts mentioned here are
also valid for other constructor expressions further down but not
necessarily mentioned explicitly. See the details on the syntactical
options of the constructor operators in the ABAP Keyword Documentation.
<p align="right">(<a href="#top">back to top</a>)</p>
## `CORRESPONDING`
- Expressions with the
[`CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expr_corresponding.htm)
operator construct structures and internal tables based on a data
type (i. e. a [table
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentable_type_glosry.htm "Glossary Entry")
or [structured
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenstructured_type_glosry.htm "Glossary Entry")).
- The components or columns of the target data object are filled using
assignments of the parameters specified within the parentheses.
- The assignments are made using identical names or based on [mapping
relationships](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencorresponding_constr_mapping.htm)
- Note: Pay attention to the [assignment and conversion
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_rules.htm)
to avoid errors when using the operator. Consider, for example, the
impact of assigning the values of identically named fields having
different types (e. g. one field is of type `c` and another
field is of type `string`).
The following table includes a selection of various possible additions to
this constructor operator. There are more variants available like the
addition `EXACT`, using a lookup table, the option of discarding
duplicates or
[RAP](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrap_glosry.htm "Glossary Entry")-specific
variants that are not part of this cheat sheet. Find the details in
[this
topic](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expr_corresponding.htm).
| Addition | Details |
|---|---|
| `BASE` | Keeps original values. Unlike, for example, the operator `VALUE`, a pair of parentheses must be set around `BASE`. |
| `MAPPING` | Enables the mapping of component names, i. e. a component of a source structure or source table can be assigned to a differently named component of a target structure or target table (e. g. `MAPPING c1 = c2`). |
| `EXCEPT` | You can specify components that should not be assigned content in the target data object. They remain initial. In doing so, you exclude identically named components in the source and target object that are not compatible or convertible from the assignment to avoid syntax errors or runtime errors. |
| `DEEP` | Relevant for deep tabular components. They are resolved at every hierarchy level and identically named components are assigned line by line. |
| `[DEEP] APPENDING` | Relevant for (deep) tabular components. It ensures that the nested target tables are not deleted. The effect without `DEEP` is that lines of the nested source table are added using `CORRESPONDING` without addition. The effect with `DEEP` is that lines of the nested source table are added using `CORRESPONDING` with the addition `DEEP`. |
See the executable example for demonstrating the effect of the variants:
``` abap
"Assignment of a structure/internal table to another one having a different type
struc2 = CORRESPONDING #( struc1 ).
tab2 = CORRESPONDING #( tab1 ).
"BASE keeps original content, does not initialize the target
struc2 = CORRESPONDING #( BASE ( struc2 ) struc1 ).
tab2 = CORRESPONDING #( BASE ( tab2 ) tab1 ).
"MAPPING/EXACT are used for mapping/excluding components in the assignment
struc2 = CORRESPONDING #( struc1 MAPPING comp1 = comp2 ).
tab2 = CORRESPONDING #( tab1 EXCEPT comp1 ).
"Complex assignments with deep components using further additions
st_deep2 = CORRESPONDING #( DEEP st_deep1 ).
st_deep2 = CORRESPONDING #( DEEP BASE ( st_deep2 ) st_deep1 ).
st_deep2 = CORRESPONDING #( APPENDING ( st_deep2 ) st_deep1 ).
st_deep2 = CORRESPONDING #( DEEP APPENDING ( st_deep2 ) st_deep1 ).
```
> **✔️ Hint**<br>
> `CORRESPONDING` operator versus
[`MOVE-CORRESPONDING`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove-corresponding.htm):
Although the functionality is the same, note that, as the name implies,
constructor operators construct and - without the addition
`BASE` - target objects are initialized. Hence, the following
two statements are not the same:
>``` abap
>struc2 = CORRESPONDING #( struc1 ).
>
>"Not matching components are not initialized
>MOVE-CORRESPONDING struc1 TO struc2.
>```
<p align="right">(<a href="#top">back to top</a>)</p>
## `NEW`
- Using the instance operator
[`NEW`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_new.htm),
you can create [anonymous data
objects](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenanonymous_data_object_glosry.htm "Glossary Entry")
or
[instances](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninstance_glosry.htm "Glossary Entry")
of a class and also assign values to the new object. As a result,
you get a [reference
variable](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenreference_variable_glosry.htm "Glossary Entry")
that points to the created object. In doing so, the operator
basically replaces [CREATE
DATA](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcreate_data.htm)
and [CREATE
OBJECT](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcreate_object.htm).
- For the type specification preceding the parentheses, you can use
- non-generic data types which creates a [data reference
variable](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_variable_glosry.htm "Glossary Entry")
pointing to the anonymous data object.
- classes which creates objects of these classes. The result is a
[object reference
variable](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenobject_refer_variable_glosry.htm "Glossary Entry")
pointing to an object.
- Regarding the created object reference variables, you can use the
[object component
selector](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenobject_component_select_glosry.htm "Glossary Entry")
`->` in certain contexts to ...
- point to a class attribute: `... NEW class( ... )->attr`
- introduce
[standalone](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcall_method_static_short.htm)
and
[functional](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcall_method_functional.htm)
method calls, including [chained method
calls](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenchained_method_call_glosry.htm "Glossary Entry")
which is a big advantage because you do not need to declare an
extra variable: `... NEW class( ... )->meth( ... ) ...`
- Regarding the type specifications before and parameters within the
parentheses:
- No parameter specified within the parentheses: An anonymous data
object retains its type-specific initial value. In case of
classes, no parameter specification means that no values are
passed to the instance constructor of an object. However, in
case of mandatory [input
parameters](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninput_parameter_glosry.htm "Glossary Entry"),
the parameters must be specified.
- Single parameter specified: If the type specified before the
parentheses is a non-generic elementary, structured, table, or a
reference type (or such a type can be derived using
`#`), a single data object can be specified as an
unnamed argument. Note the [assignment
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_rules.htm)
regarding the value assignments within the parentheses and that
a constructor expression itself can be specified there.
- Structures and internal tables specified: If the type specified
before the parentheses is a structured data type or `#`
stands for it, you can specify the individual components as
named arguments (`comp1 = 1 comp2 = 2 ...`; see more
information
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abennew_constructor_params_struct.htm)).
For the construction of anonymous internal tables, multiple
options are available. Among them, there is the use of
`LET` and `FOR` expressions and others. See more
details
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abennew_constructor_params_itab.htm).
- Classes: As mentioned, non-optional input parameters of the
instance constructor of the instantiated class must be filled.
No parameters are passed for a class without an explicit
instance constructor. See more information:
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abennew_constructor_params_class.htm).
Examples:
``` abap
"Data references
"Declaring data reference variables
DATA dref1 TYPE REF TO i.    "Complete type
DATA dref2 TYPE REF TO data. "Generic type
"Creating anonymous data objects
"Here, no parameters are specified within the parentheses meaning the
"data objects retain their initial values.
dref1 = NEW #( ).
dref2 = NEW string( ).
"Assigning single values; specified as unnamed data objects
dref1 = NEW #( 123 ).
dref2 = NEW string( `hallo` ).
"Using inline declarations to omit a prior declaration of a variable
DATA(dref3) = NEW i( 456 ).
DATA text TYPE string VALUE `world`.
"Another constructor expression specified within the parentheses
dref2 = NEW string( `Hello ` && text && CONV string( '!' ) ).
DATA dref4 TYPE REF TO string_table.
dref4 = NEW #( VALUE string_table( ( `a` ) ( `b` ) ) ).
"Structured type; named arguments within the parentheses
DATA(dref5) = NEW scarr( carrid = 'AA' carrname = 'American Airlines' ).
"Object references
"Declaring object reference variables
DATA oref1 TYPE REF TO cl1. "Assumption: class without constructor implementation
DATA oref2 TYPE REF TO cl2. "Assumption: class with constructor implementation
"Creating instances of classes
oref1 = NEW #( ).
"Listing the parameter bindings for the constructor method
"If there is only one parameter, the explicit specification of the
"parameter name is not needed and the value can be specified directly
oref2 = NEW #( p1 = ... p2 = ... ).
"Using inline declaration
DATA(oref3) = NEW cl2( p1 = ... p2 = ... ).
"Method chaining
... NEW some_class( ... )->meth( ... ).
"Chained attribute accesses
... NEW some_class( ... )->attr ...
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `CONV`
- The
[`CONV`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_conv.htm)
operator enforces conversions from one type to another and creates
an appropriate result.
- Note that the conversion is carried out according to [conversion
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_rules.htm).
- Further [special
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconv_constructor_inference.htm)
apply if the constructor expression is passed to an [actual
parameter](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenactual_parameter_glosry.htm "Glossary Entry")
with a generically typed [formal
parameter](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenformal_parameter_glosry.htm "Glossary Entry").
- The operator is particularly suitable for avoiding the declaration
of helper variables.
Examples:
``` abap
"Result: 0.2
DATA(a) = CONV decfloat34( 1 / 5 ).
"Comparison with an expression without CONV; the result is 0
DATA(b) = 1 / 5.
```
Excursion: As outlined above, you can construct structures and internal
tables using the `VALUE` operator. Using this operator for
constructing [elementary data
objects](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenelementary_data_object_glosry.htm "Glossary Entry")
is not possible apart from creating a data object with an initial value,
for example `DATA(str) = VALUE string( ).`. The `CONV`
operator closes this gap. However, in some cases, the use of
`CONV` is redundant.
``` abap
DATA(c) = CONV decfloat34( '0.4' ).
"Instead of
DATA d TYPE decfloat34 VALUE '0.4'.
"Redundant conversion
"Derives the string type automatically
DATA(e) = `hallo`.
"Produces a syntax warning
"DATA(f) = CONV string( `hallo` ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `EXACT`
- The
[`EXACT`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_exact.htm)
operator enforces either a [lossless
assignment](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenlossless_move.htm)
or a [lossless
calculation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenlossless_calculation.htm)
depending on the data object specified within the parentheses and
creates an appropriate result.
- In case of calculations, [rules of lossless
assignments](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove_exact.htm)
apply. In other cases, the result is created according to the
[conversion
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_rules.htm)
mentioned above and an additional check is performed in accordance
with the [rules of lossless
assignments](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove_exact.htm).
Examples:
``` abap
"Leads to a data loss when converting to a data object accepting only a single character
TRY.
  DATA(exact1) = EXACT abap_bool( 'XY' ).
  CATCH CX_SY_CONVERSION_DATA_LOSS INTO DATA(error1).
ENDTRY.
"The calculation cannot be executed exactly; a rounding is necessary
TRY.
  DATA(exact2) = EXACT decfloat34( 1 / 3 ).
  CATCH CX_SY_CONVERSION_ROUNDING INTO DATA(error2).
ENDTRY.
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `REF`
- The
[`REF`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_ref.htm)
operator creates a [data reference
variable](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_variable_glosry.htm "Glossary Entry")
pointing to a specified data object.
- The type specified after `REF` and directly before the first
parenthesis determines the [static
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenstatic_type_glosry.htm "Glossary Entry")
of the result.
- The operator replaces [`GET
REFERENCE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapget_reference.htm)
and is particularly useful for avoiding the declaration of helper
variables that are only necessary, for example, to specify data
reference variables as actual parameters.
Examples:
``` abap
"Data references
"Declaring data object and assign value
DATA number TYPE i VALUE 5.
"Declaring data reference variable
DATA dref_a TYPE REF TO i.
"Getting references
dref_a = REF #( number ).
"Inline declaration and explicit type specification
DATA(dref_b) = REF string( `hallo` ).
"Object references
DATA(oref_a) = NEW some_class( ).
DATA(oref_b) = REF #( oref_a ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `CAST`
- Using the
[`CAST`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_cast.htm)
operator, you can carry out
[upcasts](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenup_cast_glosry.htm "Glossary Entry")
and
[downcasts](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendown_cast_glosry.htm "Glossary Entry")
and create a reference variable of a static type as a result.
- It replaces the
[`?=`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove_cast.htm)
operator and enables [chained method
calls](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenchained_method_call_glosry.htm "Glossary Entry").
- The operator is particularly helpful for avoiding the declaration of
helper variables and more contexts.
- Similar to the `NEW` operator, constructor expressions with
`CAST` can be followed by the object component selector
`->` to point to a class or interface attribute (`... CAST class( ... )->attr`) and methods (`... CAST class( ...
)->meth( ... )`). Method chaining, standalone and
functional method calls are possible, too. See more information
[here](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_cast.htm).
[Run Time Type Identification
(RTTI)](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrun_time_type_identific_glosry.htm "Glossary Entry")
examples:
``` abap
"Getting component information
DATA(components) =
  CAST cl_abap_structdescr(
    cl_abap_typedescr=>describe_by_data( some_object ) )->components.
"Getting method information
DATA(methods) =
  CAST cl_abap_objectdescr(
    cl_abap_objectdescr=>describe_by_name( 'LOCAL_CLASS' ) )->methods.
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `COND`
- The
[`COND`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconditional_expression_cond.htm)
operator is used for either creating a result depending on [logical
expressions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenlogical_expression_glosry.htm "Glossary Entry")
or raising a [class-based
exception](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenclass_based_exception_glosry.htm "Glossary Entry")
(which is specified within the parentheses after the addition
[`THROW`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconditional_expression_result.htm)).
- There can be multiple logical expressions initiated by
`WHEN` followed by the result specified after
`THEN`. If none of the logical expressions are true, you can
specify an `ELSE` clause at the end. If this clause is not
specified, the result is the initial value of the specified or
derived data type.
- Note that all operands specified after `THEN` must be
convertible to the specified or derived data type.
Example:
``` abap
DATA(b) = COND #( WHEN a BETWEEN 1 AND 3 THEN w
                  WHEN a > 4 THEN x
                  WHEN a IS INITIAL THEN y
                  ELSE z ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `SWITCH`
The
[`SWITCH`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconditional_expression_switch.htm)
operator is fairly similar to the `COND` operator and works in
the style of
[`CASE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcase.htm)
statements, i. e. it uses the value of only a single variable that is
checked in the case distinction.
``` abap
DATA(b) = SWITCH #( a
                    WHEN 1 THEN w
                    WHEN 2 THEN x
                    WHEN 3 THEN y
                    ELSE z ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `FILTER`
- The
[`FILTER`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_filter.htm)
operator constructs an internal table line by line based on an
existing table and conditions specified in a `WHERE` clause.
- The conditions can either be based on single values or a [filter
table](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expr_filter_table.htm).
- Additions:
|Addition |Details |
|---|---|
|`USING KEY` | Specifies the [table key](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentable_key_glosry.htm "Glossary Entry") with which the `WHERE` condition is evaluated, i. e. a [sorted key](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensorted_key_glosry.htm "Glossary Entry") or a [hash key](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhash_key_glosry.htm "Glossary Entry"). If the internal table has neither of them, a [secondary table key](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensecondary_table_key_glosry.htm "Glossary Entry") must be available and specified. |
| `EXCEPT` | The specification of `EXCEPT` means that those lines of the existing table are used that do not meet the condition specified in the `WHERE` clause. Hence, if `EXCEPT` is not specified, the lines of the existing table are used that meet the condition. |
Examples:
``` abap
DATA(f1) = FILTER #( tab WHERE comp > 5 ).
DATA(f2) = FILTER #( tab EXCEPT WHERE comp < 3 ).
DATA(f3) = FILTER #( tab USING KEY x WHERE comp = 4 ).
"Filtering based on another table
DATA(f3) = FILTER #( tab IN filter_tab
                     WHERE comp = 3 ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `REDUCE`
- The
[`REDUCE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_reduce.htm)
operator creates a result of a specified or derived type from one or
more [iteration
expressions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeniteration_expression_glosry.htm "Glossary Entry").
- It basically reduces sets of data objects to a single data object.
For example, the numeric values of a table column are summed up. As
a result, the total number is constructed.
The following example calculates the total of the numbers from 1 to 10
using the `REDUCE` operator:
``` abap
DATA(sum) = REDUCE i( INIT s = 0
                      FOR  i = 1 UNTIL i > 10
                      NEXT s += i ) ). "sum: 55
```
> **💡 Note**<br>
> - `INIT ...`: A temporary variable is specified that sets an
initial value for the result variable.
>- `FOR ...`: Represents a loop. The loop is carried out until
the condition is met after `UNTIL`.
>- `NEXT ...`: Represents the assignment to the temporary
variable after every iteration.
>- Once the loop has finished, the target variable is assigned the
resulting value.
<p align="right">(<a href="#top">back to top</a>)</p>
## Iteration Expressions with `FOR`
- Using [iteration
expressions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeniteration_expression_glosry.htm "Glossary Entry")
with the language element
[`FOR`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfor.htm),
you can carry out [conditional
iterations](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfor_conditional.htm)
(including the ABAP words `UNTIL` and `WHILE` which
have the semantics of ABAP statements
[`DO`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapdo.htm)
and
[`WHILE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapwhile.htm))
or [table
iterations](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentable_iteration_glosry.htm "Glossary Entry")
(having the semantics of [[LOOP
AT]](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_variants.htm);
the expressions include the ABAP word `IN`).
- Such expressions are possible in the following contexts:
- `REDUCE`: The reduction result is created in the
iteration steps.
- `NEW` and `VALUE`: Used in the context of
looping across internal tables. New table lines are created in
the iteration steps and inserted into a target table.
`FOR ... WHILE`: The following example with `REDUCE`
has the same effect as the example using `UNTIL` shown above.
``` abap
DATA(sum) = REDUCE i( INIT y = 0
                      FOR n = 1 THEN n + 1 WHILE n < 11
                      NEXT y += n ).
```
`FOR ... UNTIL`: See the example in the `REDUCE`
section.
`FOR ... IN`:
- The operand specified after `FOR` represents an iteration
variable, i. e. a [work
area](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenwork_area_glosry.htm "Glossary Entry")
that contains the data while looping across the table.
- This variable is only visible within the `FOR`
expression, i. e. it cannot be used outside of the expression.
- The type of the variable is determined by the type of the internal
table specified after `IN`.
- One or more iteration expressions can be specified using
`FOR`.
- The components or the whole table line that is to be returned are
specified within the pair of parentheses before the closing
parenthesis.
- In contrast to `LOOP` statements, the sequential processing
cannot be debugged.
Some examples for looping across tables and storing values in target
tables:
``` abap
"Looping across table and storing the whole line in a new table;
"the target table must have the same table type as the source table itab;
"without the WHERE condition, all lines are respected
TYPES t_type LIKE itab.
... = VALUE t_type( FOR wa IN itab
                    "WHERE ( comp1 > 2 )
                    ( wa ) ).
"Storing specific components having different names by specifying the assignment
"individually; assumption: the target type is not compatible to the type of itab;
"a field mapping is provided; pay attention to potential type conversion
... = VALUE t_type( FOR wa IN itab
                    "WHERE ( comp1 > 2 )
                    ( compX = wa-comp1
                      compY = wa-comp2 ) ).
"Storing specific components having the same names;
"assumption: Target type is not compatible to the type of itab;
"if there are identically named components in the table types, you might
"also use CORRESPONDING
... = VALUE t_type( FOR wa IN itab
                    "WHERE ( comp1 > 2 )
                    ( CORRESPONDING #( wa ) ) ).
"Multiple iteration expressions
... = VALUE t_type( FOR wa1 IN itab1 WHERE ( comp1 = 4 )
                    FOR wa2 IN itab2 WHERE ( comp2 > 5 )
                    FOR wa3 IN itab3 WHERE ( comp3 < 3 )
                    ( compX = wa1-comp1
                      compY = wa2-comp2
                      compZ = wa3-comp3 ) ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## `LET Expressions`
- [`LET`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaplet.htm)
expressions allow you to declare local helper fields (variables or
fields symbols) and assign values (the type is derived from the
defined value) to be used in constructor expressions, for example,
in iteration expressions using `FOR` or results specified in
the conditional expressions of `COND` and `SWITCH`.
- Note that the helper field is only valid in the context in which the
`LET` expression is specified.
Examples:
``` abap
"Creating a string table using a LET expression
DATA(str_tab) = VALUE string_table( LET it = `be` IN
                    ( |To { it } is to do| )
                    ( |To { it } or not to { it }| )
                    ( |To do is to { it }| )
                    ( |Do { it } do { it } do| ) ).
"Conditional expressions
DATA(a) = COND #( LET b = c IN
                  WHEN b > x THEN ...
                  WHEN b < y THEN ...
                  ...
                  ELSE ... ).
```
<p align="right">(<a href="#top">back to top</a>)</p>
## Executable Example
[zcl_demo_abap_constructor_expr](./src/zcl_demo_abap_constructor_expr.clas.abap)
Note the steps outlined [here](README.md#🎬-getting-started-with-the-examples) about how to import and run the code.

866
06_Dynamic_Programming.md Normal file
View File

@@ -0,0 +1,866 @@
<a name="top"></a>
# Dynamic Programming
- [Dynamic Programming](#dynamic-programming)
- [Notes on "Dynamic"](#notes-on-dynamic)
- [Excursion: Field Symbols and Data References](#excursion-field-symbols-and-data-references)
- [Field Symbols](#field-symbols)
- [Data References](#data-references)
- [Dynamic ABAP Statements](#dynamic-abap-statements)
- [Runtime Type Services (RTTS)](#runtime-type-services-rtts)
- [Further Information](#further-information)
- [Executable Example](#executable-example)
## Notes on "Dynamic"
Some considerations regarding "dynamic" in contrast to "static" aspects:
- ABAP programs can include both dynamic and static parts.
- Consider a [data
object](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_object_glosry.htm "Glossary Entry")
you declare in a program having dedicated technical properties like
the [data
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_type_glosry.htm "Glossary Entry")
or the actual name of the data object, i. e. these properties are
already (statically) known to the program at compile time and they
do not change throughout the program execution.
- On the other hand, there can be use cases where these properties
**are not known or not yet determined at compile time** at all.
- They are **only known at a program's runtime**, i. e. the
properties are defined and passed to programs at runtime.
- Consider a program that does not work with a specific kind of table
but should be able to work with any kind of table, for example, a
user must input the table name first in a UI. The tables to be used
in the program certainly have different properties, line types,
field names, number of rows, and so on. Nevertheless, the program
must be able to work with all of them, no matter what table is
processed.
- You might also need to determine information about data types and
data objects at runtime or even create them.
Dynamic programming is a powerful means to make ABAP programs more
flexible and versatile. However, as implied above, dynamic programming
techniques must be handled with care and you must be aware of some
downsides, too. For example:
- Dynamic features implemented in a program cannot be checked or
analyzed by the ABAP compiler. The exact data is not known at
compile time but only when the program is executed which has also an
impact on performance since the checks must be carried out at
runtime.
- Testing
[procedures](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenprocedure_glosry.htm "Glossary Entry")
including dynamic parts is difficult.
<p align="right">(<a href="#top">back to top</a>)</p>
## Excursion: Field Symbols and Data References
[Field
symbols](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfield_symbol_glosry.htm "Glossary Entry")
and [data
references](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_glosry.htm "Glossary Entry")
support dynamic programming and working with data objects whose
properties are only known at runtime.
### Field Symbols
Field symbols ...
- can be considered as alias names for existing data objects.
- can only be used if they are assigned to a data object first. And if
assigned, you can access the content of variables via the field
symbol name.
- do not consume any space but act as a sort of label for the
particular memory area that is used by a data object which the field
symbol is assigned to.
- can be used in ABAP programs as if working with the actual data
object.
- can be statically typed with both [complete data
types](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencomplete_data_type_glosry.htm "Glossary Entry")
and [generic data
types](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abengeneric_data_type_glosry.htm "Glossary Entry").
- are especially helpful for accessing and editing data in structures
or internal tables at runtime without the need to copy the data
somewhere which boosts performance.
**Declaring field symbols**
Field symbols are declared with the `FIELD-SYMBOLS` statement.
You provide the name of the field symbol between angle brackets. You can
either type them with a complete data type or with a generic type.
> **💡 Note**<br>
>- There are plenty of options for generic ABAP types. A prominent one
is `data` that stands for any data type (the older generic
type `any` has the same effect). See more information in the
topic [Generic ABAP
Types](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenbuilt_in_types_generic.htm).
>- Field symbols cannot be declared in the declaration part of
[classes](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenclass_glosry.htm "Glossary Entry")
and
[interfaces](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenoo_intf_glosry.htm "Glossary Entry").
>- Untyped field symbols are not supported in object-oriented contexts.
>- Field symbols can also be [declared
inline](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfield-symbol_inline.htm).
Syntax:
``` abap
"Complete types
FIELD-SYMBOLS: <fs_i> TYPE i,
<fs_fli> TYPE zdemo_abap_fli,
<fs_tab_type> TYPE LINE OF some_table_type,
<fs_like> LIKE some_data_object.
"Generic types
FIELD-SYMBOLS <fs_data> TYPE data. "or: TYPE any
FIELD-SYMBOLS <fs_any_table> TYPE any table.
```
**Assigning data objects**
When assigning data objects to field symbols with the
[`ASSIGN`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapassign.htm)
statement, field symbols are given all properties and values from the
data objects. In case of completely typed field symbols, you can only
assign data objects that have the same type. Further dynamic aspects
enter the picture with dynamic assignment. This is dealt with further
down.
Syntax:
``` abap
"Data objects.
DATA: number TYPE i,
struc TYPE sflight,
tab TYPE string_table.
"Field symbols with complete types
FIELD-SYMBOLS: <fs_i> TYPE i,
<fs_struc> TYPE sflight,
<fs_tab> TYPE string_table.
"Generic type
FIELD-SYMBOLS <fs_gen> TYPE data.
"Assigning data objects to field symbols
ASSIGN number TO <fs_i>.
ASSIGN struc TO <fs_struc>.
ASSIGN tab TO <fs_tab>.
ASSIGN number TO <fs_gen>. "Could be any of the data objects
ASSIGN number TO FIELD-SYMBOL(<fs_inl>). "Field symbol declared inline
"You can also assign a particular component of a structure.
"Second component of the structure
ASSIGN COMPONENT 2 OF STRUCTURE struc TO <fs_gen>.
ASSIGN COMPONENT 'CARRID' OF STRUCTURE struc TO <fs_gen>.
```
> **💡 Note**<br>
> - When working with field symbols, you should make sure that they are assigned. Otherwise, a runtime error occurs. You can check the
assignment with the following logical expression. The statement is true if the field symbol is assigned.
> ``` abap
> IF <fs_i> IS ASSIGNED.
>   ...
> ENDIF.
> ```
>- You can explicitly remove the assignment of the field symbol. After this, the field symbol does not point to any data object any more.
Note that a `CLEAR` statement only initializes the value.
> ``` abap
> UNASSIGN <fs_i>.
> ```
>- When assigning data objects to fields symbols, you should pay attention to compatible types of data object and field symbol. There
is also an ABAP syntax with which you can carry out type casting for incompatible types. You can cast either implicitly or explicitly by specifying the concrete type. The addition [`TYPE HANDLE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapassign_casting&sap-language=EN&sap-client=000&version=X&anchor=!ABAP_ADDITION_5@5@&tree=X)
is relevant for [Runtime Type Services
(RTTS)](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrtti.htm).
> ``` abap
> TYPES c_len_3 TYPE c LENGTH 3.
> DATA(chars) = 'abcdefg'.
>
> FIELD-SYMBOLS <fs1> TYPE c_len_3.
> "Implicit casting
> ASSIGN chars TO <fs1> CASTING.
>
> FIELD-SYMBOLS <fs2> TYPE data.
> "Explicit casting
> ASSIGN chars TO <fs2> CASTING TYPE c_len_3.
> ```
**Using field symbols**
When accessing field symbols, you address the memory area of an existing data object. After an assignment, you might assign the data object another value:
``` abap
DATA: number TYPE i VALUE 1.
FIELD-SYMBOLS <fs_i> TYPE i.
ASSIGN number TO <fs_i>.
<fs_i> = 2.
"number has now the value 2
```
As mentioned, field symbols are often used when working with internal tables, for example, in `LOOP` statements. In this context,
field symbols are very handy. You can avoid an actual copying of content to a work area during the loop. In doing so, the loop is considerably faster especially when dealing with large tables. You can assign the field symbol using the `ASSIGNING` addition. With `ASSIGNING FIELD-SYMBOL(...)`, you can make use of a field symbol declared inline and assign the field symbol in one go.
``` abap
SELECT * FROM zdemo_abap_fli
INTO TABLE @DATA(itab).
FIELD-SYMBOLS <fs1> LIKE LINE OF itab.
LOOP AT itab ASSIGNING <fs1>.
<fs1>-carrid = ... "The field symbol represents a line of the table.
<fs1>-connid = ... "Components are accessed with the component selector.
"E. g. a new value is assigned.
...
ENDLOOP.
"Inline declaration of field symbol
LOOP AT itab ASSIGNING FIELD-SYMBOL(<fs2>).
<fs2>-carrid = ...
<fs2>-connid = ...
...
ENDLOOP.
```
<p align="right">(<a href="#top">back to top</a>)</p>
### Data References
[Data references](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_glosry.htm "Glossary Entry")
...
- are similar to field symbols but you can do more with them compared
to field symbols.
- point to data objects in the memory, i. e. they include the data
object's address of the memory location.
- are contained in [data reference
variables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_variable_glosry.htm "Glossary Entry")
in ABAP programs.
[Data reference
variables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_reference_variable_glosry.htm "Glossary Entry")
...
- contain values as every other data object. However, the direct value is here a reference (i. e. it points to the memory location of
another data object) which means you cannot work with the value directly. You must dereference the reference first.
- are, despite only pointing to other data objects, data objects themselves that can, for example, also be used as components in
structures or columns in internal tables (which is not possible with field symbols).
> **💡 Note**<br>
>- Data reference variables are considered to be
[deep](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendeep_glosry.htm "Glossary Entry")
like strings and internal tables since none of them have an assigned
dedicated memory area. Internally, strings and internal tables are
addressed using references.
>- [Object
references](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenobject_reference_glosry.htm "Glossary Entry")
and [object reference
variables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenobject_refer_variable_glosry.htm "Glossary Entry")
are not part of this cheat sheet. To get more details, refer to the
ABAP Keyword Documentation or the cheat sheet [ABAP Object Orientation](04_ABAP_Object_Orientation.md).
**Declaring data reference variables**
Like field symbols, data reference variables can be declared with both a complete and a generic data type using `DATA` statements and the
addition `REF TO`. The type after `REF TO` represents the static data type.
When declared, data reference variables do not yet point to a data object.
Examples:
``` abap
DATA: ref1 TYPE REF TO i, "Complete data type
ref2 TYPE REF TO some_dbtab, "Complete data type
ref3 LIKE REF TO some_data_object,
ref4 TYPE REF TO data. "Generic data type
```
**Assigning data references**
There are multiple options to assign data references:
**Creating data references to existing data objects**: Using the
[reference
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenreference_operator_glosry.htm "Glossary Entry")
`REF`, you can get a data reference to an existing data object.
The older syntax [`GET REFERENCE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapget_reference.htm)
has the same effect as using the newer reference operator but should not
be used anymore.
``` abap
"Declaring a data object
DATA num TYPE i VALUE 5.
"Declaring data reference variables
DATA ref1 TYPE REF TO i.
DATA ref_gen TYPE REF TO data.
"Creating data references to data objects.
"The # sign means that the type is derived from the context.
ref1 = REF #( num ).
ref_gen = REF #( num ).
"You can also use inline declarations to omit the explicit declaration.
DATA(ref2) = REF #( num ).
"You can explicitly specify the data type after REF.
DATA(ref3) = REF string( `hallo` ).
"GET REFERENCE OF; do not use anymore
"GET REFERENCE OF num INTO ref1.
"GET REFERENCE OF num INTO DATA(ref4).
```
**Creating new data objects at runtime**: You create a [anonymous
data
object](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenanonymous_data_object_glosry.htm "Glossary Entry")
at runtime by placing the reference in the variable and providing the
desired type. You can use the [instance
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninstance_operator_glosry.htm "Glossary Entry")
[`NEW`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_new.htm).
The older syntax [`CREATE DATA`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapcreate_data.htm)
has the same effect as using the newer instance operator.
Examples:
``` abap
"Declaring data reference variables
DATA ref1 TYPE REF TO i. "Complete type
DATA ref_gen TYPE REF TO data. "Generic type
"Creating anonymous data objects
"Using the # sign and the explicit type: see REF #( ) above.
ref1 = NEW #( ).
ref_gen = NEW string( ).
"For directly assigning values, insert the values within the parentheses.
ref1 = NEW #( 123 ).
"Using inline declarations to omit a prior declaration of a variable.
DATA(ref2) = NEW i( 456 ).
TYPES i_table TYPE STANDARD TABLE OF i WITH EMPTY KEY.
DATA(ref3) = NEW i_table( ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ).
"Older syntax.
DATA ref4 TYPE REF TO string.
DATA ref5 TYPE REF TO data.
CREATE DATA ref4.
"Note: TYPE ... needed because of generic type data
CREATE DATA ref5 TYPE p LENGTH 6 DECIMALS 2.
CREATE DATA ref5 LIKE ref4.
```
**Assigning/Copying existing data references**: You can copy a data reference into another one. Note that static types of both data
reference variables must be compatible and that only the reference is copied and not the data object as such. That means that, when copied, both data reference variables point to the same data object.
Notes:
- Data reference variables have both a
[static](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenstatic_type_glosry.htm "Glossary Entry")
and a [dynamic
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendynamic_type_glosry.htm "Glossary Entry").
- When declaring a data reference variable, e. g. `DATA ref TYPE REF TO
i.`, you determine the static type. This type is either a
non-generic (`i` in the example) or a generic type (like
`data` or `any`; e. g. `DATA ref TYPE REF TO
data.`).
- The dynamic type is determined at runtime of the
program and is the data type of a referenced data object. Especially in
the context of assigning data references (and also object references),
this differentiation is relevant.
- The following basic rule applies: The
assignment of a data reference variable to another one is possible if
the static type of the target reference variable is more general than or
the same as the dynamic type of the source reference variable.
- If it can
be statically checked that an assignment is possible, the assignment is
done using the [assignment
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenassignment_operator_glosry.htm "Glossary Entry")
`=` that triggers an
[upcast](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenup_cast_glosry.htm "Glossary Entry")
automatically. Otherwise, it is a
[downcast](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendown_cast_glosry.htm "Glossary Entry").
Here, the assignability is not checked until runtime. The downcast must
be triggered explicitly using [casting
operators](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencasting_operator_glosry.htm "Glossary Entry"),
either with the [constructor
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_operator_glosry.htm "Glossary Entry")
[`CAST`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconstructor_expression_cast.htm)
or the older
[`?=`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapmove_cast.htm),
for the assignment of data reference variables.
- See more information in
the topic [Assignment Rules for Reference
Variables](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_references.htm).
The following example demonstrates up- and downcasts with the assignment
of data reference variables typed with a complete and generic data type:
Syntax:
``` abap
"Declaring data reference variables
DATA ref1 TYPE REF TO i.
DATA ref2 TYPE REF TO i.
ref1 = NEW #( 789 ).
"Copying data reference
ref2 = ref1.
"Casting
"Complete type
DATA(ref3) = NEW i( 321 ).
"Generic type
DATA ref4 TYPE REF TO data.
"Upcast
ref4 = ref3.
"Downcasts
DATA ref5 TYPE REF TO i.
"Generic type
DATA ref6 TYPE REF TO data.
ref6 = NEW i( 654 ).
ref5 = CAST #( ref6 ).
"Alternative syntax to the CAST operator
ref5 ?= ref6.
```
**Accessing data references**
The content of data objects a data reference refers to can only be
accessed via dereferencing data reference variables using the
[dereferencing
operator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendereferencing_operat_glosry.htm "Glossary Entry")
`->*`.
> **💡 Note**<br>
>- When dereferencing a data reference variable that has a structured
data type, you can use the [component
selector](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencomponent_selector_glosry.htm "Glossary Entry")
`->` to access individual components.
>- In older ABAP releases, you could not dereference data reference
variables typed with a generic type. You had to do an assignment to
a field symbol first.
Syntax:
``` abap
"Creating data reference variables and assign values
DATA(ref_i) = NEW i( 1 ).
DATA(ref_carr) = NEW zdemo_abap_carr( carrid = 'LH' carrname = 'Lufthansa' ).
"Generic type
DATA ref_gen TYPE REF TO data.
ref_gen = ref_i. "Copying reference
"Accessing
"Variable number receives the content.
DATA(number) = ref_i->*.
"Content of referenced data object is changed.
ref_i->* = 10.
"Data reference used in a logical expression.
IF ref_i->* > 5.
...
ENDIF.
"Dereferenced generic type
DATA(calc) = 1 + ref_gen->*.
"Structure
"Complete structure
DATA(struc) = ref_carr->*.
"Individual component
DATA(carrid) = ref_carr->carrid.
ref_carr->carrid = 'UA'.
"This syntax also works but it is less comfortable.
ref_carr->*-carrname = 'United Airlines'.
```
> **💡 Note**<br>
> - You can check if a data reference can be dereferenced by using a
logical expression with [`IS BOUND`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenlogexp_bound.htm):
> ``` abap
> IF ref IS BOUND.
>   ...
> ENDIF.
> ```
>- If you explicitly want to remove a reference from a data reference variable, you can use a `CLEAR` statement. However, the
[garbage collector](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abengarbage_collector_glosry.htm "Glossary Entry")
takes over the reference removal automatically once the data is not used any more by a reference.
> ``` abap
> CLEAR ref.
> ```
**Using data references**
Some contexts of using data references are as follows:
**Overwriting data reference variables**: A data reference variable is overwritten when a new object is created with a data reference
variable already pointing to a data object.
``` abap
ref = NEW i( 1 ).
ref = NEW i( 2 ).
```
**Keeping data references**: If your use case is to retain the data references and you want to prevent that data references are overwritten
when using the same reference variable, you can put the reference variables in internal tables. The following code shows that three data
references are created with the same reference variable.
``` abap
DATA: ref TYPE REF TO data,
itab TYPE TABLE OF REF TO data,
number TYPE i VALUE 0.
DO 3 TIMES.
"Adding up 1 to demonstrate a changed data object.
number += 1.
"Creating data reference and assigning value.
"In the course of the loop, the variable gets overwritten.
ref = NEW i( number ).
"Adding the reference to itab
itab = VALUE #( BASE itab ( ref ) ).
ENDDO.
```
**Processing internal tables**: Similar to using field symbols, you can avoid the copying of table rows into a work area, for example, in a
loop using data reference variables and a `REFERENCE INTO` statement. In doing so, the processing of internal tables is much faster
than copying table lines to a work area. In the code snippet, an inline declaration is used in the `LOOP` statement.
``` abap
"Fill an internal table.
SELECT * FROM zdemo_abap_fli
INTO TABLE @DATA(fli_tab).
LOOP AT fli_tab REFERENCE INTO DATA(ref).
"A component of the table line might be addressed.
ref->carrid = ...
...
ENDLOOP.
```
**Data reference variables as part of structures and internal tables**: In contrast to field symbols, data reference variables can be used as components of structures or columns in internal tables.
``` abap
"Structure
DATA: BEGIN OF struc,
num TYPE i,
ref TYPE REF TO i,
END OF struc.
"Some value assignment
struc2 = VALUE #( num = 1 ref = NEW #( 2 ) ).
"Internal table
DATA itab LIKE TABLE OF struc WITH EMPTY KEY.
"Some value assignment in the first table line
"assuming the table is filled and a line is available.
itab[ 1 ]-ref->* = 123.
```
> **✔️ Hint**<br>
> The question might now arise when to actually use either a field symbol
or a data reference variable. It depends on your use case. However, data
reference variables are more powerful as far as their usage options are
concerned, and they better fit into the modern (object-oriented) ABAP
world. Recommended read: [Accessing Data Objects
Dynamically](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abendyn_access_data_obj_guidl.htm "Guideline").
<p align="right">(<a href="#top">back to top</a>)</p>
## Dynamic ABAP Statements
Dynamic aspects come particularly into the picture when considering the
options of dynamic ABAP statements. In this context, you can make use of
[tokens](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentoken_glosry.htm "Glossary Entry")
put within parentheses and included as operands in many ABAP statements
(e. g. `SORT table BY (field_name).`). The content of the token
is character-like and should be provided in capital letters. The content
is determined at runtime, e. g. a user entry in an input field whose
content is then part of an ABAP statement.
Note that especially in this context, static checks are not possible, i.
e. if you have an ABAP statement using such a token, it cannot be
determined at compile time whether the operand that is passed is valid.
This can cause runtime errors.
You can make use of the following dynamic token specification options:
1. **Dynamic specification of data objects and fields**
The names of data objects and fields are determined at runtime.
Examples:
``` abap
"The sorting is done by a field that is determined at runtime.
SORT itab BY (field_name).
"A field symbol is assigned a data object; here, an attribute of a class
ASSIGN class=>(attribute_name) TO FIELD-SYMBOL(<fs>).
```
2. **Dynamic specification of types**
The name of a data or object type is determined at runtime.
Examples:
``` abap
"Anonymous data objects are created using a type determined at runtime.
"Note that the NEW operator cannot be used here!
CREATE DATA ref TYPE (some_type).
CREATE DATA ref TYPE TABLE OF (some_type).
"Assigning a data object to a field symbol casting a type
ASSIGN dobj TO <fs> CASTING TYPE (some_type).
"Assigning a structure component dynamically to a field symbol that is declared inline
DATA struct TYPE zdemo_abap_flsch.
ASSIGN struct-('CARRID') TO FIELD-SYMBOL(<fs>).
```
3. **Dynamic specification of clauses in ABAP SQL statements**
For example, a token that includes the `WHERE` clause conditions in a `SELECT` statement. The token can also be an internal table of a character-like line type.
Examples:
``` abap
"Dynamic SELECT list
DATA(select_list) = `CARRID, CONNID, COUNTRYFR, COUNTRYTO`.
SELECT (select_list)
FROM zdemo_abap_fli
INTO TABLE @itab.
"Dynamic FROM clause
DATA(table) = `ZDEMO_ABAP_FLI`.
SELECT *
FROM (table)
INTO TABLE @itab.
"Dynamic WHERE clause
DATA(where_clause) = `CARRID = 'LH'`.
SELECT *
FROM zdemo_abap_fli
WHERE (where_clause) INTO TABLE @itab.
```
4. **Dynamic specification of [procedures](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenprocedure_glosry.htm "Glossary Entry")**
Names are specified dynamically, e. g. the names of classes and methods.
Examples:
``` abap
"Dynamic method calls
"Note that these calls require a CALL METHOD statement.
"Method dynamically specified.
CALL METHOD class=>(meth).
"Class dynamically specified.
CALL METHOD (class)=>meth.
"Class and method dynamically specified.
CALL METHOD (class)=>(meth).
"Specifying parameters
CALL METHOD class=>(meth) IMPORTING param = ... .
"Parameters and exceptions can also be specified dynamically in tables.
CALL METHOD class=>(meth) PARAMETER-TABLE ptab.
CALL METHOD class=>(meth) PARAMETER-TABLE ptab EXCEPTION-TABLE etab.
```
Regarding the addition `PARAMETER-TABLE`, you can assign [actual
parameters](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenactual_parameter_glosry.htm "Glossary Entry")
to [formal
parameters](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenformal_parameter_glosry.htm "Glossary Entry")
dynamically using the table `ptab` that is of type
`ABAP_PARMBIND_TAB`. The table must be filled and have a
line for all non-optional parameters. The line type is
`ABAP_PARMBIND`. The following fields are relevant:
- `name`: The name of the formal parameter.
- `kind`: Specifies the kind of parameter, e. g. importing or exporting parameter. You can make use of the constants defined in class `CL_ABAP_OBJECTDESCR`. Note that if the method signature has an importing parameter, it must be specified as exporting parameter here and vice versa.
- `value`: Specifies a data reference to the actual parameter.
Errors raise catchable exceptions of class `CX_SY_DYN_CALL_ERROR`. Using the addition `EXCEPTION-TABLE` and an internal table of type `ABAP_EXCPBIND_TAB`, you can handle non-[class-based
exceptions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenclass_based_exception_glosry.htm "Glossary Entry").
<p align="right">(<a href="#top">back to top</a>)</p>
## Runtime Type Services (RTTS)
[RTTS](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrun_time_type_services_glosry.htm "Glossary Entry")
represent a hierarchy of [type description
classes](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentype_class_glosry.htm "Glossary Entry")
containing methods for [Runtime Type Creation
(RTTC)](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrun_time_type_creation_glosry.htm "Glossary Entry")
and [Runtime Type Identification
(RTTI)](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenrun_time_type_identific_glosry.htm "Glossary Entry").
Using these classes, you can
- get type information on data objects, data types or
[instances](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninstance_glosry.htm "Glossary Entry")
at runtime.
- define and create new data types at runtime.
The hierarchy of type description classes is as follows.
<pre>
CL_ABAP_TYPEDESCR
|
|--CL_ABAP_DATADESCR
| |
| |--CL_ABAP_ELEMDESCR
| | |
| | |--CL_ABAP_ENUMDESCR
| |
| |--CL_ABAP_REFDESCR
| |--CL_ABAP_COMPLEXDESCR
| |
| |--CL_ABAP_STRUCTDESCR
| |--CL_ABAP_TABLEDESCR
|
|--CL_ABAP_OBJECTDESCR
|
|--CL_ABAP_CLASSDESCR
|--CL_ABAP_INTFDESCR
</pre>
So, the
[superclass](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensuperclass_glosry.htm "Glossary Entry")
`CL_ABAP_TYPEDESCR` has multiple
[subclasses](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensubclass_glosry.htm "Glossary Entry"),
for example, to deal with each kind of type. Among them, there are, for
example, structures or tables. Working with this superclass and its
subclasses means making use of
[casts](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abencast_glosry.htm "Glossary Entry"),
especially
[downcasts](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendown_cast_glosry.htm "Glossary Entry").
Detailing out all the possibilities for the information retrieval and
type creation is beyond scope. Check the information, options and
various methods that can be used in the class documentation, e. g. using
F2 help information in
[ADT](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenadt_glosry.htm "Glossary Entry"),
for more details.
The following examples show the retrieval of information. Instead of the
cumbersome extra declaration of data reference variables, you can use
[inline
declarations](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abeninline_declaration_glosry.htm "Glossary Entry").
[Method
chaining](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenmethod_chaining_glosry.htm "Glossary Entry")
comes in handy, too.
``` abap
"The properties of a type are retrieved.
DATA(some_type) = cl_abap_typedescr=>describe_by_data( var ).
"The components of a structure are retrieved.
"Like above, the describe_by_data method is used together with a variable.
DATA(components) = CAST cl_abap_structdescr(
cl_abap_typedescr=>describe_by_data( some_struc )
)->components.
"The attributes of a global class are retrieved. In contrast to the
"example above the describe_by_name method is used together with the actual name.
DATA(attributes) = CAST cl_abap_classdescr(
cl_abap_classdescr=>describe_by_name( 'CL_SOME_CLASS' )
)->attributes.
```
The following example demonstrates the creation of an internal table
type based on a [DDIC
type](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenddic_type_glosry.htm "Glossary Entry").
Furthermore, an internal table is created based on this type. The type
itself is a sorted table (constants can also be used here). Unique keys
are defined in a dedicated table of type
`ABAP_KEYDESCR_TAB` that is part of the
`cl_abap_tabledescr=>create` method call.
Note the [`TYPE HANDLE`](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abapcreate_data_handle.htm)
addition as part of the `CREATE DATA` statement that is used
when referring to dynamically created data types.
``` abap
DATA(line_type) = CAST cl_abap_structdescr(
cl_abap_tabledescr=>describe_by_name( `ZDEMO_ABAP_CARR` ) ).
"Defining primary table keys of internal table type to be created
DATA(key_tab) = VALUE abap_keydescr_tab( ( name = 'CARRID' )
( name = 'CARRNAME' ) ).
"Creating internal table type
DATA(table_type) = cl_abap_tabledescr=>create(
p_line_type = line_type
p_table_kind = cl_abap_tabledescr=>tablekind_sorted
p_unique = cl_abap_typedescr=>true
p_key = key_tab ).
"Create internal table based on the created table type
DATA ref_tab TYPE REF TO data.
CREATE DATA ref_tab TYPE HANDLE table_type.
```
<p align="right">(<a href="#top">back to top</a>)</p>
## Further Information
- It is recommended that you also consult section [Dynamic Programming Techniques (F1 docu for standard ABAP)](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abendynamic_prog_technique_gdl.htm) in the ABAP Keyword Documentation since it provides important aspects that should be considered when dealing with dynamic programming in general (e. g. security aspects or runtime error prevention).
- There are even further dynamic programming techniques in the unrestricted language scope like the
generation or execution of programs at runtime. They are not part of this cheat sheet. Find more details on the related syntax (e. g. `GENERATE SUBROUTINE POOL`, `READ REPORT` and `INSERT REPORT` in the ABAP Keyword Documentation for Standard ABAP: [Dynamic Program Development](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap_language_dynamic.htm)
## Executable Example
[zcl_demo_abap_dynamic_prog](./src/zcl_demo_abap_dynamic_prog.clas.abap)
Note the steps outlined [here](README.md#🎬-getting-started-with-the-examples) about how to import and run the code.

1178
07_String_Processing.md Normal file

File diff suppressed because it is too large Load Diff

1183
08_EML_ABAP_for_RAP.md Normal file

File diff suppressed because it is too large Load Diff

182
09_Bits_and_Bytes.md Normal file
View File

@@ -0,0 +1,182 @@
<a name="top"></a>
# Excursion Down to Bits and Bytes
This sheet goes a bit into the technical background of data types and
data objects. It may be helpful for a better understanding of how to
handle data in ABAP including a glance on casting and conversions.
After its declaration, a [data
object](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abendata_object_glosry.htm "Glossary Entry")
is usable in its context (procedure, class, program) according to its
type. For example, a numeric data object can be assigned the result of a
calculation:
> **💡 Note**<br>
> For checking out the code snippets in an SAP BTP ABAP environment, you can use the interface `if_oo_adt_classrun` in a class by implementing the method `if_oo_adt_classrun~main`.
``` abap
DATA num TYPE i.
num = 2 * 3 * 5 * 53 * 2267.
cl_demo_output=>display( num ).
```
After this assignment, the data object `num` contains the
calculated value 3604530, which is also displayed accordingly with a
type-compliant output as, for example,
`cl_demo_output=>display`. And of course the same can be seen
in the display of the variable in the ABAP Debugger when setting a
breakpoint at the last statement.
The ABAP Debugger also shows the hexadecimal value 32003700 of the data
object. This directly represents the binary value `0011 0010 0000 0000
0011 0111 0000 0000` stored in the 4 bytes allocated to the 4-byte
integer number in the memory. This value is platform dependent and for
numeric types is defined by the [byte
order](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenbyte_order_glosry.htm "Glossary Entry")
order, where either the most significant (big endian) or least
significant (little endian) byte is written to the first memory
location. The decimal value of the hexadecimal value `32003700` shown here
would be `838874880` and is not the integer value
`3604530` that ABAP deals with. This shows the meaning of
data types. A data object is a sequence of bytes stored in memory at its
address, which is interpreted by the ABAP runtime framework according to
the data type. The hexadecimal value is in most cases irrelevant to the
programmer.
Let us now consider a character-like field text with a length of two
characters:
``` abap
DATA text TYPE c LENGTH 2.
text = '2' && '7'.
cl_demo_output=>display( text ).
```
This field can be assigned the result of a string operation as shown and
the result shown by `cl_demo_output=>display` as well as in
the ABAP Debugger is the character string `27`. Again, it is
the data type, that derives the value `27` from the actual hexadecimal
content, which is `32003700` as in the previous example! In
this case, `32003700` is the encoding of the string
`27` in the Unicode character representation
[UCS-2](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenucs2_glosry.htm "Glossary Entry"),
which is supported by ABAP in Unicode systems. The Unicode character
representation also depends on the platform-dependent byte order.
Only for a byte-type data type does the value as interpreted by ABAP
directly correspond to the hexadecimal content. The following lines
modify the bits of a byte string with a bit-operation:
``` abap
DATA hex TYPE x LENGTH 4 VALUE 'CDFFC8FF'.
hex = BIT-NOT hex.
cl_demo_output=>display( hex ).
```
Here, the output with `cl_demo_output=>display`, the value
display of the ABAP Debugger as well as the hexadecimal value are the
same, namely `32003700`.
In the above examples, we presented three data objects that all occupy 4
bytes in memory that have the same binary values, but are handled
differently by ABAP due to their data type. The data type is also
responsible for the fact, that different kind of operations (numeric
calculation, string concatenation, bit-operation) can be applied to the
respective data objects. Using these examples we can have now look at
the basic concepts of
[casting](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencast_casting_glosry.htm "Glossary Entry")
and [type
conversion](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abentype_conversion_glosry.htm "Glossary Entry")
and their relation to bits and bytes.
In ABAP, the term casting means nothing more than treating a data object
according to a different data type than the one that is permanently
assigned to it. This can be done using [field
symbols](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfield_symbol_glosry.htm "Glossary Entry"),
with which a new (symbolic) name and a new type can be defined for the
memory area of a data object. When the memory area is accessed using a
field symbol, it is handled according to the type of the field symbol.
The following lines show an example.
``` abap
DATA hex TYPE x LENGTH 4 VALUE '32003700'.
FIELD-SYMBOLS: <num>  TYPE i,
               <text> TYPE c.
ASSIGN hex TO <num>  CASTING.
ASSIGN hex TO <text> CASTING.
cl_demo_output=>new(
  )->write_data( hex
  )->write_data( <num>
  )->write_data( <text> )->display( ).
```
The bit string in `hex` is cast to a numeric field when accessed
using the name `<num>` and to a text field when accessed using
the name `<text>`. The outputs are `32003700`,
`3604530` and `27`, clearly showing the effect of
the data type on handling one and the same hexadecimal content.
In contrast, in a type conversion (or conversion for short), the actual
binary content of a data object is converted so that it fits another
data type. Type conversions usually occur in assignments between data
objects of different data types. The goal of such a conversion is to
preserve the type-specific meaning of the content in the source field as
far as possible for the data type of the target field. For this purpose,
ABAP contains a large set of [conversion
rules](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenconversion_rules.htm).
A simple example is shown here:
``` abap
TYPES hex TYPE x LENGTH 4.
FIELD-SYMBOLS:
  <hex_text> TYPE hex,
  <hex_num>  TYPE hex.
DATA: text TYPE c LENGTH 2 VALUE '27',
      num  TYPE i.
num = text.
ASSIGN text TO <hex_text> CASTING.
ASSIGN num  TO <hex_num>  CASTING.
cl_demo_output=>new(
  )->write_data( text
  )->write_data( <hex_text>
  )->write_data( num
  )->write_data( <hex_num> )->display( ).
```
We are assigning the character-like field `text` to the numeric
field `num` and display the result that can also be checked in
the ABAP Debugger. The ABAP runtime framework recognizes that the
character string `27` in text can be interpreted as the
integer number `27`, generates the hexadecimal value 1B000000
in which this number is encoded for the numeric type of `num`,
and assigns it to the memory location of `num`. Thus, the actual
conversion takes place for the original hexadecimal content
`32003700` of `text` to the new hexadecimal content
`1B000000` of `num`. For character strings in text
fields, for which no such meaningful conversion is possible, an
exception occurs. The field symbols `<hex_text>` and
`<hex_num>` are used to show the hexadecimal content of the
fields `text` and `num` by casting them to a byte-like
type.
> **✔️ Hint**<br>
> For reasons of simplicity this sheet is restricted to named elementary
variables. Note that in particular the same holds for
[literals](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenabap_literal_glosry.htm "Glossary Entry")
that are handled internally in such a way as if they were constants of
the data type assigned to the literal. In the preceding example,
`text` can be replaced by a literal `'27'` yielding
the same results.

703
10_ABAP_SQL_Hierarchies.md Normal file
View File

@@ -0,0 +1,703 @@
<a name="top"></a>
# ABAP SQL: Working with Hierarchies
This cheat sheet summarizes the functions ABAP SQL offers together with
ABAP CDS for working with [hierarchical
data](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_glosry.htm "Glossary Entry")
that is stored in database tables. Hierarchical data in database tables
means that lines of one or more database tables are connected by
[parent-child
relationships](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenpcr_glosry.htm "Glossary Entry").
There are many use cases where hierarchical data plays a role and where
accessing information about the hierarchical relationship is important.
For example, a common task can be to find out the descendants or
ancestors of a given hierarchy node or to aggregate values of subtrees.
- [ABAP SQL: Working with Hierarchies](#abap-sql-working-with-hierarchies)
- [Overview](#overview)
- [SQL Hierarchies](#sql-hierarchies)
- [Creating SQL Hierarchies](#creating-sql-hierarchies)
- [ABAP CDS Hierarchies](#abap-cds-hierarchies)
- [ABAP SQL Hierarchy Generator HIERARCHY](#abap-sql-hierarchy-generator-hierarchy)
- [ABAP CTE Hierarchies](#abap-cte-hierarchies)
- [Hierarchy Navigators](#hierarchy-navigators)
- [Hierarchy Node Navigator HIERARCHY\_DESCENDANTS](#hierarchy-node-navigator-hierarchy_descendants)
- [Hierarchy Node Navigator HIERARCHY\_ANCESTORS](#hierarchy-node-navigator-hierarchy_ancestors)
- [Hierarchy Node Navigator HIERARCHY\_SIBLINGS](#hierarchy-node-navigator-hierarchy_siblings)
- [Hierarchy Aggregate Navigators](#hierarchy-aggregate-navigators)
- [Further Information](#further-information)
## Overview
In former times you had to load the data from the database into internal
tables and program it all by yourself (if you did not find an
appropriate API). In between,
[meshes](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenmesh_glosry.htm "Glossary Entry")
offered some features for working with hierarchies, as shown in this
[example](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenmesh_for_reflex_sngl_abexa.htm),
but have not found wide distribution.
Meanwhile, the standard AS ABAP database is a SAP HANA database that
offers a lot of helpful features. Among other things, you will find a
set of hierarchy functions there that allow you to deal with
hierarchical data directly on the database and that you can look up in
the [SAP HANA
documentation](https://help.sap.com/http.svc/ahp2/DRAFT/SAP_S4HANA_ON-PREMISE/2022.000/EN/20/ff532c751910148657c32fe3431a9/frameset.htm).
Now you might expect that you must use
[AMDP](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenamdp.htm)
in order to access these functions from your ABAP programs, but no need
to do so! ABAP SQL and ABAP CDS support hierarchies directly by wrapping
the HANA built-in functions without any loss of performance. You can
stay in the comfortable ABAP world and nevertheless have access to most
modern features. All you have to do, is to understand some concepts and
learn some additional syntax and then you can start right away.
> **💡 Note**<br>
> The examples in this cheat sheet are only relevant for [standard ABAP](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenstandard_abap_glosry.htm), i. e. the unrestricted ABAP language scope. Find the artifacts used in the code snippets in your on-premise system.
## SQL Hierarchies
With [SQL
hierarchy](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensql_hierarchy_glosry.htm "Glossary Entry")
we denote a special [hierarchical data
source](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_data.htm)
that you can use in the `FROM` clause of ABAP SQL queries. A SQL
hierarchy is a tabular set of rows which form the hierarchy nodes of a
hierarchy and which contains additionally [hierarchy
columns](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_column_glosry.htm "Glossary Entry")
that contain hierarchy attributes with hierarchy-specific information
for each row. For creating a SQL hierarchy, you need the following:
- Data Source
This can be any data source you can access normally in an ABAP SQL
query, as most commonly a database table or a CDS view, but also a
CTE (common table expression). The structure and content of the data
source should be able to represent hierarchical data.
- Parent-Child Relation
A parent-child relation must be defined between two or more columns
of the data source. From the parent-child relation and the actual
data of the data source, the SQL hierarchy consisting of parent
nodes and child nodes can be created. The parent-child relation must
be defined by a self-association which we call hierarchy
association. This can be achieved with CDS associations or CTE
associations. A data source exposing a hierarchy association can be
used as a hierarchy source for creating a SQL hierarchy.
- Hierarchy Creation
From a hierarchy source, that is a data source exposing a hierarchy
association, a SQL hierarchy can be created. This can be done either
by defining a CDS hierarchy outside an ABAP program or with the
hierarchy generator of ABAP SQL directly in the `FROM`
clause of an ABAP SQL query inside an ABAP program.
The following topics show you step-by-step how SQL hierarchies can be
created and accessed.
## Creating SQL Hierarchies
### ABAP CDS Hierarchies
With [CDS
hierarchies](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_column_glosry.htm "Glossary Entry"),
you outsource the hierarchy data source and the creation of the SQL
hierarchy from your ABAP program to ABAP CDS. Here the hierarchy is a
fully fledged CDS entity, it is reusable in different programs or in
other CDS entities (views), and can be part of your data model including
access control using CDS DCL. For a CDS hierarchy, the hierarchy source
cannot be anything else but a CDS view that exposes a [hierarchy
association](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_association_glosry.htm "Glossary Entry").
Here is a very simple example for that:
``` abap
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity DEMO_CDS_SIMPLE_TREE_VIEW
  as select from demo_simple_tree
  association [1..1] to DEMO_CDS_SIMPLE_TREE_VIEW as _tree  
    on $projection.parent = _tree.id
{
      _tree,
   key id,
      parent_id as parent,
      name
}
```
This CDS view entity accesses the database table
`DEMO_SIMPLE_TREE`, where the actual data is
stored, and exposes a
[self-association](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenself_association_glosry.htm "Glossary Entry")
`_tree`. The `ON` condition of the association
defines a parent-child relation between the elements `id` and
`parent`. It simply means that a row of the result set where
column `parent` has the same value as the column
`id` of another row is a child of the latter row in the
hierarchy that is constructed from that view. The CDS view exposes also
another column `name` of the database table that represents
the remaining data content. Note that you can define such CDS views for
any available data source and that the `ON` condition can be
more complex than shown in the simple example here.
Now we can use the above CDS view as the hierarchy source of a CDS
hierarchy that can be defined as follows:
``` abap
define hierarchy DEMO_CDS_SIMPLE_TREE
  with parameters
    p_id : abap.int4
  as parent child hierarchy(
    source
      DEMO_CDS_SIMPLE_TREE_SOURCE
      child to parent association _tree
      start where
        id = :p_id
      siblings order by
        id ascending
    )
    {
      id,
      parent,
      name
    }
```
The CDS DDL statement [`DEFINE
HIERARCHY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencds_f1_define_hierarchy.htm)
that can be used in the DDL source code editor of ADT defines a CDS
hierarchy as a CDS entity that can be accessed in CDS views or ABAP SQL
as a SQL hierarchy. The most important additions of the statement are:
- `SOURCE` for specifying the hierarchy source, here our
`DEMO_CDS_SIMPLE_TREE_VIEW`.
- `CHILD TO PARENT ASSOCIATION` for specifying the
hierarchy association, here `_tree`.
- `START WHERE` for defining the root nodes of the SQL
hierarchy, here represented by an input parameter `p_id`
that must be passed when accessing the CDS hierarchy.
- `SIBLINGS ORDER BY` to define also a sort order for
sibling nodes besides the sort order that comes from the
parent-child relationship anyhow.
- An element list `{ ... }` that defines the columns of
the SQL hierarchy, here simply all elements of the hierarchy source.
For a full description and all other additions see [`DEFINE
HIERARCHY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencds_f1_define_hierarchy.htm).
When you access the CDS hierarchy, all lines are selected from the
original data source, in our case the database table
`DEMO_SIMPLE_TREE`, that fulfill the `START WHERE` condition. Those make up the root node set of the SQL
hierarchy. In the simplest case we have exactly one root node, but more
are possible. Then, for each root node, its descendants are retrieved.
That means each line from the database table that fulfills the
`ON`-condition of the hierarchy association is added to the
SQL hierarchy. And for each descendant this is done again and again
until all descendants are found. And that is basically all! Further
additions to `DEFINE HIERARCHY` allow you to control the
creation of the SQL hierarchy, for example, whether multiple parents are
allowed or how orphans or cycles should be handled.
Besides the elements of the hierarchy, the element list can also contain
the hierarchy attributes listed under [Hierarchy
Attributes](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abencds_hierarchy_attributes.htm).
Then the SQL hierarchy is enriched with columns containing information
about the role, the current line plays as a hierarchy node, as, for
example, the hierarchy rank or the hierarchy level. In our example, we
did not add such elements, because ABAP SQL does that implicitly for you
when accessing the CDS hierarchy!
The SQL hierarchy can be used in an ABAP SQL query by using the CDS
hierarchy directly as a data source of the `FROM` clause:
``` abap
DATA root_id type demo_cds_simple_tree_view-id.
...
SELECT FROM demo_cds_simple_tree( p_id = @root_id )
       FIELDS id,
              parent,
              name,
              hierarchy_rank,
              hierarchy_tree_size,
              hierarchy_parent_rank,
              hierarchy_level,
              hierarchy_is_cycle,
              hierarchy_is_orphan,
              node_id,
              parent_id
           INTO TABLE @FINAL(cds_result).
```
And although we did not define any hierarchy attributes in the element
list of the CDS hierarchy, we can add all the hierarchy columns listed
under [Hierarchy
Columns](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenddddl_hierarchy.htm)
to the `SELECT` list of our ABAP SQL statement! This is always
possible when a SQL hierarchy is accessed in ABAP SQL. We can pass any
ID to the CDS hierarchy now and see what happens. If such a line is
found in the database table, the respective hierarchical data will be
retrieved and delivered. Execute class
`CL_DEMO_SQL_HIERARCHIES` for filling the
database table with randomly generated data and inspect the tabular
result. As expected, all elements of the `SELECT` list appear as
columns. Note that the content of column `NAME` could be
anything. It is filled here with a string representation of the path
from the root node to the current node for demonstration purposes only.
From the ABAP language point of view, CDS hierarchies are the most
convenient way of using SQL hierarchies. Now let us turn to other ways,
involving more ABAP, until we do not use any CDS more in the end.
### ABAP SQL Hierarchy Generator HIERARCHY
The ABAP SQL [hierarchy
generator](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_generator_glosry.htm "Glossary Entry")
is a ABAP SQL function named
[`HIERARCHY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_generator.htm),
that allows you to define a SQL hierarchy in the ABAP program itself.
Let us look directly at an example:
``` abap
DATA root_id TYPE demo_cds_simple_tree_view-id.
...
SELECT FROM HIERARCHY( SOURCE demo_cds_simple_tree_view
                       CHILD TO PARENT ASSOCIATION _tree
                       START WHERE id = @root_id
                       SIBLINGS ORDER BY id
                       MULTIPLE PARENTS NOT ALLOWED ) "hierarchy
]
       FIELDS id,
              parent,
              name,
              hierarchy_rank,
              hierarchy_tree_size,
              hierarchy_parent_rank,
              hierarchy_level,
              hierarchy_is_cycle,
              hierarchy_is_orphan,
              node_id,
              parent_id
       INTO TABLE @FINAL(asql_cds_result).
ASSERT asql_cds_result = cds_result.
```
Looks familiar? Well, almost the same syntax used for defining the CDS
hierarchy is used in the brackets `HIERARCHY( ... )` and it
does exactly the same! The difference is the same as it is between ABAP
SQL joins and joins in CDS views:
- If you code it in ABAP SQL, it is for usage in one program only.
- If you code it in ABAP CDS, it is for usage in many programs or
whole data models.
And, as you can see, we dare to prove this with an `ASSERT`
statement. Also note that we use the hierarchy columns again. They exist
implicitly when an SQL hierarchy, here created by the hierarchy
generator, is accessed.
The above hierarchy generator of ABAP SQL accesses the same hierarchy
source as the CDS hierarchy, namely the CDS view
`DEMO_CDS_SIMPLE_TREE_VIEW` that exposes the necessary
hierarchy association `_tree`. In the following code
snippet, we replace the CDS hierarchy source with a CTE:
``` abap
DATA root_id type demo_cds_simple_tree_view-id.
...
WITH
  +cte_simple_tree_source AS
     ( SELECT FROM demo_simple_tree
              FIELDS id,
                     parent_id AS parent,
                     name )
        WITH ASSOCIATIONS (
          JOIN TO MANY +cte_simple_tree_source AS _tree
            ON +cte_simple_tree_source~parent = _tree~id )
  SELECT FROM HIERARCHY( SOURCE +cte_simple_tree_source
                         CHILD TO PARENT ASSOCIATION _tree
                         START WHERE id = @root_id
                         SIBLINGS ORDER BY id
                         MULTIPLE PARENTS NOT ALLOWED ) "hierarchy
]
         FIELDS id,
                parent,
                name,
                hierarchy_rank,
                hierarchy_tree_size,
                hierarchy_parent_rank,
                hierarchy_level,
                hierarchy_is_cycle,
                hierarchy_is_orphan,
                node_id,
                parent_id
         INTO TABLE @FINAL(asql_cte_result). ]
ASSERT asql_cte_result = cds_result.
```
Common table expressions (CTEs) are a very powerful tool for defining
subqueries that can be used in subsequent queries of the same
[`WITH`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapwith.htm)
statement. They can be regarded as an internal ABAP SQL definition of
data sources that fulfill the same functionality as program external
data sources, especially CDS views. As you see above, the CTE
`cte_simple_tree_source` does the same as the CDS view
`DEMO_CDS_SIMPLE_TREE_VIEW`:
- It accesses the database table `DEMO_SIMPLE_TREE`.
- It exposes an association `_tree` by using the addition
[`WITH ASSOCIATIONS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapwith_associations.htm).
The main query of the `WITH` statement uses the hierarchy
generator in the same way as the `SELECT` above, just with the
CTE as a data source instead of the CDS view and the result is - of
course - the same.
For a full description of the hierarchy generator and all other
additions see [`SELECT, FROM HIERARCHY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_generator.htm).
We managed to create a SQL hierarchy with ABAP SQL means only. Last but
not least we will use CTEs as hierarchies themselves. You might skip the
following section and turn directly to the hierarchy navigators if you
are not too interested in this syntactic gimmicks.
### ABAP CTE Hierarchies
A CTE that produces hierarchical data can declare itself as a SQL
hierarchy of a freely defined name with the addition [`WITH HIERARCHY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapwith_hierarchy.htm).
That simply means that subsequent queries of the same `WITH`
statement can use the CTE as a hierarchy with its implicit hierarchy
columns or - more important - in hierarchy navigators.
The following code snippets show the three ways in which a CTE can
produce hierarchical data:
``` abap
DATA root_id TYPE demo_cds_simple_tree_view-id.
...
WITH
      +tree AS
        ( SELECT FROM demo_cds_simple_tree( p_id = @root_id )
                 FIELDS * )
          WITH HIERARCHY demo_cds_simple_tree
      SELECT FROM  +tree "hierarchy ]
             FIELDS id,
                    parent,
                    name,
                    hierarchy_rank,
                    hierarchy_tree_size,
                    hierarchy_parent_rank,
                    hierarchy_level,
                    hierarchy_is_cycle,
                    hierarchy_is_orphan,
                    node_id,
                    parent_id
             INTO TABLE @FINAL(cte_cds_result).
...
WITH
      +tree AS
        ( SELECT FROM HIERARCHY(
            SOURCE demo_cds_simple_tree_view
            CHILD TO PARENT ASSOCIATION _tree
            START WHERE id = @root_id
            SIBLINGS ORDER BY id
            MULTIPLE PARENTS NOT ALLOWED ) AS asql_hierarchy
            FIELDS id,
                   parent,
                   name )
          WITH HIERARCHY asql_hierarchy
      SELECT FROM +tree "hierarchy ]
             FIELDS id,
                    parent,
                    name,
                    hierarchy_rank,
                    hierarchy_tree_size,
                    hierarchy_parent_rank,
                    hierarchy_level,
                    hierarchy_is_cycle,
                    hierarchy_is_orphan,
                    node_id,
                    parent_id
             INTO TABLE @FINAL(cte_asql_result).
...
WITH
      +cte_simple_tree_source AS
        ( SELECT FROM demo_simple_tree
                 FIELDS id,
                        parent_id AS parent,
                        name )
           WITH ASSOCIATIONS (
             JOIN TO MANY +cte_simple_tree_source AS _tree
               ON +cte_simple_tree_source~parent = _tree~id ),
      +tree AS
        ( SELECT FROM HIERARCHY(
            SOURCE +cte_simple_tree_source
            CHILD TO PARENT ASSOCIATION _tree
            START WHERE id = @root_id
            SIBLINGS ORDER BY id
            MULTIPLE PARENTS NOT ALLOWED ) AS cte_hierarchy
            FIELDS id,
                   parent,
                   name  )
            WITH HIERARCHY cte_hierarchy
      SELECT FROM +tree "hierarchy ]
             FIELDS id,
                    parent,
                    name,
                    hierarchy_rank,
                    hierarchy_tree_size,
                    hierarchy_parent_rank,
                    hierarchy_level,
                    hierarchy_is_cycle,
                    hierarchy_is_orphan,
                    node_id,
                    parent_id
             INTO TABLE @FINAL(cte_cte_result).
ASSERT cte_cds_result  = cds_result.
ASSERT cte_asql_result = cds_result.
ASSERT cte_cte_result  = cds_result.
```
A CTE that is exposed as a SQL hierarchy must access a SQL hierarchy
itself and in the end these are always based on a CDS hierarchy or the
ABAP SQL hierarchy generator as shown above. Again, the hierarchy source
of the hierarchy generator can be a CDS view or a CTE exposing the
hierarchy association. Running
`CL_DEMO_SQL_HIERARCHIES` shows that all
assertions are fulfilled.
## Hierarchy Navigators
[Hierarchy
navigators](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_navigator_glosry.htm "Glossary Entry")
are an additional set of [hierarchy
functions](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_function_glosry.htm "Glossary Entry")
in ABAP SQL that allow you to work on existing SQL hierarchies instead
of creating them. Hierarchy navigators can work on SQL hierarchies
created as shown above, namely on CDS hierarchies, the hierarchy
generator or a CTE hierarchy. They can be used as data sources in ABAP
SQL queries. If you need a SQL hierarchy multiple times, from a
performance point of view it is best to create it once with a given set
of root nodes and then access it with hierarchy navigators. Furthermore,
each hierarchy navigator can add further hierarchy columns to the result
set that offer additional options for the evaluation.
In the following examples, we access our CDS hierarchy with hierarchy
navigators. But you could also replace it with the hierarchy generator
or a CTE hierarchy. Check the examples of the
[documentation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_navigators.htm),
where this is also shown.
### Hierarchy Node Navigator HIERARCHY_DESCENDANTS
As the name says,
[`HIERARCHY_DESCENDANTS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_node_navis.htm)
fetches all descendants for any nodes from a SQL hierarchy. It adds
`HIERARCHY_DISTANCE` as an additional hierarchy column to
the result set. Let us look at an example. All examples are code
snippets from `CL_DEMO_SQL_HIERARCHIES` again.
``` abap
DATA root_id TYPE demo_cds_simple_tree_view-id.
DATA sub_id TYPE demo_cds_simple_tree_view-id.
...
SELECT FROM HIERARCHY_DESCENDANTS(
              SOURCE demo_cds_simple_tree( p_id = @root_id )
              START WHERE id = @sub_id  )
  FIELDS id,
         parent_id,
         name,
         hierarchy_distance
  INTO TABLE @FINAL(descendants).
```
Our CDS hierarchy `DEMO_CDS_SIMPLE_TREE_VIEW` is used to
create a SQL hierarchy with a start node passed to parameter
`p_id` and for a node `sub_id` all descendants
are fetched. Running the program shows the result including the
additional column `HIERARCHY_DISTANCE` that contains the
distance to the respective start node. A further parameter
`DISTANCE` - not shown here - allows you to restrict the
distance to the respective start node.
### Hierarchy Node Navigator HIERARCHY_ANCESTORS
Now the other way around: ABAP SQL function
[`HIERARCHY_ANCESTORS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_node_navis.htm)
returns the ancestors of any given node of an existing hierarchy:
``` abap
DATA root_id TYPE demo_cds_simple_tree_view-id.
DATA max_id TYPE demo_cds_simple_tree_view-id.
...
SELECT FROM HIERARCHY_ANCESTORS(
              SOURCE demo_cds_simple_tree( p_id = @root_id )
              START WHERE id = @max_id )
  FIELDS id,
          parent_id,
          name,
          hierarchy_distance
  INTO TABLE @FINAL(ancestors).
```
Looking at the result when running
`CL_DEMO_SQL_HIERARCHIES`, you see that the
value of column `HIERARCHY_DISTANCE` is negative now. Using
aggregate functions or evaluating the internal result table, you can now
easily extract further information like the number of ancestors and so
on.
### Hierarchy Node Navigator HIERARCHY_SIBLINGS
Besides descendants and ancestors, hierarchy nodes also can have
siblings, that is nodes that have the same parent node. You can find
these by looking for all nodes with the same value in hierarchy column
`HIERARCHY_PARENT_RANK`. But there is also
[`HIERARCHY_SIBLINGS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_node_navis.htm)
as a hierarchy function for that:
``` abap
DATA root_id TYPE demo_cds_simple_tree_view-id.
DATA sibl_id TYPE demo_cds_simple_tree_view-id.
...
SELECT FROM HIERARCHY_SIBLINGS(
              SOURCE demo_cds_simple_tree( p_id = @root_id )
              START WHERE id = @sibl_id )
  FIELDS id,
          parent_id,
          name,
          hierarchy_sibling_distance
  INTO TABLE @FINAL(siblings).
```
You see that this function adds another hierarchy column
`HIERARCHY_SIBLING_DISTANCE` that contains the distance to
the respective start node. Running
`CL_DEMO_SQL_HIERARCHIES`, where we start with
a node that definitely has some siblings, shows the result.
### Hierarchy Aggregate Navigators
Finally let us turn to the [hierarchy aggregate
navigators](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenhierarchy_agg_navi_glosry.htm "Glossary Entry")
that allow you to apply some aggregate functions to descendants and
ancestors of any node of a SQL hierarchy:
- [`HIERARCHY_DESCENDANTS_AGGREGATE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_desc_agg.htm)
- [`HIERARCHY_ANCESTORS_AGGREGATE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_ancs_agg.htm)
We will show an example for the descendants case and refer to the
[documentation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_ancs_agg.htm)
for the ancestors.
Applying aggregate functions to columns normally means that you have
some data there for which this makes sense. In our simplistic SQL
hierarchy tree we do not have such meaningful data. On the other hand,
this can also be a use case: You can have the administrative data for
the parent-child relation in one database table and the real data in
another one. And for that use case, the hierarchy aggregate navigator
`HIERARCHY_DESCENDANTS_AGGREGATE` gives you the option of
joining such data to your SQL hierarchy:
``` abap
TYPES:
  BEGIN OF value,
    id     TYPE i,
    amount TYPE p LENGTH 16 DECIMALS 2,
  END OF value.
DATA value_tab TYPE SORTED TABLE OF value WITH UNIQUE KEY id.
DATA root_id TYPE demo_cds_simple_tree_view-id.
DATA sub_id TYPE demo_cds_simple_tree_view-id.
...
SELECT FROM HIERARCHY_DESCENDANTS_AGGREGATE(
              SOURCE demo_cds_simple_tree( p_id = @sub_id  ) AS h
              JOIN @value_tab AS v
                ON  v~id = h~id
              MEASURES SUM( v~amount ) AS amount_sum
              WHERE hierarchy_rank > 1
              WITH SUBTOTAL
              WITH BALANCE )
  FIELDS id,
         amount_sum,
         hierarchy_rank,
         hierarchy_aggregate_type
  INTO TABLE @FINAL(descendants_aggregate).
```
In our example, we join an internal table `value_tab` of the
same program to the SQL hierarchy. In a real life example you would join
another database table, of course. On the other hand the example shows
ABAP SQL's capability of using internal tables as data sources. You
even can go so far to evaluate hierarchical data in internal tables with
ABAP SQL by using an internal table as data source for a CTE hierarchy!
The example does the following:
- We use the hierarchy aggregate navigator
`HIERARCHY_DESCENDANTS_AGGREGATE` as a data source of a
`FROM` clause.
- Our CDS hierarchy `DEMO_CDS_SIMPLE_TREE_VIEW` joined
with internal table `value_tab` is used as the data source.
- The ABAP SQL function returns a tabular result of nodes of the data
source.
- The aggregate function `SUM` behind `MEASURES` sums
up the values of the column amounts of the joined internal table for
all descendants of each node returned by the ABAP SQL function.
- The `WHERE` condition restricts the result set by a freely
programmable condition.
- The `WITH` additions add further rows to the result set that
can be recognized by values in an additional hierarchy column
`HIERARCHY_AGGREGATE_TYPE`:
- `WITH SUBTOTAL`
In the row where `HIERARCHY_AGGREGATE_TYPE` has
value 1, column `AMOUNT_SUM` contains the sum of the
values of all hierarchy nodes that meet the `WHERE`
condition.
- `WITH BALANCE`
In the row where `HIERARCHY_AGGREGATE_TYPE` has
value 2, column `AMOUNT_SUM` contains the sum of the
values of all hierarchy nodes that do not meet the
`WHERE` condition.
For more `WITH` additions see the
[documentation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_desc_agg.htm).
Running `CL_DEMO_SQL_HIERARCHIES` shows the
result. It also shows the result of the joined data source, where you
can check that the calculated values are correct.
## Further Information
For the complete reference documentation about SQL hierarchies, see [`SELECT, FROM hierarchy_data`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenselect_hierarchy_data.htm).

View File

@@ -0,0 +1,171 @@
<a name="top"></a>
# ABAP SQL: Grouping Internal Tables
- [ABAP SQL: Grouping Internal Tables](#abap-sql-grouping-internal-tables)
- [Introduction](#introduction)
- [Grouping by One Column](#grouping-by-one-column)
- [Grouping by More than One Column](#grouping-by-more-than-one-column)
- [Group Key Binding when Grouping by One Column](#group-key-binding-when-grouping-by-one-column)
- [Group Key Binding when Grouping by More than One Column](#group-key-binding-when-grouping-by-more-than-one-column)
- [Executable Example](#executable-example)
## Introduction
Similar to SQL's [`GROUP BY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapgroupby_clause.htm),
there is also a [`GROUP BY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by.htm)
for working with internal tables that can be used behind [`LOOP AT itab`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_variants.htm)
or in the form [`IN GROUP`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfor_in_group.htm)
in a table iteration with
[`FOR`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abenfor_itab.htm).
It replaces the clumsy group level processing with statements [`AT NEW ...`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abapat_itab.htm)
that relies on the order of table columns and content that is sorted
respectively.
Thi cheat sheet explains the grouping of internal tables step by step
using a very simple case of an internal table `spfli_tab` that
is filled with data from the database table `SPFLI`. The
following steps show how the content of the internal table can be
grouped using [`LOOP AT GROUP BY`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by.htm).
## Grouping by One Column
The simplest form of grouping is by one column without explicitly
specifying the output behavior of the group loop:
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY wa-carrid.
       ... wa-carrid ...
ENDLOOP.
```
Within the loop, there is access to the work area `wa`, in
particular to the component `wa-carrid` that is used for
grouping. The work area `wa` contains the first line of each
group and represents the group in the loop. This is called
representative binding.
To access the members of a group, a member loop can be inserted into the
group loop:
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY wa-carrid.
  ...
  LOOP AT GROUP wa INTO DATA(member).
    ... member-... ...
  ENDLOOP.
  ...
ENDLOOP.
```
The member loop is executed using the group represented by `wa`
and its members are assigned to `member` and are available in
the member loop.
## Grouping by More than One Column
To group by more than just one criterion, a structured group key is
defined as follows. In the simplest case, the grouping criteria are
columns of the internal table:
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom ).
  ... wa-carrid ... wa-airpfrom ...
ENDLOOP.
```
This is also a representative binding in which the work area
`wa` is reused in the group loop to access the group key.
To access the members of the groups, the exact same member loop can be
inserted as when grouping by one column.
## Group Key Binding when Grouping by One Column
By explicitly specifying an [output
area](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by_binding.htm)
for the group key, a group key binding can be defined explicitly instead
of the representative binding in which the output area of the group loop
is reused:
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY wa-carrid
                  INTO DATA(key).
  ... key ...
ENDLOOP.
```
The difference to the example with representative binding is the
`INTO` addition after `GROUP BY`. Instead of reusing
`wa`, an elementary data object `key` represents the
group. This can be generated inline. The additions [`GROUP
SIZE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by_key.htm),
[`GROUP
INDEX`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by_key.htm),
and [`WITHOUT
MEMBERS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by.htm)
can only be used in the group key binding, which gives it more functions
than the representative binding. If these are not required, the
representative binding can be used. The group key binding can also be
used to make the use of the group key in the loop more explicit.
Inserting a member loop works in the same way as in the representative
binding, with the difference that a group is now addressed by
`key` instead of `wa`.
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY wa-carrid
                  INTO key.
  ...
  LOOP AT GROUP key INTO member.
    ... members ...
  ENDLOOP.
  ...
ENDLOOP.
```
## Group Key Binding when Grouping by More than One Column
Finally, the group key binding for structured group keys:
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom )
                  INTO DATA(key).
  ... key-key1 ... key-key2 ...
ENDLOOP.
```
Here, `key` is a structure with the components `key1`
and `key2`. A member loop can be inserted in exactly the same
way as when grouping by one column.
If the group members are not relevant, the addition [`NO
MEMBERS`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by.htm)
can be used to save time and memory.
``` abap
LOOP AT spfli_tab INTO wa
                  GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom
                             index = GROUP INDEX size = GROUP SIZE )
                  WITHOUT MEMBERS
                  INTO DATA(key).
  ... key-key1 ... key-key2 ... key-index ... key-size ...
ENDLOOP.
```
It is no longer possible to use a member loop here. Instead, the group
key was enriched with optional components for further information using
[`GROUP
INDEX`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by_key.htm)
[`GROUP
SIZE`](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abaploop_at_itab_group_by_key.htm).
## Executable Example
[zcl_demo_abap_sql_group_by](./src/zcl_demo_abap_sql_group_by.clas.abap)
Note the steps outlined [here](README.md#🎬-getting-started-with-the-examples) about how to import and run the code.

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

73
LICENSES/Apache-2.0.txt Normal file
View File

@@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

206
README.md Normal file
View File

@@ -0,0 +1,206 @@
<br />
<div align="center">
<a href="https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap.htm">
<img src="./files/ABAP_Keyword_Documentation.png" alt="ABAP Keyword Documentation" >
</a>
<h3 align="center" style="font-size: 40px; color: #FCB913;">ABAP Cheat Sheets</h3>
<p align="center">
Explore ABAP syntax in a nutshell & executable examples
<br />
<!--<a href=""><strong>Expore ABAP syntax in a nutshell & executable examples</strong></a>
<br />-->
<br />
<a href="#🏗️-how-to-use">How to Use</a>
·
<a href="#📝-abap-cheat-sheets-overview">Cheat Sheets</a>
·
<a href="#🎬-getting-started-with-the-examples">Examples</a>
</p>
</div>
<br>
<hr>
<br>
ABAP cheat sheets[^1] ...
- provide a **collection of information on selected ABAP topics** in a nutshell for your reference.
- focus on **ABAP syntax**.
- include **code snippets**.
- are supported by easy-to-consume **demonstration examples** that you can import into your [SAP BTP ABAP environment](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm?file=abensap_btp_abap_env_glosry.htm) or on-premise ABAP system using [abapGit](https://abapgit.org/) to run and check out ABAP syntax in action in simple contexts.
- are enriched by links to glossary entries and chapters of the **ABAP Keyword Documentation** (the *F1 help*) for you to deep dive into the respective ABAP topics and get more comprehensive information.
<details>
<summary>💡 Note</summary>
<br>
- Since the ABAP cheat sheets provide information in a nutshell, they do not claim to be exhaustive as far as the described syntax and concepts are concerned. If you want to go more into the details, just consult the ABAP Keyword Documentation, for example, by choosing `F1` for a keyword in your code or directly researching via the online version or the system-internal version.
- If not stated otherwise in the cheat sheets and examples, the content of this repository is relevant for these ABAP language versions:
- [ABAP for Cloud Development](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap_for_sap_cloud_glosry.htm): Restricted ABAP language scope for developments in the [SAP BTP ABAP environment](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abensap_btp_abap_env_glosry.htm) → [Online version of the documentation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm)
- [Standard ABAP](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenstandard_abap_glosry.htm): Unrestricted ABAP language scope, for example, for developments in an on-premise ABAP system → [Online version of the documentation (latest version)](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap.htm)
- Check the [Known Issues](#⚡-known-issues) and [Disclaimer](#⚠️-disclaimer).
- In the cheat sheets, links are available to glossary entries and topics of the ABAP Keyword Documentation. Note that these links refer to the ABAP for Cloud Development version in most cases.
</details>
<br>
## 🏗️ How to Use
1. **ABAP syntax info**: Get info in a nutshell on ABAP syntax and concepts related to various ABAP topics in the [ABAP cheat sheets](#📝-abap-cheat-sheets-overview).
2. **Demo examples**: Import the ABAP development objects of this repository into your system using [abapGit](https://abapgit.org/) as described [here](#🎬-getting-started-with-the-examples) and run the demo classes by choosing `F9` in the [ABAP Development Tools (ADT)](https://tools.eu1.hana.ondemand.com/) for checking out the ABAP syntax in action.
## 📝 ABAP Cheat Sheets Overview
| Cheat Sheet | Topics Covered | Demo Example |
| ------------- | ------------- | ----- |
|[Working with Internal Tables](01_Internal_Tables.md)| Creating, filling, reading from, sorting, modifying internal tables | [zcl_demo_abap_internal_tables](./src/zcl_demo_abap_internal_tables.clas.abap) |
|[Working with Structures](02_Structures.md)| Creating structures and structured types, variants of structures, accessing components of structures, filling structures, clearing structures, structures in use in the context of tables | [zcl_demo_abap_structures](./src/zcl_demo_abap_structures.clas.abap) |
|[ABAP SQL: Working with Persisted Data in Database Tables](03_ABAP_SQL.md)| Reading from database tables using `SELECT`, changing data in database tables using `INSERT`, `UPDATE`, `MODIFY` and `DELETE` | [zcl_demo_abap_sql](./src/zcl_demo_abap_sql.clas.abap) |
|[ABAP Object Orientation](04_ABAP_Object_Orientation.md)| Working with objects and components, concepts like inheritance, interfaces, and more | [zcl_demo_abap_objects](./src/zcl_demo_abap_objects.clas.abap) |
|[Working with Constructor Expressions](05_Constructor_Expressions.md)| Operators `VALUE`, `CORRESPONDING`, `NEW`, `CONV`, `EXACT`, `REF`, `CAST`, `COND`, `SWITCH`, `FILTER`, `REDUCE`, iteration expressions with `FOR`, `LET` expressions | [zcl_demo_abap_constructor_expr](./src/zcl_demo_abap_constructor_expr.clas.abap) |
|[Dynamic Programming](06_Dynamic_Programming.md)| Touches on field symbols and data references as supporting elements for dynamic programming, dynamic ABAP syntax components, runtime type services (RTTS), i. e. runtime type identification (RTTI) and runtime type creation (RTTC) | [zcl_demo_abap_dynamic_prog](./src/zcl_demo_abap_dynamic_prog.clas.abap) |
|[String Processing](07_String_Processing.md)| Creating strings and assigning values, chaining strings, string templates, concatenating, splitting, modifying strings, searching and replacing, regular expressions | [zcl_demo_abap_string_proc](./src/zcl_demo_abap_string_proc.clas.abap) |
|[ABAP for RAP: Entity Manipulation Language (ABAP EML)](08_EML_ABAP_for_RAP.md)| Setting EML in the context of RAP, standard (create, read, update, delete) and non-standard operations (actions) | <ul><li>[Demo RAP scenario with a managed RAP BO, external numbering (zcl_demo_abap_rap_ext_num_m)](./src/zcl_demo_abap_rap_ext_num_m.clas.abap)</li><br><li>[Demo RAP scenario with an unmanaged RAP BO, external numbering (zcl_demo_abap_rap_ext_num_u)](./src/zcl_demo_abap_rap_ext_num_u.clas.abap)</li><br><li>[Demo RAP scenario ("RAP calculator") with a managed, draft-enabled RAP BO, late numbering (zcl_demo_abap_rap_draft_ln_m)](./src/zcl_demo_abap_rap_draft_ln_m.clas.abap) <br>Note that this example can also be checked out using the preview version of an SAP Fiori UI. Check the comments in the class for the steps.</li></ul> |
|[Excursion Down to Bits and Bytes](09_Bits_and_Bytes.md)|Touches on the technical background of data types and data objects|-|
|[ABAP SQL: Working with Hierarchies](10_ABAP_SQL_Hierarchies.md)|Summarizes the functions ABAP SQL offers together with ABAP CDS for working with hierarchical data that is stored in database tables|-|
|[ABAP SQL: Grouping Internal Tables](11_ABAP_SQL_Grouping_Internal_Tables.md)|Touches on the `GROUP BY` clause in ABAP SQL|[zcl_demo_abap_sql_group_by](./src/zcl_demo_abap_sql_group_by.clas.abap)
## 🎬 Getting Started with the Examples
The executable examples are especially targeted at being imported into the SAP BTP ABAP environment, however, they are basically fit for both on-premise systems and the SAP BTP ABAP environment (that's why there are no ABAP programs included). Hence, check the info in the following collapsible sections for your system environment and carry out the prerequisite steps.
<details>
<summary>1) General info</summary>
<br>
- A few **DDIC artifacts**, for example, database tables, are part of the repository. They are used by the examples to ensure self-contained examples. For all examples to work, all artifacts must be imported.
- All examples are designed to **display some output in the ADT console**. Once successfully imported, you can **execute** the examples in ADT by choosing `F9` to display the output in the ADT console.
- The examples **include descriptions and comments** in the code for providing explanations and setting the context.
</details>
<details>
<summary>2a) SAP BTP ABAP environment</summary>
<br>
**Prerequisites**
- [x] Before importing the code, you have made a system-wide search for, for example, classes named `ZCL_DEMO_ABAP*` so as not to run into issues when you try to import the code. If someone has already imported the content in the system, you can simply check out that imported version and proceed with the step *3) Run the code*.
- [x] You have access to an SAP BTP ABAP Environment instance (see [here](https://blogs.sap.com/2018/09/04/sap-cloud-platform-abap-environment) for additional information).
- [x] You have downloaded and installed ABAP Development Tools (ADT). Make sure that you use the most recent version as indicated on the [installation page](https://tools.hana.ondemand.com/#abap).
- [x] You have created an ABAP cloud project in ADT that allows you to access your SAP BTP ABAP Environment instance (see [here](https://help.sap.com/viewer/5371047f1273405bb46725a417f95433/Cloud/en-US/99cc54393e4c4e77a5b7f05567d4d14c.html) for additional information). Your logon language is English.
- [x] You have installed the [abapGit](https://github.com/abapGit/eclipse.abapgit.org) plug-in for ADT from the [update site](http://eclipse.abapgit.org/updatesite/).
**Import Code**
Use the abapGit plug-in to install the <em>ABAP Cheat Sheets</em> by carrying out the following steps:
1. In your ABAP cloud project, create a package, for example, `ZABAP_CHEAT_SHEETS` as target package. It is recommended that you assign the package to a transport request suitable for demo content.
2. Add the package to the *Favorite Packages* in the *Project Explorer* view in ADT.
3. To add the <em>abapGit Repositories</em> view to the <em>ABAP</em> perspective, choose `Window``Show View``Other...` from the menu bar and choose `abapGit Repositories`.
4. On the <em>abapGit Repositories</em> view, click the `+` icon in the top right corner of the ADT tab to link a new abapGit repository.
<br>![ADT](./files/abapGit_Repositories.png)
5. The *Link abapGit Repository* pop-up is displayed. Insert the following URL:
```
https://github.com/SAP-samples/abap-cheat-sheets.git
```
6. Choose `Next`.
7. On the *Branch and Package Selection* screen, insert the name of the created package (e. g. `ZABAP_CHEAT_SHEETS`) in the `Package` field.
8. Choose `Next`.
9. On the *Select Transport Request* screen, select the created transport request suitable for demo content and choose `Finish` to link the Git repository to your ABAP cloud project. If the created package is already assigned to a transport request for the demo content and a message that an object is already locked in a transport request is displayed, choose `Finish`, too.
10. In the *abapGit Repositories* view, filter for your package. The repository appears in the *abapGit Repositories* view with status <em>Linked</em>.
11. Right-click the new abapGit repository and choose `Pull...` to start the cloning of the repository contents.
12. On the *Branch and Package Selection* screen, choose `Next`.
13. If the *Locally Modified Object* screen is displayed, select the objects (for example, the package to automatically select all artifacts) in the list and choose `Next`.
14. On the next screen, select a transport request and choose `Finish`. Same as above, if an *object already locked* message is displayed, choose `Finish`, too. The status in the *abapGit Repositories* view changes to <em>Pull running...</em>. Note that the pull run may take a few minutes.
15. Once the cloning has finished, the status is set to `Pulled Successfully`. You might need to refresh the `abapGit Repositories` view to see the progress of the import. To do so, choose the icon for refreshing (`Refresh`) in the top right corner of the view.
16. Refresh your project tree. E. g. in ADT, right-click the package and choose `Refresh` or `F5`. The package should contain all artifacts from the GitHub repository.
17. Make sure that all artifacts are active. To activate all inactive development objects, choose the `Activate all inactive ABAP development objects` button from the menu (or choose `CTRL+Shift+F3`).
</details>
<details>
<summary>2b) Application Server ABAP On-Premise</summary>
<br>
**Prerequisites**
- [x] The assumption is that you are on the latest [ABAP release](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abennews-75.htm). The content was also tested with release 7.56.
- [x] Before importing the code, you have made a system-wide search for, for example, classes named `ZCL_DEMO_ABAP*` so as not to run into issues when you try to import the code. If someone has already imported the content in the system, you can simply check out that imported version and proceed with the step *3) Run the code*.
- [x] You have downloaded and installed ABAP Development Tools (ADT). Make sure that you use the most recent version as indicated on the [installation page](https://tools.hana.ondemand.com/#abap).
- [x] You have created an ABAP Project in ADT that allows you to access your Application Server as mentioned above. Your logon language is English.
- [x] You have downloaded and installed the standalone version of the abapGit report. Make sure that you use the most recent version as indicated on the [installation page](https://docs.abapgit.org/). You can create a report, for example, `zabapgit_standalone` and copy and paste [this code](https://raw.githubusercontent.com/abapGit/build/main/zabapgit_standalone.prog.abap) into the program.
- [x] You have installed the certificate files for github.com, see [abapGit Documentation](https://docs.abapgit.org/guide-ssl-setup.html).
**Import Code**
Use the standalone version of the abapGit report to import the demo examples of the <em>ABAP Cheat Sheets</em> by carrying out the following steps:
1. In your ABAP project, create a package, for example, `TEST_ABAP_CHEAT_SHEETS` as target package suitable for demo content (e. g. by using `LOCAL` as software component).
2. Add the package to the *Favorite Packages* in the *Project Explorer* view in ADT.
3. Run the standalone version of the abapGit report.
4. Choose the `New Online` button. If the button is not available, for example, if another repository is already opened, choose the `Repository List` button.
5. On the *New Online Repository* screen, make the following entries:
- `Git Repository URL`:
```
https://github.com/SAP-samples/abap-cheat-sheets.git
```
- `Package`: Your demo package, for example, `TEST_ABAP_CHEAT_SHEETS`
6. Leave the other fields unchanged and choose `Create Online Repo`.
7. On the *Repository* screen, you will see the available ABAP artifacts to be imported into your ABAP system.
8. Choose the `Pull` button. The import of the artifacts is triggered. It might take some minutes.
9. If the `Inactive Objects` pop-up is displayed, select all artifacts and choose `Continue` (✔️).
10. Once the cloning has finished, refresh your project tree. E. g. in ADT, right-click the package and choose `Refresh` or `F5`. The package should contain all artifacts from the GitHub repository.
11. Make sure that all artifacts are active. To activate all inactive development objects, choose the `Activate all inactive ABAP development objects` button from the (or choose `CTRL+Shift+F3`).
</details>
<details>
<summary>3) Run the code</summary>
<br>
- Open your created package containing the imported ABAP artifacts in the ABAP Development Tools (ADT).
- Open an ABAP cheat sheet example class as listed in the [ABAP Cheat Sheets Overview](#📝-abap-cheat-sheets-overview) section, for example, `zcl_demo_abap_string_proc`. The classes are contained in folder `Source Code Library` → `Classes`.
- Choose `F9` to run the class. Alternatively, choose `Run` → `Run As` → `2 ABAP Application (Console)` from the menu.
- Check the console output.
> **💡 Note**<br>
>- Check notes on the context and the ABAP syntax used included in the class as comments.
>- Due to the amount of output in the console, the examples include numbers (e. g. 1) ..., 2) ..., 3) ...) representing the header of the individual example code sections. Plus, the variable name is displayed in the console in most cases. Hence, to easier and faster find the relevant output in the console, just search in the console for the number (e. g. search for `3)` for the particular output) or variable name (`STRG+F` in the console) or use break points in the code to check variables in the debugger.
>- You might want to clear the console by making a right-click within the console and choosing `Clear` before running another demo class so as not to confuse the output of multiple classes.
</details>
<br>
## ⚡ Known Issues
- Only one user on the system may import this repository as all object names must be globally unique. If you receive an error that the objects already exist when trying to import, search the system for classes named `ZCL_DEMO_ABAP*`. Someone has already imported the content in the system and you can simply check out that imported version.
- Since the repository contains self-contained examples, i. e. they work, for example, with demo database tables included in the repository (note that these tables are filled in the course of method executions), all demo artifacts must be imported so that all examples work.
- For the import into an on-premise system, note the following: The demos cover ABAP syntax irrespective of the ABAP release so as not to scatter information and to have the info in one go. Hence, there may be syntax that is not yet available with the ABAP version of your on-premise system. In that case, you might want to comment out affected code sections if an activation fails.
- Regarding potential code check warnings, for example, for the many strings in the code, not using an `ORDER BY` clause or messages regarding using `SELECT *`, the code purposely renounces pragmas and pseudo comments to keep the code fairly simple and to focus on the available ABAP syntax. See also the [Disclaimer](#⚠️-disclaimer).
## 🛈 Further Information
- Regarding the system-internal version of the ABAP Keyword Documentation in your
- ... **on-premise system**: Access the documentation in SAP GUI via the transactions `ABAPDOCU` (opens the documentation directly) and `ABAPHELP` (opens an input field with which you can search the documentation content, for example, you can search for a keyword like `SELECT`). Or, certainly, in your code, choose `F1` for a keyword. If you are in SAP GUI (e. g. in `SE80`), the system-internal version is opened. If you are in ADT, the documentation is opened in the *ABAP Language Help* view.
- ... **SAP BTP ABAP environment**: In ADT, you find the documentation in the *ABAP Language Help* view where you can also search. When choosing `F1` for a keyword in your code, the documentation is opened there accordingly.
- Links to the online version of the ABAP Keyword Documentation for:
- **Standard ABAP**: Unrestricted ABAP language scope, for example, for developments in an on-premise ABAP system → [Online version of the documentation (latest version)](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap.htm)
- **ABAP for Cloud Development**: Restricted ABAP language scope for developments in the SAP BTP ABAP environment → [Online version of the documentation](https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/index.htm)
- Regarding demonstration examples of the ABAP Keyword Documentation in your on-premise system: Have you ever checked out the package `SABAPDEMOS`? This package contains all the examples used in the ABAP Keyword Documentation. To get the context, program names etc., check out the [example page](https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/index.htm?file=abenabap_examples.htm) (which is also available in the system-internal SAP GUI version as node in the topic tree) summarizing executable examples. Certainly, you also find the example topics in the context of the individual ABAP Keyword Documentation topic. The example topics have a ⚙️ sign:
![](./files/example_topics.png)
- See [this blog](https://blogs.sap.com/2021/04/28/video-tutorials-on-how-to-use-the-abap-keyword-documentation-abap-f1-help/) for videos about the ABAP Keyword Documentation on the [Help Portal](https://www.youtube.com/watch?v=a4ckF1XkfG8), in [SAP GUI](https://www.youtube.com/watch?v=fsX-085MlD8) and in [ADT](https://www.youtube.com/watch?v=hNGEYFpWwh0).
## ⚠️ Disclaimer
The code examples presented in this repository are only syntax examples and are not intended for direct use in a production system environment. The code examples are primarily intended to provide a better explanation and visualization of the syntax and semantics of ABAP statements and not to solve concrete programming tasks. For production application programs, a dedicated solution should therefore always be worked out for each individual case.
SAP does not guarantee either the correctness or the completeness of the code. In addition, SAP takes no legal responsibility or liability for possible errors or their consequences, which occur through the use of the example programs.
## 📟 How to Obtain Support
This project is provided "as-is": there is no guarantee that raised issues will be answered or addressed in future releases.
## 📜 License
Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This project is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE](LICENSE) file.
[^1]: "A written [...] aid (such as a sheet of notes) that can be referred to for help in understanding or remembering something complex" (Definition for "cheat sheet" in Merriam-Webster Dictionary).

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
files/example_topics.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_ENQU" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD25V>
<VIEWNAME>EZDEMO_ABAP_LOCK</VIEWNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<AGGTYPE>E</AGGTYPE>
<ROOTTAB>ZDEMO_ABAP_RAPT1</ROOTTAB>
<DDTEXT>Lock on demo table</DDTEXT>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD25V>
<DD26E_TABLE>
<DD26E>
<VIEWNAME>EZDEMO_ABAP_LOCK</VIEWNAME>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<TABPOS>0001</TABPOS>
<FORTABNAME>ZDEMO_ABAP_RAPT1</FORTABNAME>
<ENQMODE>E</ENQMODE>
</DD26E>
</DD26E_TABLE>
<DD27P_TABLE>
<DD27P>
<VIEWNAME>EZDEMO_ABAP_LOCK</VIEWNAME>
<OBJPOS>0001</OBJPOS>
<VIEWFIELD>CLIENT</VIEWFIELD>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ENQMODE>E</ENQMODE>
</DD27P>
<DD27P>
<VIEWNAME>EZDEMO_ABAP_LOCK</VIEWNAME>
<OBJPOS>0002</OBJPOS>
<VIEWFIELD>KEY_FIELD</VIEWFIELD>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<FIELDNAME>KEY_FIELD</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ENQMODE>E</ENQMODE>
</DD27P>
</DD27P_TABLE>
</asx:values>
</asx:abap>
</abapGit>

11
src/package.devc.xml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DEVC" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DEVC>
<CTEXT>ABAP Cheat Sheets</CTEXT>
<TPCLASS>X</TPCLASS>
</DEVC>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,20 @@
***********************************************************************
*
* RAP BO provider (i. e. ABAP behavior pool/ABP)
* for a RAP demo scenario
*
* See more information in the CCIMP include (local types tab in ADT).
*
**********************************************************************
"! <p class="shorttext synchronized">Behavior implementation for RAP demo scenario (draft BO)</p>
"! The class represents a RAP BO provider (i. e. an ABAP behavior pool/ABP) for a RAP demo scenario
"! (managed, draft-enabled RAP BO with late numbering).
CLASS zbp_demo_abap_rap_draft_m DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zdemo_abap_rap_draft_m.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zbp_demo_abap_rap_draft_m IMPLEMENTATION.
ENDCLASS.

View File

@@ -0,0 +1,234 @@
***********************************************************************
*
* RAP BO provider (i. e. ABAP behavior pool/ABP)
* for a RAP demo scenario
*
* - RAP scenario: "RAP calculator" (managed, draft-enabled RAP BO with
* late numbering)
* - Data model: Consists of a root entity alone.
* The BDEF defines the behavior for this entity. The definitions in the
* BDEF determine which methods must be implemented in the ABAP behavior
* pool (ABP). Note that the view contains many annotations for the
* SAP Fiori UI.
*
* ----------------------------- NOTE -----------------------------------
* This simplified example is not a real life scenario and rather
* focuses on the technical side by giving an idea how the communication
* and data exchange between a RAP BO consumer, which is a class
* in this case, and RAP BO provider can work. Additionally, it shows
* how the methods for non-standard RAP BO operations might be
* self-implemented in an ABP. The example is is intentionally kept
* short and simple and focuses on specific RAP aspects. For this reason,
* the example might not fully meet the requirements of the RAP BO contract.
*
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
***********************************************************************
CLASS lhc_calc DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS delete_all FOR MODIFY
IMPORTING keys FOR ACTION calc~delete_all.
METHODS get_global_authorizations FOR GLOBAL AUTHORIZATION
IMPORTING REQUEST requested_authorizations FOR calc RESULT result.
METHODS validate FOR VALIDATE ON SAVE
IMPORTING keys FOR calc~validate.
METHODS det_modify FOR DETERMINE ON MODIFY
IMPORTING keys FOR calc~det_modify.
METHODS calculation FOR MODIFY
IMPORTING keys FOR ACTION calc~calculation.
ENDCLASS.
CLASS lhc_calc IMPLEMENTATION.
METHOD delete_all.
"Purpose: The method deletes all persisted database entries.
DATA all_keys TYPE TABLE FOR DELETE zdemo_abap_rap_draft_m.
SELECT id FROM zdemo_abap_tabca INTO CORRESPONDING FIELDS OF TABLE @all_keys.
READ ENTITIES OF zdemo_abap_rap_draft_m IN LOCAL MODE
ENTITY calc
ALL FIELDS WITH CORRESPONDING #( all_keys )
RESULT DATA(lt_del).
IF lt_del IS NOT INITIAL.
MODIFY ENTITY IN LOCAL MODE zdemo_abap_rap_draft_m
DELETE FROM CORRESPONDING #( lt_del ).
APPEND VALUE #( %msg = new_message_with_text( text = 'All persisted calculations were deleted.'
severity = if_abap_behv_message=>severity-information )
) TO reported-calc.
ELSE.
APPEND VALUE #( %msg = new_message_with_text( text = 'No persisted calculations available.'
severity = if_abap_behv_message=>severity-information )
) TO reported-calc.
ENDIF.
ENDMETHOD.
METHOD get_global_authorizations.
"Purposely kept without implementation.
ENDMETHOD.
METHOD validate.
"Retrieving instances based on requested keys
READ ENTITIES OF zdemo_abap_rap_draft_m IN LOCAL MODE
ENTITY calc
ALL FIELDS
WITH CORRESPONDING #( keys )
RESULT DATA(result_validate)
FAILED DATA(f).
CHECK result_validate IS NOT INITIAL.
"Various calculation errors are handled.
LOOP AT result_validate ASSIGNING FIELD-SYMBOL(<fs>).
APPEND VALUE #( %tky = <fs>-%tky
%state_area = 'VALIDATE_CALCULATION'
) TO reported-calc.
IF <fs>-calc_result = `Wrong operator`.
APPEND VALUE #( %tky = <fs>-%tky ) TO failed-calc.
APPEND VALUE #( %tky = <fs>-%tky
%state_area = 'VALIDATE_CALCULATION'
%msg = new_message_with_text( text = 'Only + - * / P allowed as operators.'
severity = if_abap_behv_message=>severity-error )
"%element highlights the input field
%element-arithm_op = if_abap_behv=>mk-on
) TO reported-calc.
ELSEIF <fs>-calc_result = `Division by 0`.
APPEND VALUE #( %tky = <fs>-%tky ) TO failed-calc.
APPEND VALUE #( %tky = <fs>-%tky
%state_area = 'VALIDATE_CALCULATION'
%msg = new_message_with_text( text = 'Zero division not possible.'
severity = if_abap_behv_message=>severity-error )
%element-arithm_op = if_abap_behv=>mk-on
%element-num2 = if_abap_behv=>mk-on
) TO reported-calc.
ELSEIF <fs>-calc_result = `Overflow error`.
APPEND VALUE #( %tky = <fs>-%tky ) TO failed-calc.
APPEND VALUE #( %tky = <fs>-%tky
%state_area = 'VALIDATE_CALCULATION'
%msg = new_message_with_text( text = 'Check the numbers. Try smaller ones.'
severity = if_abap_behv_message=>severity-error )
%element-num1 = if_abap_behv=>mk-on
%element-num2 = if_abap_behv=>mk-on
) TO reported-calc.
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD det_modify.
MODIFY ENTITIES OF zdemo_abap_rap_draft_m IN LOCAL MODE
ENTITY calc
EXECUTE calculation
FROM CORRESPONDING #( keys ).
ENDMETHOD.
METHOD calculation.
READ ENTITIES OF zdemo_abap_rap_draft_m IN LOCAL MODE
ENTITY calc
FIELDS ( num1 num2 arithm_op ) WITH CORRESPONDING #( keys )
RESULT DATA(lt_calc)
FAILED DATA(f).
LOOP AT lt_calc ASSIGNING FIELD-SYMBOL(<calc>).
TRY.
<calc>-calc_result = SWITCH #( <calc>-arithm_op
WHEN `+` THEN <calc>-num1 + <calc>-num2
WHEN `-` THEN <calc>-num1 - <calc>-num2
WHEN `*` THEN <calc>-num1 * <calc>-num2
WHEN `/` THEN <calc>-num1 / <calc>-num2
WHEN `P` THEN ipow( base = <calc>-num1 exp = <calc>-num2 )
ELSE `Wrong operator` ).
"Bringing "-" to the front in case of negative values in the string
IF <calc>-calc_result CA `-`.
<calc>-calc_result = shift_right( val = <calc>-calc_result circular = 1 ).
ENDIF.
"Removing trailing .0 from the string
REPLACE PCRE `\.0+\b` IN <calc>-calc_result WITH ``.
"Handling the fact that ABAP allows division by zero if the dividend itself is zero.
IF <calc>-num1 = 0 AND <calc>-num2 = 0 AND <calc>-arithm_op = `/`.
<calc>-calc_result = `Division by 0`.
ENDIF.
CATCH cx_sy_zerodivide.
<calc>-calc_result = `Division by 0`.
CATCH cx_sy_arithmetic_overflow.
<calc>-calc_result = `Overflow error`.
ENDTRY.
ENDLOOP.
MODIFY ENTITY IN LOCAL MODE zdemo_abap_rap_draft_m
UPDATE FIELDS ( calc_result )
WITH CORRESPONDING #( lt_calc ).
ENDMETHOD.
ENDCLASS.
CLASS lsc_zdemo_abap_rap_draft_m DEFINITION INHERITING FROM cl_abap_behavior_saver.
PROTECTED SECTION.
METHODS adjust_numbers REDEFINITION.
ENDCLASS.
CLASS lsc_zdemo_abap_rap_draft_m IMPLEMENTATION.
METHOD adjust_numbers.
"The newly created entity instances are given their final key
"only shortly before saving in the database in the adjust_numbers method.
"Until then, the business logic uses a temporary key that has to be replaced.
"In this very simplified example, the key 'id' is purposely typed with the
"type sysuuid_x16 which can accept the value used in %pid to finally ensure
"that there is a unique key and the instance can be stored in the database.
"Hence, the final key 'id' is in this example just the value used for %pid.
LOOP AT mapped-calc ASSIGNING FIELD-SYMBOL(<fs>).
<fs>-%key-id = <fs>-%pid.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZBP_DEMO_ABAP_RAP_DRAFT_M</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Behavior implementation for RAP demo scenario (draft BO)</DESCRIPT>
<CATEGORY>06</CATEGORY>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
<CLSDEFINT>ZDEMO_ABAP_RAP_DRAFT_M</CLSDEFINT>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,20 @@
***********************************************************************
*
* RAP BO provider (i. e. ABAP behavior pool/ABP)
* for a RAP demo scenario
*
* See more information in the CCIMP include (local types tab in ADT).
*
**********************************************************************
"! <p class="shorttext synchronized">Behavior implementation for RAP demo scenario (managed BO)</p>
"! The class represents a RAP BO provider (i. e. an ABAP behavior pool/ABP) for a RAP demo scenario
"! (managed RAP BO with external numbering).
CLASS zbp_demo_abap_rap_ro_m DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zdemo_abap_rap_ro_m.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zbp_demo_abap_rap_ro_m IMPLEMENTATION.
ENDCLASS.

View File

@@ -0,0 +1,123 @@
***********************************************************************
*
* RAP BO provider (i. e. ABAP behavior pool/ABP)
* for a RAP demo scenario
*
* - RAP scenario: managed RAP BO, external numbering
* - Data model: Consists of a root entity and one child entity. The BDEF
* defines the behavior for these two entities which are connected via
* a CDS composition relation. The definitions in the BDEF determine
* which methods must be implemented in this ABAP behavior pool (ABP).
*
* ----------------------------- NOTE -----------------------------------
* This simplified example is not a real life scenario and rather
* focuses on the technical side by giving an idea how the communication
* and data exchange between a RAP BO consumer, which is a class
* in this case, and RAP BO provider can work. Additionally, it shows
* how the methods for non-standard RAP BO operations might be
* self-implemented in an ABP. The example is is intentionally kept
* short and simple and focuses on specific RAP aspects. For this reason,
* the example might not fully meet the requirements of the RAP BO contract.
*
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
***********************************************************************
CLASS lhc_root DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS get_global_authorizations FOR GLOBAL AUTHORIZATION
IMPORTING REQUEST requested_authorizations FOR root RESULT result.
METHODS multiply_by_2 FOR MODIFY
IMPORTING keys FOR ACTION root~multiply_by_2.
METHODS det_add_text FOR DETERMINE ON SAVE
IMPORTING keys FOR root~det_add_text.
METHODS val FOR VALIDATE ON SAVE
IMPORTING keys FOR root~val.
ENDCLASS.
CLASS lhc_root IMPLEMENTATION.
METHOD get_global_authorizations.
ENDMETHOD.
METHOD multiply_by_2.
"Retrieving instances based on requested keys
READ ENTITIES OF zdemo_abap_rap_ro_m IN LOCAL MODE
ENTITY root
FIELDS ( field3 field4 ) WITH CORRESPONDING #( keys )
RESULT DATA(result)
FAILED failed.
"If read result is initial, stop further method execution.
CHECK result IS NOT INITIAL.
"Multiply integer values by 2
MODIFY ENTITIES OF zdemo_abap_rap_ro_m IN LOCAL MODE
ENTITY root
UPDATE FIELDS ( field3 field4 ) WITH VALUE #( FOR key IN result ( %tky = key-%tky
field3 = key-field3 * 2
field4 = key-field4 * 2 ) ).
ENDMETHOD.
METHOD det_add_text.
READ ENTITIES OF zdemo_abap_rap_ro_m IN LOCAL MODE
ENTITY root
FIELDS ( field2 ) WITH CORRESPONDING #( keys )
RESULT DATA(lt_res).
"If read result is initial, stop further method execution.
CHECK lt_res IS NOT INITIAL.
"field2 is changed
MODIFY ENTITIES OF zdemo_abap_rap_ro_m IN LOCAL MODE
ENTITY root
UPDATE FIELDS ( field2 )
WITH VALUE #( FOR key IN lt_res ( %tky = key-%tky
field2 = |{ key-field2 }_#| ) ).
ENDMETHOD.
METHOD val.
READ ENTITIES OF zdemo_abap_rap_ro_m IN LOCAL MODE
ENTITY root
FIELDS ( field3 ) WITH CORRESPONDING #( keys )
RESULT DATA(lt_res).
"If read result is initial, stop further method execution.
CHECK lt_res IS NOT INITIAL.
LOOP AT lt_res ASSIGNING FIELD-SYMBOL(<fs_res>).
IF <fs_res>-field3 > 1000.
APPEND VALUE #( %tky = <fs_res>-%tky
%fail-cause = if_abap_behv=>cause-disabled
)
TO failed-root.
APPEND VALUE #( %tky = <fs_res>-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = 'Validation failed!' )
) TO reported-root.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZBP_DEMO_ABAP_RAP_RO_M</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Behavior implementation for RAP demo scenario (managed BO)</DESCRIPT>
<CATEGORY>06</CATEGORY>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
<CLSDEFINT>ZDEMO_ABAP_RAP_RO_M</CLSDEFINT>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,20 @@
***********************************************************************
*
* RAP BO provider (i. e. ABAP behavior pool/ABP)
* for a RAP demo scenario
*
* See more information in the CCIMP include (local types tab in ADT).
*
**********************************************************************
"! <p class="shorttext synchronized">Behavior implementation for RAP demo scenario (unmanaged BO)</p>
"! The class represents a RAP BO provider (i. e. an ABAP behavior pool/ABP) for a RAP demo scenario
"! (unmanaged RAP BO with external numbering).
CLASS zbp_demo_abap_rap_ro_u DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zdemo_abap_rap_ro_u.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zbp_demo_abap_rap_ro_u IMPLEMENTATION.
ENDCLASS.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZBP_DEMO_ABAP_RAP_RO_U</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Behavior implementation for RAP demo scenario (unmanaged BO)</DESCRIPT>
<CATEGORY>06</CATEGORY>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
<CLSDEFINT>ZDEMO_ABAP_RAP_RO_U</CLSDEFINT>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
CLASS local_class DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING txt TYPE string,
double IMPORTING int TYPE
REF TO i RETURNING VALUE(res) TYPE i.
DATA: timestamp TYPE string,
text TYPE string.
CLASS-DATA: no_of_instances TYPE i READ-ONLY.
ENDCLASS.
CLASS local_class IMPLEMENTATION.
METHOD constructor.
"Number of instances of the class are counted.
no_of_instances = no_of_instances + 1.
"Set a time stamp.
DATA: ts TYPE timestampl.
GET TIME STAMP FIELD ts.
timestamp = |{ ts TIMESTAMP = SPACE }|.
text = |{ txt }, { sy-uname }.|.
ENDMETHOD.
METHOD double.
res = int->* * 2.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_CONSTRUCTOR_EXPR</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: Constructor expressions</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,201 @@
***********************************************************************
*
* Class for ABAP cheat sheet examples
*
* -------------------------- NOTE -------------------------------------
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
*
***********************************************************************
"! <p class="shorttext synchronized">Class for ABAP cheat sheet examples</p>
"! The class supports the displaying of output of the ABAP cheat sheet examples.
CLASS zcl_demo_abap_display DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
io_out TYPE REF TO if_oo_adt_classrun_out,
display
IMPORTING
input TYPE data
name TYPE string DEFAULT ``
RETURNING
VALUE(output) TYPE string,
next_section
IMPORTING
heading TYPE string.
protected section.
PRIVATE SECTION.
DATA:
mo_out TYPE REF TO if_oo_adt_classrun_out,
offset TYPE i.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_DISPLAY IMPLEMENTATION.
METHOD constructor.
mo_out = io_out.
ENDMETHOD.
METHOD display.
"Checking data type
DATA(type_descr) = cl_abap_typedescr=>describe_by_data( input ).
CASE type_descr->kind.
WHEN cl_abap_typedescr=>kind_struct.
DATA(struct_descr) = CAST cl_abap_structdescr( type_descr ).
"Checking for complex output
IF struct_descr->struct_kind = cl_abap_structdescr=>structkind_nested
OR line_exists( struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_table ] )
OR line_exists( struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_dref ] )
OR line_exists( struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_oref ] ).
DATA(to_be_serialized) = abap_true.
ELSE.
DATA(display) = mo_out->get( data = input name = name ).
ENDIF.
WHEN cl_abap_typedescr=>kind_table.
DATA(table_descr) = CAST cl_abap_tabledescr( type_descr ).
TRY.
DATA(line_type_struct_descr) = CAST cl_abap_structdescr( table_descr->get_table_line_type( ) ).
"Checking for complex output
IF line_type_struct_descr->struct_kind = cl_abap_structdescr=>structkind_nested
OR line_exists( line_type_struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_table ] )
OR line_exists( line_type_struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_dref ] )
OR line_exists( line_type_struct_descr->components[ type_kind = cl_abap_typedescr=>typekind_oref ] ).
to_be_serialized = abap_true.
ELSE.
display = mo_out->get( data = input name = name ).
ENDIF.
CATCH cx_sy_move_cast_error.
to_be_serialized = abap_true.
ENDTRY.
WHEN cl_abap_typedescr=>kind_class.
to_be_serialized = abap_true.
WHEN cl_abap_typedescr=>kind_intf.
to_be_serialized = abap_true.
WHEN cl_abap_typedescr=>kind_elem.
display = mo_out->get( data = COND string( WHEN name IS INITIAL THEN input ELSE `"` && name && `":` && cl_abap_char_utilities=>newline && input ) ).
WHEN cl_abap_typedescr=>kind_ref.
"Checking for data references
IF type_descr->type_kind = cl_abap_typedescr=>typekind_dref.
"Checking type of dereferenced data object
DATA(type_check_dref) = cl_abap_typedescr=>describe_by_data( input->* ).
"Processing (non-)elementary types
IF type_check_dref->kind = type_descr->kind_elem.
display = mo_out->get( data = COND string( WHEN name IS INITIAL THEN input->* ELSE `"` && name && `":` && cl_abap_char_utilities=>newline && input->* ) ).
ELSE.
to_be_serialized = abap_true.
ENDIF.
ELSE.
to_be_serialized = abap_true.
ENDIF.
ENDCASE.
"Processing complex output by serializiation
FIND SUBSTRING `Data type not yet supported ...` IN display MATCH OFFSET DATA(off) MATCH LENGTH DATA(len).
IF sy-subrc = 0 OR to_be_serialized = abap_true.
"ABAP JSON serializing
DATA(json) = /ui2/cl_json=>serialize( data = input
pretty_name = /ui2/cl_json=>pretty_mode-low_case
compress = abap_false
hex_as_base64 = abap_false
format_output = abap_true
assoc_arrays = abap_true
assoc_arrays_opt = abap_true ).
IF to_be_serialized = abap_true.
IF name IS INITIAL.
REPLACE PCRE `^` IN display WITH json && cl_abap_char_utilities=>newline.
ELSE.
REPLACE PCRE `^` IN display WITH `"` && name && `":` && cl_abap_char_utilities=>newline && json && cl_abap_char_utilities=>newline.
ENDIF.
"substring found
ELSE.
IF name IS INITIAL.
REPLACE SECTION OFFSET off LENGTH len OF display WITH json && cl_abap_char_utilities=>newline.
ELSE.
REPLACE SECTION OFFSET off LENGTH len OF display WITH `"` && name && `":` && cl_abap_char_utilities=>newline && json && cl_abap_char_utilities=>newline.
ENDIF.
ENDIF.
mo_out->write( display ).
ELSE.
mo_out->write( display ).
ENDIF.
ENDMETHOD.
METHOD next_section.
mo_out->write( `_________________________________________________________________________________`
&& cl_abap_char_utilities=>newline
&& cl_abap_char_utilities=>newline
&& heading
&& cl_abap_char_utilities=>newline ).
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_DISPLAY</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Class for ABAP cheat sheet examples</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
CLASS lcl_det_at_runtime DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
get_dyn_table_name RETURNING VALUE(tab) TYPE string,
get_dyn_dobj RETURNING VALUE(dobj) TYPE string,
get_dyn_field RETURNING VALUE(field) TYPE string,
get_dyn_select_list RETURNING VALUE(list) TYPE string,
get_dyn_where_clause RETURNING VALUE(clause_tab) TYPE string_table,
get_dyn_class RETURNING VALUE(cl) TYPE string,
get_random_type RETURNING VALUE(random_type) TYPE string.
CLASS-DATA: string1 TYPE string,
string2 TYPE string,
string3 TYPE string.
TYPES: type1 TYPE p LENGTH 8 DECIMALS 2, "elementary type
type2 TYPE zdemo_abap_carr, "structure type
type3 TYPE TABLE OF zdemo_abap_flsch, "internal table type
type4 TYPE REF TO lcl_det_at_runtime. "reference type
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS lcl_det_at_runtime IMPLEMENTATION.
METHOD get_dyn_table_name.
"Providing DDIC table names in a string table to be selected from.
DATA(flight_tables) = VALUE string_table(
( `ZDEMO_ABAP_CARR` ) ( `ZDEMO_ABAP_FLSCH` ) ( `ZDEMO_ABAP_FLI` ) ).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( flight_tables ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random table name.
TRY.
tab = flight_tables[ idx ].
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_dyn_dobj.
"Providing strings with demo content.
string1 = |Hallo, { sy-uname }. | &&
|This is string1.|.
string2 = |Hallo, { sy-uname }. | &&
|This is string2.|.
string3 = |Hallo, { sy-uname }. | &&
|This is string3.|.
"Filling table with data object names.
DATA(str_tab) = VALUE string_table(
( `STRING1` ) ( `STRING2` ) ( `STRING3` ) ).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( str_tab ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random data object name.
TRY.
dobj = str_tab[ idx ].
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_dyn_field.
"Getting list of components of DDIC type zdemo_abap_carr
DATA(comp) = CAST cl_abap_structdescr(
cl_abap_typedescr=>describe_by_name(
'ZDEMO_ABAP_CARR' )
)->components.
"Getting random number to determine the table index at runtime.
"Starting from 2 to exclude MANDT field
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 2
max = lines( comp ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random component name.
TRY.
field = comp[ idx ]-name.
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_dyn_select_list.
"Providing SELECT lists in a string table to be selected from.
DATA sel_list_tab TYPE string_table.
sel_list_tab = VALUE #(
( `CARRID, CONNID, COUNTRYFR, COUNTRYTO` )
( `CARRID, CONNID, CITYFROM, CITYTO` )
( `CARRID, CONNID, AIRPFROM, AIRPTO` )
( `CARRID, CONNID, AIRPFROM, AIRPTO, ` &&
`FLTIME, DEPTIME, ARRTIME, DISTANCE` )
).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( sel_list_tab ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random SELECT list.
TRY.
list = sel_list_tab[ idx ].
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_dyn_where_clause.
"Providing WHERE clauses in a table to be selected from.
DATA: BEGIN OF where_struc,
where_clause_tab TYPE string_table,
END OF where_struc.
DATA where_itab LIKE TABLE OF where_struc WITH EMPTY KEY.
where_itab = VALUE #(
( where_clause_tab = VALUE #( ( `CARRID = 'LH'` )
( `OR CARRID = 'AA'` ) ) )
( where_clause_tab = VALUE #( ( `CONNID BETWEEN 0 AND 300` ) ) )
( where_clause_tab = VALUE #( ( `CITYFROM LIKE '%FRA%'` ) ) )
( where_clause_tab =
VALUE #( ( `DISTANCE > 500 AND DISTID = 'KM'` ) ) ) ).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( where_itab ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random WHERE clause.
TRY.
clause_tab = where_itab[ idx ]-where_clause_tab.
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_dyn_class.
"Providing class names in a string table to be selected from.
DATA(class_tab) = VALUE string_table(
( `LCL_DET_AT_RUNTIME` )
( `LCL_DUMMY` ) ).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( class_tab ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random class name.
TRY.
cl = class_tab[ idx ].
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
METHOD get_random_type.
"Providing names of classes in a string table to be selected from.
"Note that in this example types are defined in the public section
"of a class and the program logic is included in another class.
"To be able to refer to the types, the class name is added.
DATA(str_tab) = VALUE string_table(
( `LCL_DET_AT_RUNTIME=>TYPE1` )
( `LCL_DET_AT_RUNTIME=>TYPE2` )
( `LCL_DET_AT_RUNTIME=>TYPE3` )
( `LCL_DET_AT_RUNTIME=>TYPE4` )
( `LCL_DET_AT_RUNTIME` )
( `IF_OO_ADT_CLASSRUN` ) ).
"Getting random number to determine the table index at runtime.
DATA(random) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1
max = lines( str_tab ) ).
DATA(idx) = random->get_next( ).
"Returning parameter to receive the random type name.
TRY.
random_type = str_tab[ idx ].
CATCH cx_sy_itab_line_not_found INTO DATA(error).
ENDTRY.
ENDMETHOD.
ENDCLASS.
CLASS lcl_dummy DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
meth_a IMPORTING imp TYPE i
EXPORTING exp TYPE i
RETURNING VALUE(str) TYPE string,
meth_b CHANGING ch TYPE string
RETURNING VALUE(str) TYPE string.
ENDCLASS.
CLASS lcl_dummy IMPLEMENTATION.
METHOD meth_a.
str = |Hallo from meth_a.|.
ENDMETHOD.
METHOD meth_b.
str = |Hallo from meth_b.|.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_DYNAMIC_PROG</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: Dynamic programming</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,711 @@
***********************************************************************
*
* Class for clearing and filling demo database tables used in the
* context of ABAP cheat sheets
*
* -------------------------- NOTE -------------------------------------
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
*
***********************************************************************
"! <p class="shorttext synchronized">Class for ABAP cheat sheet examples</p>
"! The class is meant to clear and fill demo database tables used in the context of ABAP cheat sheet examples.
"! The demo database tables contain airline and flight information.
CLASS zcl_demo_abap_flight_tables DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
CLASS-METHODS: clear_dbtabs,
fill_dbtabs.
protected section.
private section.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_FLIGHT_TABLES IMPLEMENTATION.
METHOD clear_dbtabs.
DELETE FROM zdemo_abap_flsch.
DELETE FROM zdemo_abap_carr.
DELETE FROM zdemo_abap_fli.
ENDMETHOD.
METHOD fill_dbtabs.
"Clearing db tables before filling
clear_dbtabs( ).
"Filling db table
MODIFY zdemo_abap_flsch FROM TABLE @( VALUE #(
( carrid = 'AA'
connid = 0017
countryfr = 'US'
cityfrom = 'NEW YORK'
airpfrom = 'JFK'
countryto = 'US'
cityto = 'SAN FRANCISCO'
airpto = 'SFO'
fltime = 361
deptime = '110000'
arrtime = '140100'
distance = 2572
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'AA'
connid = 0064
countryfr = 'US'
cityfrom = 'SAN FRANCISCO'
airpfrom = 'SFO'
countryto = 'US'
cityto = 'NEW YORK'
airpto = 'JFK'
fltime = 321
deptime = '090000'
arrtime = '172100'
distance = 2572
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'AZ'
connid = 0555
countryfr = 'IT'
cityfrom = 'ROME'
airpfrom = 'FCO'
countryto = 'DE'
cityto = 'FRANKFURT'
airpto = 'FRA'
fltime = 125
deptime = '190000'
arrtime = '210500'
distance = 845
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'AZ'
connid = 0788
countryfr = 'IT'
cityfrom = 'ROME'
airpfrom = 'FCO'
countryto = 'JP'
cityto = 'TOKYO'
airpto = 'TYO'
fltime = 775
deptime = '120000'
arrtime = '085500'
distance = 6130
distid = 'MI'
fltype = ''
period = 1 )
( carrid = 'AZ'
connid = 0789
countryfr = 'JP'
cityfrom = 'TOKYO'
airpfrom = 'TYO'
countryto = 'IT'
cityto = 'ROME'
airpto = 'FCO'
fltime = 940
deptime = '114500'
arrtime = '192500'
distance = 6130
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'AZ'
connid = 0790
countryfr = 'IT'
cityfrom = 'ROME'
airpfrom = 'FCO'
countryto = 'JP'
cityto = 'OSAKA'
airpto = 'KIX'
fltime = 815
deptime = '103500'
arrtime = '081000'
distance = 6030
distid = 'MI'
fltype = 'X'
period = 1 )
( carrid = 'DL'
connid = 0106
countryfr = 'US'
cityfrom = 'NEW YORK'
airpfrom = 'JFK'
countryto = 'DE'
cityto = 'FRANKFURT'
airpto = 'FRA'
fltime = 475
deptime = '193500'
arrtime = '093000'
distance = 3851
distid = 'MI'
fltype = ''
period = 1 )
( carrid = 'DL'
connid = 1699
countryfr = 'US'
cityfrom = 'NEW YORK'
airpfrom = 'JFK'
countryto = 'US'
cityto = 'SAN FRANCISCO'
airpto = 'SFO'
fltime = 382
deptime = '171500'
arrtime = '203700'
distance = 2572
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'DL'
connid = 1984
countryfr = 'US'
cityfrom = 'SAN FRANCISCO'
airpfrom = 'SFO'
countryto = 'US'
cityto = 'NEW YORK'
airpto = 'JFK'
fltime = 325
deptime = '100000'
arrtime = '182500'
distance = 2572
distid = 'MI'
fltype = ''
period = 0 )
( carrid = 'JL'
connid = 0407
countryfr = 'JP'
cityfrom = 'TOKYO'
airpfrom = 'NRT'
countryto = 'DE'
cityto = 'FRANKFURT'
airpto = 'FRA'
fltime = 725
deptime = '133000'
arrtime = '173500'
distance = 9100
distid = 'KM'
fltype = ''
period = 0 )
( carrid = 'JL'
connid = 0408
countryfr = 'DE'
cityfrom = 'FRANKFURT'
airpfrom = 'FRA'
countryto = 'JP'
cityto = 'TOKYO'
airpto = 'NRT'
fltime = 675
deptime = '202500'
arrtime = '154000'
distance = 9100
distid = 'KM'
fltype = 'X'
period = 1 )
( carrid = 'LH'
connid = 0400
countryfr = 'DE'
cityfrom = 'FRANKFURT'
airpfrom = 'FRA'
countryto = 'US'
cityto = 'NEW YORK'
airpto = 'JFK'
fltime = 444
deptime = '101000'
arrtime = '113400'
distance = 6162
distid = 'KM'
fltype = ''
period = 0 )
( carrid = 'LH'
connid = 0401
countryfr = 'US'
cityfrom = 'NEW YORK'
airpfrom = 'JFK'
countryto = 'DE'
cityto = 'FRANKFURT'
airpto = 'FRA'
fltime = 435
deptime = '183000'
arrtime = '074500'
distance = 6162
distid = 'KM'
fltype = ''
period = 1 )
( carrid = 'LH'
connid = 0402
countryfr = 'DE'
cityfrom = 'FRANKFURT'
airpfrom = 'FRA'
countryto = 'US'
cityto = 'NEW YORK'
airpto = 'JFK'
fltime = 455
deptime = '133000'
arrtime = '150500'
distance = 6162
distid = 'KM'
fltype = 'X'
period = 0 )
( carrid = 'LH'
connid = 2402
countryfr = 'DE'
cityfrom = 'FRANKFURT'
airpfrom = 'FRA'
countryto = 'DE'
cityto = 'BERLIN'
airpto = 'SXF'
fltime = 65
deptime = '103000'
arrtime = '113500'
distance = 555
distid = 'KM'
fltype = ''
period = 0 ) ) ).
"Filling db table
MODIFY zdemo_abap_carr FROM TABLE @( VALUE #(
( carrid = 'AA'
carrname = 'American Airlines'
currcode = 'USD'
url = 'http://www.aa.com' )
( carrid = 'LH'
carrname = 'Lufthansa'
currcode = 'EUR'
url = 'http://www.lufthansa.com' )
( carrid = 'JL'
carrname = 'Japan Airlines'
currcode = 'JPY'
url = 'http://www.jal.co.jp' )
( carrid = 'DL'
carrname = 'Delta Airlines'
currcode = 'USD'
url = 'http://www.delta-air.com' )
( carrid = 'AZ'
carrname = 'ITA Airways'
currcode = 'EUR'
url = 'http://www.ita-airways.com' ) ) ).
"Filling db table
MODIFY zdemo_abap_fli FROM TABLE @( VALUE #(
( carrid = 'AA'
connid = 0017
fldate = '20230923'
price = '464.35'
currency = 'USD'
planetype = '747-400'
seatsmax = 385
seatsocc = 369
paymentsum = '191993.87'
seatsmax_b = 31
seatsocc_b = 31
seatsmax_f = 21
seatsocc_f = 19 )
( carrid = 'AA'
connid = 0017
fldate = '20230929'
price = '464.35'
currency = 'USD'
planetype = '747-400'
seatsmax = 385
seatsocc = 372
paymentsum = '193537.52'
seatsmax_b = 31
seatsocc_b = 30
seatsmax_f = 21
seatsocc_f = 20 )
( carrid = 'AA'
connid = 0017
fldate = '20231111'
price = '464.35'
currency = 'USD'
planetype = '747-400'
seatsmax = 385
seatsocc = 374
paymentsum = '193651.77'
seatsmax_b = 31
seatsocc_b = 29
seatsmax_f = 21
seatsocc_f = 21 )
( carrid = 'AA'
connid = 0064
fldate = '20220131'
price = '464.35'
currency = 'USD'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 313
paymentsum = '168469.88'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'AA'
connid = 0064
fldate = '20220215'
price = '464.35'
currency = 'USD'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 157
paymentsum = '84846.15'
seatsmax_b = 30
seatsocc_b = 15
seatsmax_f = 20
seatsocc_f = 10 )
( carrid = 'AZ'
connid = 0555
fldate = '20230721'
price = '226.41'
currency = 'EUR'
planetype = 'A319-100'
seatsmax = 120
seatsocc = 114
paymentsum = '26519.75'
seatsmax_b = 8
seatsocc_b = 8
seatsmax_f = 8
seatsocc_f = 8 )
( carrid = 'AZ'
connid = 0555
fldate = '20230728'
price = '226.41'
currency = 'EUR'
planetype = 'A319-100'
seatsmax = 120
seatsocc = 115
paymentsum = '16695.50'
seatsmax_b = 8
seatsocc_b = 8
seatsmax_f = 8
seatsocc_f = 8 )
( carrid = 'AZ'
connid = 0788
fldate = '20230922'
price = '1071.41'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 456
paymentsum = '548722.20'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 20 )
( carrid = 'AZ'
connid = 0788
fldate = '20230722'
price = '1071.41'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 455
paymentsum = '544674.30'
seatsmax_b = 30
seatsocc_b = 28
seatsmax_f = 20
seatsocc_f = 20 )
( carrid = 'AZ'
connid = 0789
fldate = '20231025'
price = '1071.41'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 455
paymentsum = '545704.30'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'AZ'
connid = 0789
fldate = '20230221'
price = '1071.41'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 459
paymentsum = '549226.90'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 20 )
( carrid = 'AZ'
connid = 0790
fldate = '20231228'
price = '1055.41'
currency = 'EUR'
planetype = '747-400'
seatsmax = 385
seatsocc = 370
paymentsum = '462373.86'
seatsmax_b = 31
seatsocc_b = 30
seatsmax_f = 21
seatsocc_f = 21 )
( carrid = 'AZ'
connid = 0790
fldate = '20231201'
price = '1055.41'
currency = 'EUR'
planetype = '747-400'
seatsmax = 385
seatsocc = 367
paymentsum = '463661.64'
seatsmax_b = 31
seatsocc_b = 31
seatsmax_f = 21
seatsocc_f = 21 )
( carrid = 'DL'
connid = 0106
fldate = '20230209'
price = '652.42'
currency = 'USD'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 178
paymentsum = '136750.33'
seatsmax_b = 30
seatsocc_b = 17
seatsmax_f = 20
seatsocc_f = 10 )
( carrid = 'DL'
connid = 0106
fldate = '20240102'
price = '652.42'
currency = 'USD'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 16
paymentsum = '12892.33'
seatsmax_b = 30
seatsocc_b = 2
seatsmax_f = 20
seatsocc_f = 10 )
( carrid = 'DL'
connid = 1699
fldate = '20230921'
price = '464.35'
currency = 'USD'
planetype = '767-200'
seatsmax = 260
seatsocc = 250
paymentsum = '126636.91'
seatsmax_b = 21
seatsocc_b = 20
seatsmax_f = 11
seatsocc_f = 11 )
( carrid = 'DL'
connid = 1699
fldate = '20230511'
price = '464.35'
currency = 'USD'
planetype = '767-200'
seatsmax = 260
seatsocc = 251
paymentsum = '126493.06'
seatsmax_b = 21
seatsocc_b = 20
seatsmax_f = 11
seatsocc_f = 11 )
( carrid = 'DL'
connid = 1984
fldate = '20230719'
price = '464.35'
currency = 'USD'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 460
paymentsum = '225427.35'
seatsmax_b = 30
seatsocc_b = 29
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'DL'
connid = 1984
fldate = '20230213'
price = '464.35'
currency = 'USD'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 458
paymentsum = '225088.83'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'JL'
connid = 0407
fldate = '20231128'
price = '1102.77'
currency = 'JPY'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 458
paymentsum = '563231.65'
seatsmax_b = 30
seatsocc_b = 27
seatsmax_f = 20
seatsocc_f = 20 )
( carrid = 'JL'
connid = 0407
fldate = '20231019'
price = '1102.77'
currency = 'JPY'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 452
paymentsum = '553552.12'
seatsmax_b = 30
seatsocc_b = 28
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'JL'
connid = 0408
fldate = '20231128'
price = '1102.77'
currency = 'JPY'
planetype = '747-400'
seatsmax = 385
seatsocc = 365
paymentsum = '470129.20'
seatsmax_b = 31
seatsocc_b = 28
seatsmax_f = 21
seatsocc_f = 20 )
( carrid = 'JL'
connid = 0408
fldate = '20230123'
price = '1102.77'
currency = 'JPY'
planetype = '747-400'
seatsmax = 385
seatsocc = 372
paymentsum = '487715.90'
seatsmax_b = 31
seatsocc_b = 31
seatsmax_f = 21
seatsocc_f = 20 )
( carrid = 'LH'
connid = 0400
fldate = '20230628'
price = '1184.54'
currency = 'EUR'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 319
paymentsum = '270822.24'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 20 )
( carrid = 'LH'
connid = 0400
fldate = '20230323'
price = '1184.54'
currency = 'EUR'
planetype = 'A340-600'
seatsmax = 330
seatsocc = 312
paymentsum = '262597.14'
seatsmax_b = 30
seatsocc_b = 28
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'LH'
connid = 0401
fldate = '20231128'
price = '669.20'
currency = 'EUR'
planetype = '767-200'
seatsmax = 260
seatsocc = 246
paymentsum = '195417.72'
seatsmax_b = 21
seatsocc_b = 19
seatsmax_f = 11
seatsocc_f = 10 )
( carrid = 'LH'
connid = 0401
fldate = '20231229'
price = '669.20'
currency = 'EUR'
planetype = '767-200'
seatsmax = 260
seatsocc = 252
paymentsum = '199300.50'
seatsmax_b = 21
seatsocc_b = 19
seatsmax_f = 11
seatsocc_f = 11 )
( carrid = 'LH'
connid = 0402
fldate = '20230617'
price = '669.20'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 461
paymentsum = '353526.12'
seatsmax_b = 30
seatsocc_b = 29
seatsmax_f = 20
seatsocc_f = 18 )
( carrid = 'LH'
connid = 0402
fldate = '20230313'
price = '669.20'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 450
paymentsum = '349223.76'
seatsmax_b = 30
seatsocc_b = 29
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'LH'
connid = 2402
fldate = '20231028'
price = '245.20'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 451
paymentsum = '127197.62'
seatsmax_b = 30
seatsocc_b = 29
seatsmax_f = 20
seatsocc_f = 19 )
( carrid = 'LH'
connid = 2402
fldate = '20231223'
price = '245.20'
currency = 'EUR'
planetype = 'A380-800'
seatsmax = 475
seatsocc = 458
paymentsum = '18944.86'
seatsmax_b = 30
seatsocc_b = 30
seatsmax_f = 20
seatsocc_f = 20 ) ) ).
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_FLIGHT_TABLES</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Class for ABAP cheat sheet examples</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_INTERNAL_TABLES</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: Internal tables</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,556 @@
*&--------------------------------------------------------------------*
*& Custom exception classes
*&--------------------------------------------------------------------*
CLASS cx_afternoon DEFINITION INHERITING FROM cx_static_check.
ENDCLASS.
CLASS cx_night DEFINITION INHERITING FROM cx_static_check.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Class to demonstrate various method parameters
*& All formal parameters are passed by reference except the
*& returning parameter.
*&--------------------------------------------------------------------*
CLASS lcl_demo DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
"No parameters
hallo_static_ext,
"One importing parameter
powers_of_two IMPORTING i_pow TYPE i,
"Two importing parameters
"Specifying REFERENCE(p) is optional; a formal parameter
"without VALUE(p) or REFERENCE(p) is REFERENCE(p) by default
addition IMPORTING i_add1 TYPE i
REFERENCE(i_add2) TYPE i,
"Two importing parameters, one of them is optional.
addition_optional IMPORTING i_add_mand TYPE i
i_add_opt TYPE i OPTIONAL,
"Importing and exporting parameters
subtraction IMPORTING i_sub1 TYPE i
i_sub2 TYPE i
EXPORTING e_sub_result TYPE i,
"One exporting parameter
exporting_hallo EXPORTING text TYPE string,
"Changing parameter
square_root CHANGING i_sqr TYPE decfloat34,
"Importing and returning parameters
multiplication IMPORTING i_mult1 TYPE i
i_mult2 TYPE i
RETURNING VALUE(r_mult_result) TYPE i,
"Importing and exporting parameters
"for comparing the signature with method 'multiplication'
multiplication_exp_param IMPORTING i_multa TYPE i
i_multb TYPE i
EXPORTING e_mult_result TYPE i,
"Includes RAISING
division IMPORTING i_div1 TYPE i
i_div2 TYPE i
RETURNING VALUE(r_div_result) TYPE decfloat34
RAISING cx_sy_arithmetic_error,
check_daytime IMPORTING time TYPE t
EXPORTING greetings TYPE string
RAISING cx_afternoon cx_night,
"Include parameters with generic types
generic_data IMPORTING i_data TYPE data,
generic_tab IMPORTING i_anytab TYPE ANY TABLE.
CLASS-DATA: calc_result TYPE i,
string TYPE string,
some_data TYPE REF TO data.
ENDCLASS.
CLASS lcl_demo IMPLEMENTATION.
METHOD hallo_static_ext.
string = |Hallo { sy-uname }. | &&
|I'm a static method of class lcl_demo.|.
ENDMETHOD.
METHOD square_root.
i_sqr = sqrt( i_sqr ).
ENDMETHOD.
METHOD powers_of_two.
calc_result = i_pow * i_pow.
ENDMETHOD.
METHOD addition.
calc_result = i_add1 + i_add2.
ENDMETHOD.
METHOD addition_optional.
calc_result = i_add_mand + i_add_opt.
ENDMETHOD.
METHOD subtraction.
e_sub_result = i_sub1 - i_sub2.
ENDMETHOD.
METHOD exporting_hallo.
text = |Hallo { sy-uname }. | && |I'm a static method of class lcl_demo with one exporting parameter.|.
ENDMETHOD.
METHOD multiplication.
r_mult_result = i_mult1 * i_mult2.
ENDMETHOD.
METHOD multiplication_exp_param.
e_mult_result = i_multa * i_multb.
ENDMETHOD.
METHOD division.
CLEAR string.
TRY.
r_div_result = i_div1 / i_div2.
CATCH cx_sy_arithmetic_error INTO DATA(exc).
string = exc->get_text( ).
ENDTRY.
ENDMETHOD.
METHOD check_daytime.
CLEAR string.
"Morning: 5 am to 12 pm
IF time BETWEEN '050001' AND '120000'.
DATA(subrc) = 0.
ENDIF.
"Afternoon: 12 pm to 5 pm.
IF time BETWEEN '120001' AND '170000'.
subrc = 11.
ENDIF.
"Evening 5 pm to 9 pm.
"Commented out on purpose to have a time range for OTHERS :)
"IF time BETWEEN '170001' AND '210000'.
" subrc = 22.
"ENDIF.
"Night: 9 pm to 4 am.
IF time BETWEEN '210001' AND '050000'.
subrc = 33.
ENDIF.
IF subrc <> 0.
CASE subrc.
WHEN 11.
greetings = |Good afternoon.|.
WHEN 33.
greetings = |Good night.|.
WHEN OTHERS.
greetings = |It's neither morning, afternoon or night. | &&
|Hence, wishing you a good evening.|.
ENDCASE.
ELSE.
greetings = |Good morning.|.
ENDIF.
ENDMETHOD.
METHOD generic_data.
"A data reference variable is created that has the type of the
"imported variable. Its content is store in the variable
"some_data in the public section to be able to access the content.
CREATE DATA some_data LIKE i_data.
some_data->* = i_data.
ENDMETHOD.
METHOD generic_tab.
"See implementation of generic_data.
"Here, an internal table is handled.
CREATE DATA some_data LIKE i_anytab.
some_data->* = i_anytab.
ENDMETHOD.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Class to demonstrate basics in the global class
*&--------------------------------------------------------------------*
CLASS local_class DEFINITION.
PUBLIC SECTION.
METHODS: constructor.
DATA: num_inst TYPE i,
uuid TYPE sysuuid_x16,
timestamp TYPE timestampl.
CLASS-DATA: no_of_instances TYPE i READ-ONLY,
num_stat TYPE i VALUE 33.
CONSTANTS: const_number TYPE i VALUE 11.
TYPES type_i TYPE i.
ENDCLASS.
CLASS local_class IMPLEMENTATION.
METHOD constructor.
"Number of instances of the class are counted.
no_of_instances = no_of_instances + 1.
"Set a time stamp.
GET TIME STAMP FIELD timestamp.
"Increase the number.
num_inst = num_inst + 1.
"Get a random UUID.
TRY.
uuid = cl_system_uuid=>create_uuid_x16_static( ) .
CATCH cx_uuid_error.
ENDTRY.
ENDMETHOD.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Class to demonstrate events
*&--------------------------------------------------------------------*
CLASS lcl_events DEFINITION.
PUBLIC SECTION.
DATA: greets TYPE string.
"Events declaration.
EVENTS: morning, afternoon, evening, night.
"Event handler methods
METHODS: morning_greets FOR EVENT morning OF lcl_events,
afternoon_greets FOR EVENT afternoon OF lcl_events,
evening_greets FOR EVENT evening OF lcl_events,
night_greets FOR EVENT night OF lcl_events.
"Method to raise events
METHODS: greetings.
ENDCLASS.
CLASS lcl_events IMPLEMENTATION.
METHOD greetings.
DATA(syst_time) = cl_abap_context_info=>get_system_time( ).
"Morning: 5 am to 12 pm
IF syst_time BETWEEN '050001' AND '120000'.
RAISE EVENT morning.
"Afternoon: 12 pm to 5 pm.
ELSEIF syst_time BETWEEN '120001' AND '170000'.
RAISE EVENT afternoon.
"Evening 5 pm to 9 pm.
ELSEIF syst_time BETWEEN '170001' AND '210000'.
RAISE EVENT evening.
"Night: 9 pm to 5 am.
ELSEIF syst_time BETWEEN '210001' AND '050000'.
RAISE EVENT night.
ENDIF.
ENDMETHOD.
METHOD morning_greets.
greets = |Good morning, { sy-uname }.|.
ENDMETHOD.
METHOD afternoon_greets.
greets = |Good afternoon, { sy-uname }.|.
ENDMETHOD.
METHOD evening_greets.
greets = |Good evening, { sy-uname }.|.
ENDMETHOD.
METHOD night_greets.
greets = |Good night, { sy-uname }.|.
ENDMETHOD.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Class to demonstrate constructors
*&--------------------------------------------------------------------*
CLASS lcl_constructors DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING num1 TYPE i
num2 TYPE i RAISING cx_sy_zerodivide.
DATA: uuid TYPE sysuuid_x16,
in_div_result TYPE i,
in_text TYPE string.
CLASS-METHODS: class_constructor,
add_1.
CLASS-DATA: no_of_instances TYPE i READ-ONLY,
stat_number TYPE i,
stat_text TYPE string.
ENDCLASS.
CLASS lcl_constructors IMPLEMENTATION.
METHOD constructor.
"Get time stamp.
DATA(ts1) = utclong_current( ).
"Provide message.
in_text = |The instance constructor of the class | &&
|lcl_constructors was called on { ts1 }.|.
"Count number of instances.
no_of_instances = no_of_instances + 1.
"Get random UUID.
TRY.
uuid = cl_system_uuid=>create_uuid_x16_static( ) .
CATCH cx_uuid_error.
ENDTRY.
CLEAR in_div_result.
"Do calculation.
in_div_result = num1 / num2.
ENDMETHOD.
METHOD class_constructor.
"Set a number.
stat_number = 999.
"Get time stamp.
DATA(ts2) = utclong_current( ).
"Provide message.
stat_text = |The static constructor of the class | &&
|lcl_constructors was called on { ts2 } and the | &&
|value for the variable 'stat_number' was set to | &&
|{ stat_number }.|.
ENDMETHOD.
METHOD add_1.
stat_number += 1.
ENDMETHOD.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Classes to demonstrate inheritance, polymorphism and casting
*&--------------------------------------------------------------------*
"Class 1
CLASS lcl_class1 DEFINITION.
PUBLIC SECTION.
"Note: All methods are purposely included in the public section.
"Otherwise, it cannot be called in the demo's main class.
METHODS: constructor IMPORTING i_obj TYPE string OPTIONAL,
get_string RETURNING VALUE(str) TYPE string,
get_obj_name RETURNING VALUE(obj) TYPE string.
PRIVATE SECTION.
DATA: obj_name TYPE string.
ENDCLASS.
CLASS lcl_class1 IMPLEMENTATION.
METHOD constructor.
obj_name = i_obj.
ENDMETHOD.
METHOD get_obj_name.
obj = obj_name.
ENDMETHOD.
METHOD get_string.
str = `Hallo`.
ENDMETHOD.
ENDCLASS.
"Class 2a
CLASS lcl_class2a DEFINITION INHERITING FROM lcl_class1.
PUBLIC SECTION.
METHODS: get_string REDEFINITION,
get_number_2a RETURNING VALUE(num) TYPE i..
ENDCLASS.
CLASS lcl_class2a IMPLEMENTATION.
METHOD get_string.
str = |{ super->get_string( ) }, { sy-uname }!|.
ENDMETHOD.
METHOD get_number_2a.
num = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1 max = 100 )->get_next( ).
ENDMETHOD.
ENDCLASS.
"Class 2b
CLASS lcl_class2b DEFINITION INHERITING FROM lcl_class1 FINAL.
PUBLIC SECTION.
METHODS: get_string REDEFINITION,
get_number_2b RETURNING VALUE(num) TYPE i.
ENDCLASS.
CLASS lcl_class2b IMPLEMENTATION.
METHOD get_string.
str = |{ super->get_string( ) } from lcl_class2b, { sy-uname }!|.
ENDMETHOD.
METHOD get_number_2b.
num = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( ) min = 1 max = 100 )->get_next( ).
ENDMETHOD.
ENDCLASS.
"Class 3a
CLASS lcl_class3a DEFINITION INHERITING FROM lcl_class2a FINAL.
PUBLIC SECTION.
METHODS: get_string REDEFINITION.
ENDCLASS.
CLASS lcl_class3a IMPLEMENTATION.
METHOD get_string.
str = |{ super->get_string( ) } How are you doing?|.
ENDMETHOD.
ENDCLASS.
*&--------------------------------------------------------------------*
*& Classes to demonstrate a factory method in a singleton
*& and an abstract class.
*&--------------------------------------------------------------------*
CLASS lcl_singleton DEFINITION CREATE PRIVATE.
PUBLIC SECTION.
METHODS: constructor,
"Methods for setting and getting a time stamp.
get_timestamp RETURNING VALUE(res_timestamp)
TYPE timestampl,
set_timestamp.
CLASS-METHODS:
"Factory method that returns an instance of the class.
factory_method RETURNING VALUE(res_instance)
TYPE REF TO lcl_singleton.
CLASS-DATA: "Holds the number of overall instances.
no_of_instances TYPE i READ-ONLY.
PRIVATE SECTION.
CLASS-DATA: obj TYPE REF TO lcl_singleton.
DATA: timestamp TYPE timestampl.
ENDCLASS.
CLASS lcl_singleton IMPLEMENTATION.
METHOD factory_method.
"Checking if an instance of the class already exists.
"An instance should only be created if no instance exists
"to make sure that there is only a single instance overall.
IF obj IS INITIAL.
CREATE OBJECT obj.
ENDIF.
"In case an instance already exists, the existing one is
"always returned.
res_instance = obj.
ENDMETHOD.
METHOD constructor.
"Counts the number of instances of the class.
no_of_instances = no_of_instances + 1.
ENDMETHOD.
METHOD get_timestamp.
res_timestamp = timestamp.
ENDMETHOD.
METHOD set_timestamp.
GET TIME STAMP FIELD timestamp.
ENDMETHOD.
ENDCLASS.
CLASS lcl_sub DEFINITION DEFERRED.
CLASS lcl_abstract DEFINITION ABSTRACT.
PUBLIC SECTION.
CLASS-METHODS: factory_method IMPORTING check_num TYPE i
RETURNING VALUE(obj) TYPE REF TO lcl_abstract.
CLASS-DATA: message TYPE string.
"Abstract method: There's no implementation in this class.
METHODS: return_string ABSTRACT
IMPORTING i_str TYPE string
RETURNING VALUE(res_string) TYPE string.
ENDCLASS.
CLASS lcl_sub DEFINITION INHERITING FROM lcl_abstract.
PUBLIC SECTION.
METHODS: return_string REDEFINITION.
ENDCLASS.
CLASS lcl_abstract IMPLEMENTATION.
METHOD factory_method.
"Purpose of factory method: An instance can only be created
"if a certain condition is met.
CASE check_num.
WHEN 1.
obj = NEW lcl_sub( ).
message = `Great! I was able to create an instance.`.
WHEN OTHERS.
message = `What a pity. I'm not allowed to create an instance.`.
ENDCASE.
ENDMETHOD.
ENDCLASS.
CLASS lcl_sub IMPLEMENTATION.
METHOD return_string.
res_string = |I'm a returned string. | &&
|The object reference variable is { i_str }.|.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_OBJECTS</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP Object Orientation</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,40 @@
***********************************************************************
*
* Class for ABAP cheat sheet example
*
* ----------------------------- NOTE -----------------------------------
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets in this repository. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
*
***********************************************************************
"! <p class="shorttext synchronized">Class for ABAP cheat sheet example</p>
"! The class supports the ABAP cheat sheet on object orientation and demonstrates the concept of friendship.
CLASS zcl_demo_abap_objects_friend DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
CLASS-METHODS get_strings RETURNING VALUE(res_string) TYPE string_table.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_OBJECTS_FRIEND IMPLEMENTATION.
METHOD get_strings.
"Getting the strings and put them in the string table
APPEND zcl_demo_abap_objects=>public_string TO res_string.
APPEND zcl_demo_abap_objects=>protected_string TO res_string.
APPEND zcl_demo_abap_objects=>private_string TO res_string.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_OBJECTS_FRIEND</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Class for ABAP cheat sheet example</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,506 @@
***********************************************************************
*
* RAP BO consumer for a RAP demo scenario
* ABAP EML in use: RAP calculator (managed, draft-enabled RAP BO with
* late numbering
*
* -------------------------- PURPOSE ----------------------------------
* - This class is the RAP BO consumer for a RAP demo scenario that
* represents a calculator using RAP concepts, i. e. using ABAP EML in
* the context of a managed and draft-enabled RAP business object with
* RAP late numbering to carry out simple calculations. Here, a RAP BO
* instance consists of a calculation ID (which is the key that is finally
* set not until the RAP save sequence), two operands (having integer
* values), the arithmetic operator and the result plus other
* draft-related fields.
* - Underlying data model: Consists of a root entity alone.
* The BDEF defines the behavior for this entity. The definitions in the
* BDEF determine which methods must be implemented in the ABAP behavior
* pool (ABP). Note that the view consists many annotations for the SAP
* Fiori UI.
* - ABP for this scenario: zbp_demo_abap_rap_draft_m
*
* ----------------------- GETTING STARTED (1) -------------------------
* ----------------- Using this class as RAP BO consumer ---------------
*
* - Open the class with the ABAP Development Tools (ADT).
* - Choose F9 to run the class.
* - Check the console output.
* - To understand the context and the ABAP syntax used, check the notes
* included in the class as comments or refer to the respective topic
* in the ABAP Keyword Documentation.
* - Due to the amount of output in the console, the examples include
* numbers (e. g. 1) ..., 2) ..., 3) ...) for the individual example
* sections. Plus, the variable name is displayed in most cases. Hence,
* to easier and faster find the relevant output in the console, just
* search in the console for the number/variable name (STRG+F in the
* console) or use the debugger.
*
* ----------------------- GETTING STARTED (2) -------------------------
* Using the preview version of an SAP Fiori Elements as RAP BO consumer
*
* Create a service binding:
* 1. Find the service definition ZDEMO_ABAP_RAP_CALC_SD in the imported
* package in Business Services -> Service Definitions.
* 2. Right-click the service definition and choose New Service Binding.
* 3. In the New Service Binding pop-up, make the following entries:
* - Name: ZDEMO_ABAP_RAP_CALC_SB
* - Description: Service binding for demo
* - Binding type: OData V2 - UI
* - Service Definition: ZDEMO_ABAP_RAP_CALC_SD (should be already filled)
* 4. Choose Next.
* 5. Assign a transport request and choose Finish.
* 6. The service binding ZDEMO_ABAP_RAP_CALC_SB is opened. Activate the
* service binding.
* 7. In the Service Version Details section, choose the Publish button
* for the Local Service Endpoint. Once the service has been published,
* you should see ZDEMO_ABAP_RAP_DRAFT_M in the Entity Set and Association
* section.
* 8. Activate the service binding once the service has been published.
* 9. Select ZDEMO_ABAP_RAP_DRAFT_M and choose the Preview button.
* 10. The preview version of an SAP Fiori Elements app is displayed. If
* prompted, provide your credentials.
* 11. The app and the managed, draft-enabled RAP BO can be explored. If no
* columns are displayed, choose the 'Settings' button and select the
* desired columns.
* Choosing the 'Go' button refreshes the list. At first use, there
* might not any entry. You can create an entry choosing the 'Create'
* button.
* The late numbering aspects comes into the picture when you, for
* example, create a new instance, i. e. create a new calculation, and
* you keep a draft version of it instead of saving it to the database.
* The calculation ID which represents the key of the instance has an
* initial value. Only when you save the instance to the database, the
* final key is set.
*
* ----------------------------- NOTE -----------------------------------
* This simplified example is not a real life scenario and rather
* focuses on the technical side by giving an idea how the communication
* and data exchange between a RAP BO consumer, which is a class
* in this case, and RAP BO provider can work. Additionally, it shows
* how the methods for non-standard RAP BO operations might be
* self-implemented in an ABP. The example is intentionally kept
* short and simple and focuses on specific RAP aspects. For this reason,
* the example might not fully meet the requirements of the RAP BO contract.
*
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
***********************************************************************
"! <p class="shorttext synchronized">ABAP cheat sheet: ABAP EML in a RAP scenario (draft BO)</p>
"! Example to demonstrate ABAP EML in the context of a RAP demo scenario (managed and draft-enabled RAP business object with RAP late numbering).
"! The class represents a RAP BO consumer.<br>Choose F9 in ADT to run the class.
CLASS zcl_demo_abap_rap_draft_ln_m DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES: if_oo_adt_classrun.
CLASS-METHODS:
class_constructor.
protected section.
PRIVATE SECTION.
CLASS-DATA:
activate_tab TYPE TABLE FOR ACTION IMPORT
zdemo_abap_rap_draft_m~activate,
activate_tab2 TYPE TABLE FOR ACTION IMPORT
zdemo_abap_rap_draft_m~activate,
activate_tab3 TYPE TABLE FOR ACTION IMPORT
zdemo_abap_rap_draft_m~activate,
edit_tab TYPE TABLE FOR ACTION IMPORT
zdemo_abap_rap_draft_m~edit,
read_tab TYPE TABLE FOR READ IMPORT zdemo_abap_rap_draft_m,
f TYPE RESPONSE FOR FAILED zdemo_abap_rap_draft_m,
r TYPE RESPONSE FOR REPORTED zdemo_abap_rap_draft_m,
m TYPE RESPONSE FOR MAPPED zdemo_abap_rap_draft_m.
CLASS-METHODS:
initialize_dbtabs.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_RAP_DRAFT_LN_M IMPLEMENTATION.
METHOD class_constructor.
initialize_dbtabs( ).
ENDMETHOD.
METHOD if_oo_adt_classrun~main.
DATA(output) = NEW zcl_demo_abap_display( out ).
output->display( `RAP Demo: RAP Calculator Using Managed, ` &&
`Draft-Enabled RAP BO (Late Numbering)` ).
output->display( `1) Creating Instances and ` &&
`Saving to the database` ).
"Creating instances; draft indicator %is_draft is enabled
MODIFY ENTITY zdemo_abap_rap_draft_m
CREATE AUTO FILL CID
FIELDS ( num1 arithm_op num2 )
WITH VALUE #(
( %is_draft = if_abap_behv=>mk-on
num1 = 1 arithm_op = '+' num2 = 2 )
( %is_draft = if_abap_behv=>mk-on
num1 = 2 arithm_op = '*' num2 = 4 )
( %is_draft = if_abap_behv=>mk-on
num1 = 3 arithm_op = '-' num2 = 5 )
( %is_draft = if_abap_behv=>mk-on
num1 = 1 arithm_op = '/' num2 = 4 )
( %is_draft = if_abap_behv=>mk-on
num1 = 2 arithm_op = 'P' num2 = 5 ) )
FAILED f
REPORTED r
MAPPED m.
"Displaying responses only if FAILED and REPORTED
"response parameters are not initial
IF f IS NOT INITIAL OR r IS NOT INITIAL.
output->display( `Responses after MODIFY operation` ).
IF m IS NOT INITIAL.
output->display( input = m name = `m` ).
ENDIF.
IF f IS NOT INITIAL.
output->display( input = f name = `f` )..
ENDIF.
IF r IS NOT INITIAL.
output->display( input = r name = `r` ).
ENDIF.
ENDIF.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving draft table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time, draftentitycreationdatetime,
draftentitylastchangedatetime
FROM zdemo_abap_draft
ORDER BY id
INTO TABLE @DATA(draft_parent_before_act).
"Retrieving database table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time
FROM zdemo_abap_tabca
ORDER BY id
INTO TABLE @DATA(db_tab_root_before_act).
"Filling the derived type for the ACTIVATE method by
"getting %pid values
LOOP AT m-calc
ASSIGNING FIELD-SYMBOL(<fs>).
APPEND VALUE #( %pid = <fs>-%pid )
TO activate_tab.
ENDLOOP.
MODIFY ENTITY zdemo_abap_rap_draft_m
EXECUTE activate AUTO FILL CID WITH activate_tab
MAPPED m
FAILED f
REPORTED r.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving draft table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time, draftentitycreationdatetime,
draftentitylastchangedatetime
FROM zdemo_abap_draft
ORDER BY id
INTO TABLE @DATA(draft_parent_afer_act).
"Retrieving database table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time
FROM zdemo_abap_tabca
ORDER BY id
INTO TABLE @DATA(db_tab_root_after_act).
"Displaying entries
output->display( `1a) Draft and database tables before ` &&
`ACTIVATE action` ).
output->display( `Draft table before activation` ).
output->display( input = draft_parent_before_act name = `draft_parent_before_act` ).
output->display( `Database table before activation` ).
output->display( input = db_tab_root_before_act name = `db_tab_root_before_act` ).
output->next_section( `1b) Draft and database tables after ` &&
`ACTIVATE action` ).
output->display( `Draft table after activation` ).
output->display( input = draft_parent_afer_act name = `draft_parent_afer_act` ).
output->display( `Database table after activation` ).
output->display( input = db_tab_root_after_act name = `db_tab_root_after_act` ).
**********************************************************************
output->next_section( `2) Creating Invalid Instances` ).
"Purposely creating invalid instances;
"draft indicator %is_draft is enabled
MODIFY ENTITY zdemo_abap_rap_draft_m
CREATE AUTO FILL CID
FIELDS ( num1 arithm_op num2 )
WITH VALUE #(
( %is_draft = if_abap_behv=>mk-on
num1 = 1 arithm_op = 'a' num2 = 1 ) "wrong operator
( %is_draft = if_abap_behv=>mk-on
num1 = 1 arithm_op = '/' num2 = 0 ) "0 division
( %is_draft = if_abap_behv=>mk-on
num1 = 2 arithm_op = 'P' num2 = 12345 ) ) "arithmetic overflow
FAILED f
REPORTED r
MAPPED m.
"Displaying responses only if FAILED and REPORTED
"response parameters are not initial.
IF f IS NOT INITIAL OR r IS NOT INITIAL.
output->display( input = `Responses after MODIFY operation` ).
IF m IS NOT INITIAL.
output->display( input = m name = `m` ).
ENDIF.
IF f IS NOT INITIAL.
output->display( input = f name = `f` )..
ENDIF.
IF r IS NOT INITIAL.
output->display( input = r name = `r` ).
ENDIF.
ENDIF.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving draft table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time, draftentitycreationdatetime,
draftentitylastchangedatetime
FROM zdemo_abap_draft
ORDER BY id
INTO TABLE @draft_parent_before_act.
"Retrieving database table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time
FROM zdemo_abap_tabca
ORDER BY id
INTO TABLE @db_tab_root_before_act.
"Filling the derived type for the ACTIVATE method by
"getting %pid values; here, another table is filled for later use
LOOP AT m-calc
ASSIGNING FIELD-SYMBOL(<fs2>).
APPEND VALUE #( %pid = <fs2>-%pid )
TO activate_tab2.
APPEND VALUE #( %pid = <fs2>-%pid )
TO activate_tab3.
ENDLOOP.
MODIFY ENTITY zdemo_abap_rap_draft_m
EXECUTE activate AUTO FILL CID WITH activate_tab2
MAPPED m
FAILED f
REPORTED r.
"Displaying responses only if FAILED and REPORTED
"response parameters are not initial.
IF f IS NOT INITIAL OR r IS NOT INITIAL.
output->display( input = `Responses after MODIFY operation` ).
IF m IS NOT INITIAL.
output->display( input = m name = `m` ).
ENDIF.
IF f IS NOT INITIAL.
output->display( input = f name = `f` )..
ENDIF.
IF r IS NOT INITIAL.
output->display( input = r name = `r` ).
ENDIF.
ENDIF.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving draft table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time, draftentitycreationdatetime,
draftentitylastchangedatetime
FROM zdemo_abap_draft
ORDER BY id
INTO TABLE @draft_parent_afer_act.
"Retrieving database table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time
FROM zdemo_abap_tabca
ORDER BY id
INTO TABLE @db_tab_root_after_act.
"Displaying entries
output->next_section( `2a) Draft and database tables before ` &&
`ACTIVATE action` ).
output->display( `Draft table before activation` ).
output->display( input = draft_parent_before_act name = `draft_parent_before_act` ).
output->display( `Database table before activation` ).
output->display( input = db_tab_root_before_act name = `db_tab_root_before_act` ).
output->next_section( `2b) Draft and database tables after ` &&
`ACTIVATE action` ).
output->display( `Draft table after activation` ).
output->display( input = draft_parent_afer_act name = `draft_parent_afer_act` ).
output->display( `Database table after activation` ).
output->display( input = db_tab_root_after_act name = `db_tab_root_after_act` ).
**********************************************************************
output->next_section( `3) Correcting and Updating Invalid Instances` ).
"Preparing the derived type for the read operation to
"retrieve the field values; the draft indicator is enabled
LOOP AT activate_tab3 ASSIGNING FIELD-SYMBOL(<fs3>).
APPEND VALUE #( %pky = <fs3>-%pky
%is_draft = if_abap_behv=>mk-on
%control-id = if_abap_behv=>mk-on
%control-num1 = if_abap_behv=>mk-on
%control-arithm_op = if_abap_behv=>mk-on
%control-num2 = if_abap_behv=>mk-on
%control-calc_result = if_abap_behv=>mk-on
%control-crea_date_time = if_abap_behv=>mk-on
%control-lchg_date_time = if_abap_behv=>mk-on
) TO read_tab.
ENDLOOP.
"Retrieving the entries of the invalid instances
READ ENTITY zdemo_abap_rap_draft_m
ALL FIELDS WITH read_tab
RESULT DATA(result).
"Correcting and updating the invalid instances
MODIFY ENTITY zdemo_abap_rap_draft_m
UPDATE FROM VALUE #(
FOR wa IN result (
%pid = wa-%pid
%is_draft = if_abap_behv=>mk-on
num2 = SWITCH #( wa-calc_result
WHEN `Division by 0` THEN 2
WHEN `Overflow error` THEN 3 )
arithm_op = SWITCH #( wa-calc_result
WHEN `Wrong operator` THEN '+' )
%control-num2 = SWITCH #( wa-calc_result
WHEN `Division by 0` THEN if_abap_behv=>mk-on
WHEN `Overflow error` THEN if_abap_behv=>mk-on
ELSE if_abap_behv=>mk-off )
%control-arithm_op = SWITCH #( wa-calc_result
WHEN `Wrong operator` THEN if_abap_behv=>mk-on
ELSE if_abap_behv=>mk-off ) ) )
FAILED f
REPORTED r
MAPPED m.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
MODIFY ENTITY zdemo_abap_rap_draft_m
EXECUTE activate AUTO FILL CID WITH activate_tab3
MAPPED m
FAILED f
REPORTED r.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving draft table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time, draftentitycreationdatetime,
draftentitylastchangedatetime
FROM zdemo_abap_draft
ORDER BY id
INTO TABLE @draft_parent_afer_act.
"Retrieving database table entries
SELECT id, num1, arithm_op, num2, calc_result, crea_date_time,
lchg_date_time
FROM zdemo_abap_tabca
ORDER BY id
INTO TABLE @db_tab_root_after_act.
"Displaying entries
output->display( input = `Draft and database tables after ` &&
`ACTIVATE action` ).
output->display( `Draft table after activation` ).
output->display( input = draft_parent_afer_act name = `draft_parent_afer_act` ).
output->display( `Database table after activation` ).
output->display( input = db_tab_root_after_act name = `db_tab_root_after_act` ).
ENDMETHOD.
METHOD initialize_dbtabs.
DELETE FROM zdemo_abap_tabca.
DELETE FROM zdemo_abap_draft.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_RAP_DRAFT_LN_M</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP EML in a RAP scenario (draft BO)</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,975 @@
***********************************************************************
*
* RAP BO consumer for a RAP demo scenario:
* ABAP EML in use: Managed RAP BO with external numbering
*
* -------------------------- PURPOSE ----------------------------------
* - This class is the RAP BO consumer for a RAP demo scenario that
* demonstrates various RAP BO standard operations and non-standard
* operations using ABAP EML in the context of a managed RAP business
* object with RAP external numbering.
* See also the ABAP for RAP (EML) ABAP cheat sheet.
* - Topics covered: RAP BO operations like create (including a
* determination on save), update, delete, executing an action, validation,
* create-by-association (parent to child), read (root entity),
* read-by-association (parent to child), read (child entity),
* read-by-association (child to parent)
* - Underlying data model: Consists of a root entity and one child entity.
* The BDEF defines the behavior for these two entities which are connected
* via a CDS composition relation. The definitions in the BDEF determine
* which methods must be implemented in the ABAP behavior pool (ABP).
* - ABP for this scenario: zbp_demo_abap_rap_ro_m
*
* ----------------------- GETTING STARTED -----------------------------
* - Open the class with the ABAP Development Tools (ADT).
* - Choose F9 to run the class.
* - Check the console output.
* - To understand the context and the ABAP syntax used, check the notes
* included in the class as comments or refer to the respective topic
* in the ABAP Keyword Documentation.
* - Due to the amount of output in the console, the examples include
* numbers (e. g. 1) ..., 2) ..., 3) ...) for the individual example
* sections. Plus, the variable name is displayed in most cases. Hence,
* to easier and faster find the relevant output in the console, just
* search in the console for the number/variable name (STRG+F in the
* console) or use the debugger.
*
* ----------------------------- NOTE -----------------------------------
* This simplified example is not a real life scenario and rather
* focuses on the technical side by giving an idea how the communication
* and data exchange between a RAP BO consumer, which is a class
* in this case, and RAP BO provider can work. Additionally, it shows
* how the methods for non-standard RAP BO operations might be
* self-implemented in an ABP. The example is intentionally kept
* short and simple and focuses on specific RAP aspects. For this reason,
* the example might not fully meet the requirements of the RAP BO contract.
*
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
***********************************************************************
"! <p class="shorttext synchronized">ABAP cheat sheet: ABAP EML in a RAP scenario (managed BO)</p>
"! Example to demonstrate ABAP EML in the context of a RAP demo scenario (managed RAP BO with external numbering).
"! The class represents a RAP BO consumer.<br>Choose F9 in ADT to run the class.
CLASS zcl_demo_abap_rap_ext_num_m DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES: if_oo_adt_classrun.
CLASS-METHODS:
class_constructor.
protected section.
PRIVATE SECTION.
CLASS-DATA:
failed TYPE RESPONSE FOR FAILED zdemo_abap_rap_ro_m,
reported TYPE RESPONSE FOR REPORTED zdemo_abap_rap_ro_m,
mapped TYPE RESPONSE FOR MAPPED zdemo_abap_rap_ro_m.
CLASS-METHODS:
initialize_dbtabs,
"If there are entries in the response parameters following EML
"requests, they should be processed for displaying purposes.
extract_from_reported RETURNING VALUE(messages) TYPE string_table,
extract_from_failed RETURNING VALUE(errors) TYPE string_table,
fill_db_tab.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_RAP_EXT_NUM_M IMPLEMENTATION.
METHOD class_constructor.
initialize_dbtabs( ).
ENDMETHOD.
METHOD extract_from_failed.
CLEAR errors.
LOOP AT failed-root ASSIGNING FIELD-SYMBOL(<err>).
DATA op TYPE string.
CASE if_abap_behv=>mk-on.
WHEN <err>-%op-%create.
op = `create operation`.
WHEN <err>-%op-%update.
op = `update operation`.
WHEN <err>-%op-%delete.
op = `delete operation`.
WHEN <err>-%op-%assoc-_child.
op = `operation involving the child entity`.
WHEN <err>-%op-%action-multiply_by_2.
op = `executing action multiply_by_2`.
WHEN OTHERS. op = `operation`.
ENDCASE.
APPEND `Error for instance with ` &&
COND #( WHEN <err>-%cid IS NOT INITIAL THEN `%cid = `
&& <err>-%cid
ELSE `key = ` && <err>-key_field ) &&
`: Fail cause ` && <err>-%fail-cause && ` for ` && op
&& `.` TO errors.
ENDLOOP.
IF failed-child IS NOT INITIAL.
LOOP AT failed-child ASSIGNING FIELD-SYMBOL(<err_ch>).
APPEND `Error for child instance with key_field = ` &&
<err_ch>-key_field && ` and key_ch = ` &&
<err_ch>-key_ch && `: Fail cause `
&& <err_ch>-%fail-cause && `.` TO errors.
ENDLOOP.
ENDIF.
ENDMETHOD.
METHOD extract_from_reported.
CLEAR messages.
LOOP AT reported-root ASSIGNING FIELD-SYMBOL(<rep>).
IF <rep>-%global = if_abap_behv=>mk-on.
APPEND <rep>-%msg->m_severity &&
<rep>-%msg->if_t100_dyn_msg~msgv1 TO messages.
ELSE.
APPEND `Message for instance with ` &&
COND #( WHEN <rep>-%cid IS NOT INITIAL
THEN `%cid = ` && <rep>-%cid
ELSE `key = ` && <rep>-key_field ) &&
`: ` && <rep>-%msg->m_severity && ` ` &&
<rep>-%msg->if_t100_dyn_msg~msgv1 TO messages.
ENDIF.
ENDLOOP.
IF reported-child IS NOT INITIAL.
LOOP AT reported-child ASSIGNING FIELD-SYMBOL(<rep_ch>).
APPEND `Message for child instance with key_field = ` &&
<rep_ch>-key_field && ` and key_ch = `
&& <rep_ch>-key_ch && `: ` && <rep_ch>-%msg->m_severity &&
` ` && <rep_ch>-%msg->if_t100_dyn_msg~msgv1 TO messages.
ENDLOOP.
ENDIF.
ENDMETHOD.
METHOD fill_db_tab.
MODIFY zdemo_abap_rapt1 FROM TABLE @( VALUE #(
( key_field = 4
field1 = 'ggg'
field2 = 'hhh'
field3 = 40
field4 = 41 ) ) ).
ENDMETHOD.
METHOD if_oo_adt_classrun~main.
DATA(output) = NEW zcl_demo_abap_display( out ).
output->display( `RAP Demo: RAP BO Operations Using a Managed ` &&
`RAP BO` ).
**********************************************************************
*
* Create operation
*
**********************************************************************
output->display( `1) Create operation` ).
"Adding an entry to the database table to provoke an error for the
"EML create request.
fill_db_tab( ).
**********************************************************************
* Notes:
* - field4 is purposely not included in the FIELDS list
* - Effect:
* - %control value for field4 is set to if_abap_behv=>mk-off
* - Although the derived type (created inline here) includes a
* value assignment for field4 in an instance, the field value is
* not saved. The initial value is used.
* - The instance with key_field = 4 will not be saved since an entry
* already exists in the database table with the same key.
* - Response parameters are specified to receive information.
* - A COMMIT ENTITIES statement triggers the saving of the instances.
* - The example BDEF includes the definition of a determination on
* save for create operations. In this case, the determination
* adds some text to the value in field2.
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 )
WITH VALUE #( ( %cid = 'cid1'
key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 10
field4 = 11 ) "Value not considered
( %cid = 'cid2'
key_field = 2
field1 = 'ccc'
field2 = 'ddd'
field3 = 20 )
( %cid = 'cid3'
key_field = 3
field1 = 'eee'
field2 = 'fff'
field3 = 30 )
( %cid = 'cid4' "Instance to fail
key_field = 4
field1 = 'error'
field2 = 'error'
field3 = 99 ) )
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @DATA(tab_root).
output->display( input = tab_root name = `tab_root` ).
"Displaying response information
IF mapped-root IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root entity)` ).
output->display( input = mapped-root name = `mapped-root` ).
ENDIF.
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Update operations
*
**********************************************************************
output->next_section( `2) Update operation` ).
**********************************************************************
* Notes:
* - The EML request includes a create and an update request. The
* create request is included to have a %cid to refer to for demo
* purposes. This instance has not yet been persisted.
* - The EML statement for the create operation includes the ABAP
* FROM ... (instead of FIELDS ( ... ) WITH ...) for demo purposes.
* Here, the %control values must be set explicitly.
* - The update request purposely excludes field2 so as not to update
* the value of this particular field.
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FROM VALUE #(
%control-key_field = if_abap_behv=>mk-on
%control-field1 = if_abap_behv=>mk-on
%control-field2 = if_abap_behv=>mk-on
%control-field3 = if_abap_behv=>mk-on
%control-field4 = if_abap_behv=>mk-on
( %cid = 'cid5'
key_field = 5
field1 = 'iii'
field2 = 'jjj'
field3 = 50
field4 = 51 ) )
UPDATE FIELDS ( field1 field3 field4 )
WITH VALUE #(
"Update via cid_ref
( %cid_ref = 'cid5'
field1 = 'up_kkk'
field2 = 'up_lll' "Value not considered
field3 = 500
field4 = 501 )
"Updates via key
( key_field = 1
field1 = 'up_mmm'
field3 = 100
field4 = 101 )
( key_field = 2
field1 = 'up_ooo'
field3 = 200
field4 = 201 )
( key_field = 99 "Instance to fail
field1 = 'error'
field3 = 99
field4 = 99 ) )
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @tab_root.
output->display( input = tab_root name = `tab_root` ).
"Displaying response information
IF mapped-root IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root entity)` ).
output->display( input = mapped-root name = `mapped-root` ).
ENDIF.
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Delete operation
*
**********************************************************************
output->next_section( `3) Delete operation` ).
**********************************************************************
* Notes:
* - The EML request includes a create and an delete request. The
* create request is included to have a %cid to refer to for demo
* purposes. This instance has not yet been persisted.
* - EML statements for delete operations can only be used with the
* ABAP word FROM ....
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 field4 )
WITH VALUE #(
( %cid = 'cid_del'
key_field = 6
field1 = 'mmm'
field2 = 'nnn'
field3 = 60
field4 = 61 ) )
DELETE FROM VALUE #(
"Deletion via %cid_ref
( %cid_ref = 'cid_del' )
"Deletions via key
( key_field = 4 )
( key_field = 5 )
"Instance to fail
( key_field = 100 ) ) "Key not available
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @tab_root.
output->display( input = tab_root name = `tab_root` ).
"Displaying response information
IF mapped-root IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root entity)` ).
output->display( input = mapped-root name = `mapped-root` ).
ENDIF.
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Action multiply_by_2
*
**********************************************************************
output->next_section( `4) Action execution: mutliply_by_2` ).
**********************************************************************
* Notes:
* - The EML request includes a create request and a request to execute
* an action. The create request is included to have a %cid to refer
* to for demo purposes. This instance has not yet been persisted.
* - EML statements for executing actions can only be used with the
* ABAP word FROM ....
* - As the name implies, the action multiplies field
* values (field3 and field4) by 2 for requested instances.
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 field4 )
WITH VALUE #(
( %cid = 'cid_x2'
key_field = 7
field1 = 'ooo'
field2 = 'ppp'
field3 = 70
field4 = 71 ) )
EXECUTE multiply_by_2 FROM VALUE #(
"Executing action via %cid_ref
( %cid_ref = 'cid_x2' )
"Executing action via key
( key_field = 1 )
( key_field = 2 )
( key_field = 1234 ) ) "Instance to fail
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @tab_root.
output->display( input = tab_root name = `tab_root` ).
"Displaying response information
IF mapped-root IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root entity)` ).
output->display( input = mapped-root name = `mapped-root` ).
ENDIF.
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Create-by-association operation (from root to child entity)
*
**********************************************************************
output->next_section( `5) Create-by-association operation (from parent to child)` ).
**********************************************************************
* Notes:
* - The EML request includes a create and create-by-association
* request, i. e. a "deep create". An instance is created for the
* parent entity and, in the same request and based on this
* instance, instances are created for the child entity, too.
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 field4 )
WITH VALUE #(
( %cid = 'cid_cba'
key_field = 9
field1 = 'qqq'
field2 = 'rrr'
field3 = 90
field4 = 91 ) )
CREATE BY \_child
FIELDS ( key_ch field_ch1 field_ch2 ) WITH VALUE #(
"CBA operation via %cid_ref
( %cid_ref = 'cid_cba'
%target = VALUE #( ( %cid = 'cid_ch1'
key_ch = 9
field_ch1 = 'aaa_ch'
field_ch2 = 99 )
( %cid = 'cid_ch2'
key_ch = 10
field_ch1 = 'bbb_ch'
field_ch2 = 100 ) ) )
"CBA operation via root key
( key_field = 1
%target = VALUE #( ( %cid = 'cid_ch3'
key_ch = 1
field_ch1 = 'ccc_ch'
field_ch2 = 11 )
( %cid = 'cid_ch4'
key_ch = 2
field_ch1 = 'ddd_ch'
field_ch2 = 22 ) ) )
( key_field = 2
%target = VALUE #( ( %cid = 'cid_ch5'
key_ch = 3
field_ch1 = 'ccc_ch'
field_ch2 = 33 )
( %cid = 'cid_ch6'
key_ch = 4
field_ch1 = 'ddd_ch'
field_ch2 = 44 ) ) )
"Instance to fail
( key_field = 123
%target = VALUE #( ( %cid = 'cid_ch7'
key_ch = 1
field_ch1 = 'error'
field_ch2 = 2 )
( %cid = 'cid_ch8'
key_ch = 2
field_ch1 = 'error'
field_ch2 = 3 ) ) )
)
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES.
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @tab_root.
SELECT FROM zdemo_abap_rapt2
FIELDS key_field, key_ch, field_ch1, field_ch2
ORDER BY key_field, key_ch
INTO TABLE @DATA(tab_child).
output->display( input = tab_root name = `tab_root` ).
output->display( input = tab_child name = `tab_child` ).
"Displaying response information
IF mapped IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root and child entity)` ).
output->display( input = mapped name = `mapped` ).
ENDIF.
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Validation val
*
**********************************************************************
output->next_section( `6) Validation val` ).
**********************************************************************
* Notes:
* - The EML request includes a create request. The validation's
* handler method is implementation in a way that the saving of
* instances is disabled if a field value is not allowed. In this
* example, the value of the integer in field3 shall not exceed 1000.
* Here, the third instance will fail for the validation.
* Consequently, all instances of this request are not saved to the
* database. Either all is ok and will be saved or nothing.
* - Note that the response information for the validation is only
* available in the response parameters of the COMMIT ENTITIES
* statement. Here, the BDEF derived type is
* ... TYPE RESPONSE FOR ... LATE ....
**********************************************************************
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 field4 )
WITH VALUE #(
( %cid = 'cid_val1'
key_field = 123
field1 = 'sss'
field2 = 'ttt'
field3 = 1
field4 = 2 )
( %cid = 'cid_val2'
key_field = 456
field1 = 'uuu'
field2 = 'vvv'
field3 = 3
field4 = 4 )
( %cid = 'cid_val3'
key_field = 789
field1 = 'www'
field2 = 'xxx'
field3 = 1001
field4 = 5 ) )
MAPPED mapped
FAILED failed
REPORTED reported.
COMMIT ENTITIES RESPONSES
FAILED DATA(failed_late)
REPORTED DATA(reported_late).
IF sy-subrc <> 0.
output->display( `An issue occurred in the RAP save sequence.` ).
ENDIF.
"Retrieving and displaying database content
SELECT FROM zdemo_abap_rapt1
FIELDS key_field, field1, field2, field3, field4
ORDER BY key_field
INTO TABLE @tab_root.
output->display( input = tab_root name = `tab_root` ).
"Displaying response information
IF mapped IS NOT INITIAL.
output->display( `Entries in MAPPED response parameter ` &&
`(root and child entity)` ).
output->display( input = mapped name = `mapped` ).
ENDIF.
IF failed_late IS NOT INITIAL.
output->display( `Entries in FAILED LATE response parameter` ).
output->display( input = failed_late name = `failed_late` ).
ENDIF.
IF reported_late IS NOT INITIAL.
output->display( `Entries in REPORTED LATE response parameter` ).
output->display( input = reported_late name = `reported_late` ).
ENDIF.
**********************************************************************
*
* Read operation (root entity)
*
**********************************************************************
output->next_section( `7) Read operation (root entity)` ).
**********************************************************************
* Notes:
* - The EML request includes a read request. The EML statement uses
* the ABAP words ALL FIELDS WITH. In this case, as the name implies,
* all field values are retrieved. The %control values for all fields
* are set to if_abap_behv=>mk-on.
* - When using the ABAP words FIELDS ( ... ) WITH and specifying the
* concrete fields to be read, only for those fields %control is
* set accordingly.
* - Filling the parameter for RESULT is mandatory.
**********************************************************************
READ ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
ALL FIELDS WITH VALUE #(
( key_field = 1 )
( key_field = 2 )
( key_field = 7 )
( key_field = 5 ) ) "Instance to fail
RESULT DATA(result)
FAILED failed
REPORTED reported.
"Displaying the read result
output->display( input = result name = `result` ).
"Displaying response information
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
*********************************************************************
*
* Read operation (child entity)
*
**********************************************************************
output->next_section( `8) Read operation (child entity)` ).
**********************************************************************
* Notes:
* - The EML request includes a read request. The read operation is
* executed on the child entity directly by specifying the alias, as
* it is defined in the BDEF, following the ABAP word ENTITY.
* - All field values are read using the addition ALL FIELDS WITH.
**********************************************************************
READ ENTITIES OF zdemo_abap_rap_ro_m
ENTITY child
ALL FIELDS WITH VALUE #(
( key_field = 1 key_ch = 1 )
( key_field = 2 key_ch = 4 )
"Instances to fail
( key_field = 9 )
( key_field = 9 key_ch = 11 ) )
RESULT DATA(read_ch)
FAILED failed
REPORTED reported.
"Displaying read result
output->display( input = read_ch name = `read_ch` ).
"Displaying response information
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Read-by-association operation (from parent to child)
*
**********************************************************************
output->next_section( `9) Read-by-association operation (from parent to child)` ).
**********************************************************************
* Notes:
* - The EML request includes a read-by-association request from the
* parent to the child.
* - All field values are read using the addition ALL FIELDS WITH.
* - Specifying the parameter for RESULT is mandatory.
* - Additionally, the optional association links are retrieved.
**********************************************************************
READ ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
BY \_child
ALL FIELDS WITH VALUE #(
( key_field = 2 )
( key_field = 9 )
( key_field = 999 ) ) "Instance to fail
RESULT DATA(rba_result)
LINK DATA(association_links)
FAILED failed
REPORTED reported.
"Displaying read result and association links
output->display( input = rba_result name = `rba_result` ).
output->display( input = association_links name = `association_links` ).
"Displaying response information
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Read-by-association operation (from child to parent)
*
**********************************************************************
output->next_section( `10) Read-by-association operation (from child to parent)` ).
**********************************************************************
* Notes:
* - The EML request includes a read-by-association request from the
* child to the parent.
* - All field values are read using the addition ALL FIELDS WITH.
* - Specifying the parameter for RESULT is mandatory.
* - Additionally, the optional association links are retrieved.
**********************************************************************
READ ENTITIES OF zdemo_abap_rap_ro_m
ENTITY child
BY \_parent ALL FIELDS WITH VALUE #(
( key_field = 1 key_ch = 1 )
( key_field = 2 key_ch = 4 )
"Instances to fail
( key_field = 1 key_ch = 3 )
( key_field = 543 key_ch = 1 ) )
RESULT DATA(rba_parent)
LINK DATA(association_links_parent)
FAILED failed
REPORTED reported.
"Displaying read result and association links
output->display( input = rba_parent name = `rba_parent` ).
output->display( input = association_links_parent name = `association_links_parent` ).
"Displaying response information
IF failed IS NOT INITIAL.
output->display( `Entries in FAILED response parameter` ).
output->display( input = extract_from_failed( ) name = `extract_from_failed( )` ).
ENDIF.
IF reported IS NOT INITIAL.
output->display( `Entries in REPORTED response parameter` ).
output->display( input = extract_from_reported( ) name = `extract_from_reported( )` ).
ENDIF.
**********************************************************************
*
* Excursion: Read and read-by-association operation using dynamic
* EML statements
*
**********************************************************************
* output->next_section( `11) Excursion: Read and read-by-association ` &&
* `operations using dynamic EML` ).
* DATA:
* op_tab TYPE abp_behv_retrievals_tab,
* read_dyn TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m,
* read_dyn_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m,
* rba_dyn TYPE TABLE FOR READ IMPORT
* zdemo_abap_rap_ro_m\_child,
* rba_dyn_result TYPE TABLE FOR READ RESULT
* zdemo_abap_rap_ro_m\_child,
* rba_dyn_link TYPE TABLE FOR READ LINK zdemo_abap_rap_ro_m\_child.
*
* read_dyn = VALUE #(
* ( %key-key_field = 1
* %control = VALUE #(
* field1 = if_abap_behv=>mk-on
* field2 = if_abap_behv=>mk-on
* field3 = if_abap_behv=>mk-on
* field4 = if_abap_behv=>mk-on ) )
* ( %key-key_field = 2
* %control = VALUE #(
* field1 = if_abap_behv=>mk-on
* field2 = if_abap_behv=>mk-on
* field3 = if_abap_behv=>mk-on
* field4 = if_abap_behv=>mk-on ) ) ).
*
* rba_dyn = VALUE #(
* ( %key-key_field = 1
* %control = VALUE #(
* key_field = if_abap_behv=>mk-on
* key_ch = if_abap_behv=>mk-on
* field_ch1 = if_abap_behv=>mk-on
* field_ch2 = if_abap_behv=>mk-on ) )
* ( %key-key_field = 2
* %control = VALUE #(
* key_field = if_abap_behv=>mk-on
* key_ch = if_abap_behv=>mk-on
* field_ch1 = if_abap_behv=>mk-on
* field_ch2 = if_abap_behv=>mk-on ) ) ).
*
* op_tab = VALUE #(
* ( op = if_abap_behv=>op-r-read
* entity_name = 'ZDEMO_ABAP_RAP_RO_M'
* instances = REF #( read_dyn )
* results = REF #( read_dyn_result ) )
* ( op = if_abap_behv=>op-r-read_ba
* entity_name = 'ZDEMO_ABAP_RAP_RO_M'
* sub_name = '_CHILD'
* full = abap_true
* instances = REF #( rba_dyn )
* results = REF #( rba_dyn_result )
* links = REF #( rba_dyn_link ) ) ).
*
* READ ENTITIES OPERATIONS op_tab.
*
* output->display( `Read result (root)` ).
* output->display( input = read_dyn_result name = `read_dyn_result` ).
* output->display( `Read result (read-by-association)` ).
* output->display( input = rba_dyn_result name = `rba_dyn_result` ).
* output->display( `Links` ).
* output->display( input = rba_dyn_link name = `rba_dyn_link` ).
ENDMETHOD.
METHOD initialize_dbtabs.
DELETE FROM zdemo_abap_rapt1.
DELETE FROM zdemo_abap_rapt2.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_RAP_EXT_NUM_M</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP EML in a RAP scenario (managed BO)</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_RAP_EXT_NUM_U</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP EML in a RAP scenario (unmanaged BO)</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_SQL</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP SQL</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,175 @@
***********************************************************************
*
* ABAP cheat sheet: ABAP SQL - Grouping Internal Tables
*
* -------------------------- PURPOSE ----------------------------------
* - Example to demonstrate syntactical options when grouping internal
* tables.
*
* ----------------------- GETTING STARTED -----------------------------
* - Open the class with the ABAP Development Tools (ADT).
* - Choose F9 to run the class.
* - Check the console output.
* - To understand the context and the ABAP syntax used, check the notes
* included in the class as comments or refer to the respective topic
* in the ABAP Keyword Documentation.
* - Due to the amount of output in the console, the examples include
* numbers (e. g. 1) ..., 2) ..., 3) ...) for the individual example
* sections. Plus, the variable name is displayed in most cases. Hence,
* to easier and faster find the relevant output in the console, just
* search in the console for the number/variable name (STRG+F in the
* console) or use the debugger.
* ----------------------------- NOTE -----------------------------------
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
*
***********************************************************************
"! <p class="shorttext synchronized">ABAP cheat sheet: ABAP SQL - Grouping Internal Tables</p>
"! Example to demonstrate working with structures.<br>Choose F9 in ADT to run the class.
CLASS zcl_demo_abap_sql_group_by DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES: if_oo_adt_classrun.
CLASS-METHODS: class_constructor.
protected section.
PRIVATE SECTION.
CLASS-DATA:
wa TYPE zdemo_abap_flsch,
member TYPE zdemo_abap_flsch,
members TYPE STANDARD TABLE OF zdemo_abap_flsch WITH EMPTY KEY.
ENDCLASS.
CLASS ZCL_DEMO_ABAP_SQL_GROUP_BY IMPLEMENTATION.
METHOD class_constructor.
"Fill demo database tables.
zcl_demo_abap_flight_tables=>fill_dbtabs( ).
ENDMETHOD.
METHOD if_oo_adt_classrun~main.
DATA(output) = NEW zcl_demo_abap_display( out ).
output->display( `Demo: Grouping Internal Tables` ).
SELECT *
FROM zdemo_abap_flsch
INTO TABLE @DATA(fli_tab).
output->next_section( `1) Representative Binding` ).
output->display( `1a) Grouping by one column` ).
LOOP AT fli_tab INTO wa
GROUP BY wa-carrid.
output->display( wa-carrid ).
ENDLOOP.
output->next_section( `1b) Members of one column groups` ).
LOOP AT fli_tab INTO wa
GROUP BY wa-carrid.
CLEAR members.
LOOP AT GROUP wa INTO member.
members = VALUE #( BASE members ( member ) ).
ENDLOOP.
output->display( members ).
ENDLOOP.
output->next_section( `1c) Grouping by two columns` ).
LOOP AT fli_tab INTO wa
GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom ).
output->display( |{ wa-carrid } { wa-airpfrom }| ).
ENDLOOP.
output->next_section( `1d) Members of two column groups` ).
LOOP AT fli_tab INTO wa
GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom ).
CLEAR members.
LOOP AT GROUP wa INTO member.
members = VALUE #( BASE members ( member ) ).
ENDLOOP.
output->display( members ).
ENDLOOP.
output->next_section( `2) Group Key Binding` ).
output->display( `2a) Grouping by one column` ).
LOOP AT fli_tab INTO wa
GROUP BY wa-carrid
INTO DATA(key).
output->display( key ).
ENDLOOP.
output->next_section( `2b) Members of one column groups` ).
LOOP AT fli_tab INTO wa
GROUP BY wa-carrid
INTO key.
CLEAR members.
LOOP AT GROUP key INTO member.
members = VALUE #( BASE members ( member ) ).
ENDLOOP.
output->display( members ).
ENDLOOP.
output->next_section( `2c) Grouping by two columns` ).
LOOP AT fli_tab INTO wa
GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom )
INTO DATA(keys).
output->display( keys ).
ENDLOOP.
output->next_section( `2d) Members of two column groups` ).
LOOP AT fli_tab INTO wa
GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom )
INTO keys.
CLEAR members.
LOOP AT GROUP keys INTO member.
members = VALUE #( BASE members ( member ) ).
ENDLOOP.
output->display( members ).
ENDLOOP.
output->next_section( `2e) Two column groups without members` ).
LOOP AT fli_tab INTO wa
GROUP BY ( key1 = wa-carrid key2 = wa-airpfrom
index = GROUP INDEX size = GROUP SIZE )
WITHOUT MEMBERS
INTO DATA(keysplus).
output->display( keysplus ).
ENDLOOP.
ENDMETHOD.
ENDCLASS.

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_SQL_GROUP_BY</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: ABAP SQL - Grouping Internal Tables</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_STRING_PROC</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: String processing</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_CLAS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOCLASS>
<CLSNAME>ZCL_DEMO_ABAP_STRUCTURES</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>ABAP cheat sheet: Structures</DESCRIPT>
<STATE>1</STATE>
<CLSCCINCL>X</CLSCCINCL>
<FIXPT>X</FIXPT>
<UNICODE>X</UNICODE>
</VSEOCLASS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_CARR</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table: Airline</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_CARR</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>MANDT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CARRID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CARRNAME</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000040</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000020</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CURRCODE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000010</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CUKY</DATATYPE>
<LENG>000005</LENG>
<MASK> CUKY</MASK>
</DD03P>
<DD03P>
<FIELDNAME>URL</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000510</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000255</LENG>
<MASK> CHAR</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_CARR</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_CARR</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_DRAFT</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<LANGDEP>X</LANGDEP>
<DDTEXT>Draft table for RAP calculator</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_DRAFT</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>ID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ROLLNAME>SYSUUID_X16</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<NOTNULL>X</NOTNULL>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>DRAFTUUID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ROLLNAME>SYSUUID_X16</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<NOTNULL>X</NOTNULL>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>NUM1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>ARITHM_OP</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000002</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000001</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUM2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CALC_RESULT</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>g</INTTYPE>
<INTLEN>000008</INTLEN>
<DATATYPE>STRG</DATATYPE>
<MASK> STRG</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CREA_DATE_TIME</FIELDNAME>
<ROLLNAME>TIMESTAMPL</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>LCHG_DATE_TIME</FIELDNAME>
<ROLLNAME>TIMESTAMPL</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>.INCLUDE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<PRECFIELD>SYCH_BDL_DRAFT_ADMIN_INC</PRECFIELD>
<MASK> S</MASK>
<DDTEXT>Standard Include for Draft Administration (BDL Syntax Check)</DDTEXT>
<COMPTYPE>S</COMPTYPE>
<GROUPNAME>%ADMIN</GROUPNAME>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_DRAFT</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_DRAFT</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

192
src/zdemo_abap_fli.tabl.xml Normal file
View File

@@ -0,0 +1,192 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_FLI</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table: Flight</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_FLI</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>MANDT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CARRID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CONNID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>N</INTTYPE>
<INTLEN>000008</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>NUMC</DATATYPE>
<LENG>000004</LENG>
<MASK> NUMC</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FLDATE</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>D</INTTYPE>
<INTLEN>000016</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>DATS</DATATYPE>
<LENG>000008</LENG>
<MASK> DATS</MASK>
<SHLPORIGIN>T</SHLPORIGIN>
</DD03P>
<DD03P>
<FIELDNAME>PRICE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>P</INTTYPE>
<INTLEN>000008</INTLEN>
<REFTABLE>ZDEMO_ABAP_FLI</REFTABLE>
<REFFIELD>CURRENCY</REFFIELD>
<DATATYPE>CURR</DATATYPE>
<LENG>000015</LENG>
<DECIMALS>000002</DECIMALS>
<MASK> CURR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CURRENCY</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000010</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CUKY</DATATYPE>
<LENG>000005</LENG>
<MASK> CUKY</MASK>
</DD03P>
<DD03P>
<FIELDNAME>PLANETYPE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSMAX</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSOCC</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>PAYMENTSUM</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>P</INTTYPE>
<INTLEN>000009</INTLEN>
<REFTABLE>ZDEMO_ABAP_FLI</REFTABLE>
<REFFIELD>CURRENCY</REFFIELD>
<NOTNULL>X</NOTNULL>
<DATATYPE>CURR</DATATYPE>
<LENG>000017</LENG>
<DECIMALS>000002</DECIMALS>
<MASK> CURR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSMAX_B</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSOCC_B</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSMAX_F</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>SEATSOCC_F</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_FLI</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_FLI</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,209 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_FLSCH</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table: Flight schedule</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_FLSCH</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>MANDT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CARRID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CONNID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>N</INTTYPE>
<INTLEN>000008</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>NUMC</DATATYPE>
<LENG>000004</LENG>
<MASK> NUMC</MASK>
</DD03P>
<DD03P>
<FIELDNAME>COUNTRYFR</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CITYFROM</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000040</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000020</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>AIRPFROM</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>COUNTRYTO</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CITYTO</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000040</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000020</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>AIRPTO</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000003</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FLTIME</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>DEPTIME</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>T</INTTYPE>
<INTLEN>000012</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>TIMS</DATATYPE>
<LENG>000006</LENG>
<MASK> TIMS</MASK>
<SHLPORIGIN>T</SHLPORIGIN>
</DD03P>
<DD03P>
<FIELDNAME>ARRTIME</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>T</INTTYPE>
<INTLEN>000012</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>TIMS</DATATYPE>
<LENG>000006</LENG>
<MASK> TIMS</MASK>
<SHLPORIGIN>T</SHLPORIGIN>
</DD03P>
<DD03P>
<FIELDNAME>DISTANCE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>P</INTTYPE>
<INTLEN>000005</INTLEN>
<REFTABLE>ZDEMO_ABAP_FLSCH</REFTABLE>
<REFFIELD>DISTID</REFFIELD>
<NOTNULL>X</NOTNULL>
<DATATYPE>QUAN</DATATYPE>
<LENG>000009</LENG>
<DECIMALS>000004</DECIMALS>
<MASK> QUAN</MASK>
</DD03P>
<DD03P>
<FIELDNAME>DISTID</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>UNIT</DATATYPE>
<LENG>000003</LENG>
<MASK> UNIT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FLTYPE</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000002</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CHAR</DATATYPE>
<LENG>000001</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>PERIOD</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000001</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT1</DATATYPE>
<LENG>000003</LENG>
<MASK> INT1</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_FLSCH</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_FLSCH</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,37 @@
***********************************************************************
* ---------------------------- PURPOSE --------------------------------
* Interface to support the ABAP cheat sheet ABAP object orientation.
*
* ----------------------------- NOTE ----------------------------------
* The code presented in this class is only meant for supporting the ABAP
* cheat sheets. It is not intended for direct use in a
* production system environment. The code examples in the ABAP cheat
* sheets are primarily intended to provide a better explanation and
* visualization of the syntax and semantics of ABAP statements and not to
* solve concrete programming tasks. For production application programs,
* a dedicated solution should therefore always be worked out for each
* individual case. There is no guarantee for either the correctness or
* the completeness of the code. In addition, there is no legal
* responsibility or liability for possible errors or their consequences
* which occur through the use of the example code.
*
***********************************************************************
"! <p class="shorttext synchronized">Interface for ABAP cheat sheet example</p>
"! The interface supporta the ABAP cheat sheet on object orientation and demonstrates the use of interfaces.
INTERFACE zdemo_abap_objects_interface
PUBLIC .
METHODS: double IMPORTING i_op TYPE i
RETURNING VALUE(r_double) TYPE i,
triple DEFAULT IGNORE IMPORTING i_op TYPE i
RETURNING VALUE(r_triple) TYPE i .
DATA: in_str TYPE string.
CLASS-METHODS: halve IMPORTING i_op TYPE i
RETURNING VALUE(r_halve) TYPE i.
CLASS-DATA: stat_str TYPE string.
ENDINTERFACE.

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_INTF" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<VSEOINTERF>
<CLSNAME>ZDEMO_ABAP_OBJECTS_INTERFACE</CLSNAME>
<LANGU>E</LANGU>
<DESCRIPT>Interface for ABAP cheat sheet example</DESCRIPT>
<EXPOSURE>2</EXPOSURE>
<STATE>1</STATE>
<UNICODE>X</UNICODE>
</VSEOINTERF>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,4 @@
@EndUserText.label: 'Service definition for RAP Calculator'
define service ZDEMO_ABAP_RAP_CALC_SD {
expose ZDEMO_ABAP_RAP_DRAFT_M;
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_SRVD" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<SRVD>
<NAME>ZDEMO_ABAP_RAP_CALC_SD</NAME>
<TYPE>SRVD/SRV</TYPE>
<DESCRIPTION>Service definition for RAP Calculator</DESCRIPTION>
<LANGUAGE>EN</LANGUAGE>
<MASTER_LANGUAGE>EN</MASTER_LANGUAGE>
<SOURCE_URI>./zdemo_abap_rap_calc_sd/source/main</SOURCE_URI>
<SOURCE_TYPE>ABAP_SOURCE</SOURCE_TYPE>
<SOURCE_ORIGIN_DESCRIPTION>ABAP Development Tools</SOURCE_ORIGIN_DESCRIPTION>
<SRVD_SOURCE_TYPE>S</SRVD_SOURCE_TYPE>
<SRVD_SOURCE_TYPE_DESC>Definition</SRVD_SOURCE_TYPE_DESC>
</SRVD>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,12 @@
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity ZDEMO_ABAP_RAP_CH_M
as select from zdemo_abap_rapt2
association to parent ZDEMO_ABAP_RAP_RO_M
as _parent on $projection.key_field = _parent.key_field
{
_parent,
key key_field,
key key_ch,
field_ch1,
field_ch2
}

View File

@@ -0,0 +1,21 @@
{
"BASEINFO":
{
"FROM":
[
"ZDEMO_ABAP_RAPT2"
],
"ASSOCIATED":
[
"ZDEMO_ABAP_RAP_RO_M"
],
"BASE":
[],
"ANNO_REF":
[],
"SCALAR_FUNCTION":
[],
"VERSION":0,
"ANNOREF_EVALUATION_ERROR":""
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DDLS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DDLS>
<DDLNAME>ZDEMO_ABAP_RAP_CH_M</DDLNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<DDTEXT>CDS view entity (child)</DDTEXT>
<SOURCE_TYPE>W</SOURCE_TYPE>
</DDLS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,12 @@
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity ZDEMO_ABAP_RAP_CH_U
as select from zdemo_abap_rapt2
association to parent ZDEMO_ABAP_RAP_RO_U
as _parent on $projection.key_field = _parent.key_field
{
_parent,
key key_field,
key key_ch,
field_ch1,
field_ch2
}

View File

@@ -0,0 +1,21 @@
{
"BASEINFO":
{
"FROM":
[
"ZDEMO_ABAP_RAPT2"
],
"ASSOCIATED":
[
"ZDEMO_ABAP_RAP_RO_U"
],
"BASE":
[],
"ANNO_REF":
[],
"SCALAR_FUNCTION":
[],
"VERSION":0,
"ANNOREF_EVALUATION_ERROR":""
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DDLS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DDLS>
<DDLNAME>ZDEMO_ABAP_RAP_CH_U</DDLNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<DDTEXT>CDS view entity (child)</DDTEXT>
<SOURCE_TYPE>W</SOURCE_TYPE>
</DDLS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,31 @@
managed implementation in class zbp_demo_abap_rap_draft_m unique;
strict;
with draft;
define behavior for ZDEMO_ABAP_RAP_DRAFT_M alias calc
persistent table zdemo_abap_tabca
draft table zdemo_abap_draft
lock master
total etag crea_date_time
etag master lchg_date_time
authorization master ( global )
late numbering
{
create;
update;
delete;
field ( readonly ) id, calc_result, crea_date_time, lchg_date_time;
field ( mandatory ) num1, num2, arithm_op;
static action delete_all;
internal action calculation;
validation validate on save { create; field num1, arithm_op, num2; }
determination det_modify on modify { field num1, num2, arithm_op; }
draft action Resume;
draft action Edit;
draft action Activate;
draft action Discard;
draft determine action Prepare
{
validation validate;
}
}

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_BDEF" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<BDEF>
<NAME>ZDEMO_ABAP_RAP_DRAFT_M</NAME>
<TYPE>BDEF/BDO</TYPE>
<DESCRIPTION>BDEF, managed, draft, late numbering</DESCRIPTION>
<DESCRIPTION_TEXT_LIMIT>60</DESCRIPTION_TEXT_LIMIT>
<LANGUAGE>EN</LANGUAGE>
<LINKS>
<item>
<HREF>./zdemo_abap_rap_draft_m/source/main/versions</HREF>
<REL>http://www.sap.com/adt/relations/versions</REL>
<TITLE>Historic versions</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_draft_m/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/plain</TYPE>
<TITLE>Source Content</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_draft_m/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/html</TYPE>
<TITLE>Source Content (HTML)</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_draft_m/objectstructure</HREF>
<REL>http://www.sap.com/adt/relations/objectstructure</REL>
<TITLE>Object Structure</TITLE>
</item>
<item>
<HREF>/sap/bc/adt/vit/wb/object_type/bdefbdo/object_name/ZDEMO_ABAP_RAP_DRAFT_M</HREF>
<REL>self</REL>
<TYPE>application/vnd.sap.sapgui</TYPE>
<TITLE>Representation in SAP GUI</TITLE>
</item>
</LINKS>
<MASTER_LANGUAGE>EN</MASTER_LANGUAGE>
<ABAP_LANGU_VERSION>5</ABAP_LANGU_VERSION>
<SOURCE_URI>./zdemo_abap_rap_draft_m/source/main</SOURCE_URI>
<SOURCE_TYPE>ABAP_SOURCE</SOURCE_TYPE>
<SOURCE_FIXED_POINT_ARITHMETIC>true</SOURCE_FIXED_POINT_ARITHMETIC>
<SOURCE_UNICODE_CHECKS_ACTIVE>true</SOURCE_UNICODE_CHECKS_ACTIVE>
</BDEF>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,73 @@
@AccessControl.authorizationCheck: #NOT_REQUIRED
@ObjectModel.semanticKey: ['id']
@UI: { headerInfo: { title: { value: 'id' },
typeName: 'Calculation', typeNamePlural: 'Calculations' } }
define root view entity ZDEMO_ABAP_RAP_DRAFT_M
as select from zdemo_abap_tabca
{
//FACET SECTION
@UI.facet: [
// Header Facet (Object Page):
{ id: 'HeaderFacet',
purpose: #HEADER,
type: #FIELDGROUP_REFERENCE,
//label: 'Calculation ID',
targetQualifier: 'Fieldgroup:HeaderItems',
position: 10 },
// Body Facets (Object Page)
{ id: 'Calculation',
type: #IDENTIFICATION_REFERENCE,
label: 'Calculation',
position: 10 }
]
// Element List
@EndUserText.label: 'Calculation ID'
@UI: { lineItem: [ { importance: #HIGH, position: 10,
label: 'Calculation ID' },
{ type: #FOR_ACTION, dataAction: 'delete_all',
label: 'Delete All Persisted Calculations' } ],
fieldGroup: [ { qualifier: 'Fieldgroup:HeaderItems',
position: 10 } ] }
key id,
@UI: { lineItem: [ { importance: #HIGH, position: 20,
label: '1st Operand' } ],
identification: [ { position: 20,
label: '1st Operand' } ],
fieldGroup: [ { qualifier: 'CaluclationItems',
position: 10 } ] }
num1,
@UI: { lineItem: [ { importance: #HIGH, position: 30,
label: 'Operator' } ],
identification: [ { position: 30, label: 'Operator' } ],
fieldGroup: [ { qualifier: 'CaluclationItems',
position: 20 } ] }
arithm_op,
@UI: { lineItem: [ { importance: #HIGH, position: 40,
label: '2nd Operand' } ],
identification: [ { position: 40,
label: '2nd Operand' } ],
fieldGroup: [ { qualifier: 'CaluclationItems',
position: 30 } ] }
num2,
@UI: { lineItem: [ { importance: #HIGH, position: 50,
label: 'Result' } ],
identification: [ { position: 50, label: 'Result' } ],
fieldGroup: [ { qualifier: 'CaluclationItems',
position: 40 } ] }
calc_result,
@UI: { hidden: true }
@Semantics.systemDateTime.lastChangedAt: true
crea_date_time,
@EndUserText.label: 'Last Changed At'
@UI: { fieldGroup: [ { qualifier: 'Fieldgroup:HeaderItems',
position: 20 } ] }
@Semantics.systemDateTime.localInstanceLastChangedAt: true
lchg_date_time
}

View File

@@ -0,0 +1,19 @@
{
"BASEINFO":
{
"FROM":
[
"ZDEMO_ABAP_TABCA"
],
"ASSOCIATED":
[],
"BASE":
[],
"ANNO_REF":
[],
"SCALAR_FUNCTION":
[],
"VERSION":0,
"ANNOREF_EVALUATION_ERROR":""
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DDLS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DDLS>
<DDLNAME>ZDEMO_ABAP_RAP_DRAFT_M</DDLNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<DDTEXT>CDS root view entity</DDTEXT>
<SOURCE_TYPE>W</SOURCE_TYPE>
</DDLS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,30 @@
managed implementation in class zbp_demo_abap_rap_ro_m unique;
strict;
define behavior for ZDEMO_ABAP_RAP_RO_M alias root
persistent table zdemo_abap_rapt1
lock master
authorization master ( global )
{
create;
update;
delete;
association _child { create; }
action multiply_by_2;
validation val on save { field field3; }
determination det_add_text on save { create; }
field ( readonly:update ) key_field;
}
define behavior for ZDEMO_ABAP_RAP_CH_M alias child
persistent table zdemo_abap_rapt2
lock dependent by _parent
authorization dependent by _parent
{
update;
delete;
field ( readonly ) key_field;
field ( readonly:update ) key_ch;
association _parent;
}

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_BDEF" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<BDEF>
<NAME>ZDEMO_ABAP_RAP_RO_M</NAME>
<TYPE>BDEF/BDO</TYPE>
<DESCRIPTION>BDEF, managed, external numbering</DESCRIPTION>
<DESCRIPTION_TEXT_LIMIT>60</DESCRIPTION_TEXT_LIMIT>
<LANGUAGE>EN</LANGUAGE>
<LINKS>
<item>
<HREF>./zdemo_abap_rap_ro_m/source/main/versions</HREF>
<REL>http://www.sap.com/adt/relations/versions</REL>
<TITLE>Historic versions</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_m/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/plain</TYPE>
<TITLE>Source Content</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_m/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/html</TYPE>
<TITLE>Source Content (HTML)</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_m/objectstructure</HREF>
<REL>http://www.sap.com/adt/relations/objectstructure</REL>
<TITLE>Object Structure</TITLE>
</item>
<item>
<HREF>/sap/bc/adt/vit/wb/object_type/bdefbdo/object_name/ZDEMO_ABAP_RAP_RO_M</HREF>
<REL>self</REL>
<TYPE>application/vnd.sap.sapgui</TYPE>
<TITLE>Representation in SAP GUI</TITLE>
</item>
</LINKS>
<MASTER_LANGUAGE>EN</MASTER_LANGUAGE>
<ABAP_LANGU_VERSION>5</ABAP_LANGU_VERSION>
<SOURCE_URI>./zdemo_abap_rap_ro_m/source/main</SOURCE_URI>
<SOURCE_TYPE>ABAP_SOURCE</SOURCE_TYPE>
<SOURCE_FIXED_POINT_ARITHMETIC>true</SOURCE_FIXED_POINT_ARITHMETIC>
<SOURCE_UNICODE_CHECKS_ACTIVE>true</SOURCE_UNICODE_CHECKS_ACTIVE>
</BDEF>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,12 @@
@AccessControl.authorizationCheck: #NOT_REQUIRED
define root view entity ZDEMO_ABAP_RAP_RO_M
as select from zdemo_abap_rapt1
composition [0..*] of ZDEMO_ABAP_RAP_CH_M as _child
{
key key_field,
field1,
field2,
field3,
field4,
_child
}

View File

@@ -0,0 +1,21 @@
{
"BASEINFO":
{
"FROM":
[
"ZDEMO_ABAP_RAPT1"
],
"ASSOCIATED":
[
"ZDEMO_ABAP_RAP_CH_M"
],
"BASE":
[],
"ANNO_REF":
[],
"SCALAR_FUNCTION":
[],
"VERSION":0,
"ANNOREF_EVALUATION_ERROR":""
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DDLS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DDLS>
<DDLNAME>ZDEMO_ABAP_RAP_RO_M</DDLNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<DDTEXT>CDS root view entity</DDTEXT>
<SOURCE_TYPE>W</SOURCE_TYPE>
</DDLS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,26 @@
unmanaged implementation in class zbp_demo_abap_rap_ro_u unique;
strict;
define behavior for ZDEMO_ABAP_RAP_RO_U alias root
lock master
authorization master ( global, instance )
{
create;
update;
delete;
association _child { create; }
action multiply_by_2;
action ( features : instance ) multiply_by_3;
action ( features : global ) set_z;
field ( readonly:update ) key_field;
}
define behavior for ZDEMO_ABAP_RAP_CH_U alias child
lock dependent by _parent
authorization dependent by _parent
{
field ( readonly ) key_field;
field ( readonly : update ) key_ch;
association _parent;
}

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_BDEF" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<BDEF>
<NAME>ZDEMO_ABAP_RAP_RO_U</NAME>
<TYPE>BDEF/BDO</TYPE>
<DESCRIPTION>BDEF, unmanaged, external numbering</DESCRIPTION>
<DESCRIPTION_TEXT_LIMIT>60</DESCRIPTION_TEXT_LIMIT>
<LANGUAGE>EN</LANGUAGE>
<LINKS>
<item>
<HREF>./zdemo_abap_rap_ro_u/source/main/versions</HREF>
<REL>http://www.sap.com/adt/relations/versions</REL>
<TITLE>Historic versions</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_u/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/plain</TYPE>
<TITLE>Source Content</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_u/source/main</HREF>
<REL>http://www.sap.com/adt/relations/source</REL>
<TYPE>text/html</TYPE>
<TITLE>Source Content (HTML)</TITLE>
</item>
<item>
<HREF>./zdemo_abap_rap_ro_u/objectstructure</HREF>
<REL>http://www.sap.com/adt/relations/objectstructure</REL>
<TITLE>Object Structure</TITLE>
</item>
<item>
<HREF>/sap/bc/adt/vit/wb/object_type/bdefbdo/object_name/ZDEMO_ABAP_RAP_RO_U</HREF>
<REL>self</REL>
<TYPE>application/vnd.sap.sapgui</TYPE>
<TITLE>Representation in SAP GUI</TITLE>
</item>
</LINKS>
<MASTER_LANGUAGE>EN</MASTER_LANGUAGE>
<ABAP_LANGU_VERSION>5</ABAP_LANGU_VERSION>
<SOURCE_URI>./zdemo_abap_rap_ro_u/source/main</SOURCE_URI>
<SOURCE_TYPE>ABAP_SOURCE</SOURCE_TYPE>
<SOURCE_FIXED_POINT_ARITHMETIC>true</SOURCE_FIXED_POINT_ARITHMETIC>
<SOURCE_UNICODE_CHECKS_ACTIVE>true</SOURCE_UNICODE_CHECKS_ACTIVE>
</BDEF>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,12 @@
@AccessControl.authorizationCheck: #NOT_REQUIRED
define root view entity ZDEMO_ABAP_RAP_RO_U
as select from zdemo_abap_rapt1
composition [0..*] of ZDEMO_ABAP_RAP_CH_U as _child
{
key key_field,
field1,
field2,
field3,
field4,
_child
}

View File

@@ -0,0 +1,21 @@
{
"BASEINFO":
{
"FROM":
[
"ZDEMO_ABAP_RAPT1"
],
"ASSOCIATED":
[
"ZDEMO_ABAP_RAP_CH_U"
],
"BASE":
[],
"ANNO_REF":
[],
"SCALAR_FUNCTION":
[],
"VERSION":0,
"ANNOREF_EVALUATION_ERROR":""
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_DDLS" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DDLS>
<DDLNAME>ZDEMO_ABAP_RAP_RO_U</DDLNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<DDTEXT>CDS root view entity</DDTEXT>
<SOURCE_TYPE>W</SOURCE_TYPE>
</DDLS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table for RAP</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>KEY_FIELD</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD3</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD4</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_RAPT1</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_RAPT1</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_RAPT2</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table for RAP</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_RAPT2</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>KEY_FIELD</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>KEY_CH</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD_CH1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>FIELD_CH2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_RAPT2</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_RAPT2</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_TAB1</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_TAB1</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>KEY_FIELD</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CHAR1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CHAR2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUM1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUM2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_TAB1</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_TAB1</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_TAB2</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_TAB2</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>KEY_FIELD</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CHAR1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000020</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000010</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUM1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUMLONG</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>8</INTTYPE>
<INTLEN>000008</INTLEN>
<DATATYPE>INT8</DATATYPE>
<LENG>000019</LENG>
<MASK> INT8</MASK>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_TAB2</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_TAB2</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>

View File

@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="utf-8"?>
<abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<DD02V>
<TABNAME>ZDEMO_ABAP_TABCA</TABNAME>
<DDLANGUAGE>E</DDLANGUAGE>
<TABCLASS>TRANSP</TABCLASS>
<CLIDEP>X</CLIDEP>
<DDTEXT>Demo table for RAP calculator</DDTEXT>
<MASTERLANG>E</MASTERLANG>
<MAINFLAG>X</MAINFLAG>
<CONTFLAG>A</CONTFLAG>
<EXCLASS>1</EXCLASS>
<ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>
</DD02V>
<DD09L>
<TABNAME>ZDEMO_ABAP_TABCA</TABNAME>
<AS4LOCAL>A</AS4LOCAL>
<TABKAT>0</TABKAT>
<TABART>APPL0</TABART>
<BUFALLOW>N</BUFALLOW>
</DD09L>
<DD03P_TABLE>
<DD03P>
<FIELDNAME>CLIENT</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000006</INTLEN>
<NOTNULL>X</NOTNULL>
<DATATYPE>CLNT</DATATYPE>
<LENG>000003</LENG>
<MASK> CLNT</MASK>
</DD03P>
<DD03P>
<FIELDNAME>ID</FIELDNAME>
<KEYFLAG>X</KEYFLAG>
<ROLLNAME>SYSUUID_X16</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<NOTNULL>X</NOTNULL>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>NUM1</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>ARITHM_OP</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>C</INTTYPE>
<INTLEN>000002</INTLEN>
<DATATYPE>CHAR</DATATYPE>
<LENG>000001</LENG>
<MASK> CHAR</MASK>
</DD03P>
<DD03P>
<FIELDNAME>NUM2</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>X</INTTYPE>
<INTLEN>000004</INTLEN>
<DATATYPE>INT4</DATATYPE>
<LENG>000010</LENG>
<MASK> INT4</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CALC_RESULT</FIELDNAME>
<ADMINFIELD>0</ADMINFIELD>
<INTTYPE>g</INTTYPE>
<INTLEN>000008</INTLEN>
<DATATYPE>STRG</DATATYPE>
<MASK> STRG</MASK>
</DD03P>
<DD03P>
<FIELDNAME>CREA_DATE_TIME</FIELDNAME>
<ROLLNAME>TIMESTAMPL</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<COMPTYPE>E</COMPTYPE>
</DD03P>
<DD03P>
<FIELDNAME>LCHG_DATE_TIME</FIELDNAME>
<ROLLNAME>TIMESTAMPL</ROLLNAME>
<ADMINFIELD>0</ADMINFIELD>
<COMPTYPE>E</COMPTYPE>
</DD03P>
</DD03P_TABLE>
<I18N_LANGS>
<LANGU></LANGU>
</I18N_LANGS>
<DD02_TEXTS>
<item>
<DDLANGUAGE></DDLANGUAGE>
<DDTEXT>TABT ZDEMO_ABAP_TABCA</DDTEXT>
</item>
</DD02_TEXTS>
<TABL_EXTRAS>
<TDDAT>
<TABNAME>ZDEMO_ABAP_TABCA</TABNAME>
<CCLASS>CUS_DEV_SUP_DA</CCLASS>
</TDDAT>
</TABL_EXTRAS>
</asx:values>
</asx:abap>
</abapGit>