S4D400 Basic ABAP Programming Study Notes

ABAP Development Environment and Project Setup

  • To develop ABAP applications for SAP BTP or SAP S/4HANA Cloud, the Eclipse Integrated Development Environment (IDE) is required, available from eclipse.org.

  • The ABAP Development Tools (ADT) plugin must be installed separately into Eclipse by navigating to Help -> Install New Software and adding the repository URL tools.hana.ondemand.com/latest.

  • Periodic updates for Eclipse and ADT should be checked via Help -> Check for Updates.

Perspectives and Views in ADT

  • An Eclipse perspective represents a predefined layout of views tailored for specific tasks. The default perspective in a fresh Eclipse installation is Java.

  • To open the ABAP perspective, choose Window -> Perspective -> Open Perspective -> Other and double-click ABAP.

  • Primary views within the ABAP perspective include:

    • Source Code Editor: Used for writing and editing ABAP code.

    • Project Explorer: Navigates software packages and development objects.

    • Problems View: Displays error messages, warnings, and syntax issues below the editor.

    • Documentation View: Displays ABAP language documentation.

    • Search View & Where-Used List: Displays where specific objects or elements are referenced across the system.

ABAP Project Types and BTP Connections

  • Eclipse connects to remote ABAP execution environments through projects:

    • ABAP Project: Connects to an on-premise SAP ABAP system.

    • ABAP Cloud Project: Connects to an SAP BTP ABAP environment instance or an SAP S/4HANA Cloud system.

  • SAP Business Technology Platform (BTP) global account hierarchy:

    • Global Account -> Subaccount -> Runtime Environment (Cloud Foundry or Kyma) -> ABAP Service Instance.

  • Service Key Connection Procedure:

    1. Log on to the SAP BTP Cockpit subaccount hosting the ABAP service.

    2. Navigate to Instances and Subscriptions -> Instances.

    3. Locate the ABAP instance, select the link under Credentials (Key(s)), and select Copy JSON to copy the service key to the clipboard.

    4. In Eclipse, choose File -> New -> ABAP Cloud Project.

    5. Select Use a Service Key, click Next, and paste the JSON payload into the text editor.

    6. Choose Next, then choose Open Logon Page in Browser to authenticate.

    7. Close the browser window upon successful authentication, select the system language, and choose Finish.

Navigation Functions and Development Environment Operations

Project Explorer Operations

  • Packages serve as logical organizational containers for repository objects.

  • To add a package to favorites in Project Explorer:

    1. Right-click the Favorite Packages node.

    2. Select Add Package.

    3. Enter a filter string, select the package, and choose OK.

Shortcuts and Navigation Keys

  • Ctrl + Shift + A: Opens the Open ABAP Development Object dialog to search for objects by name.

  • F1: Displays full ABAP Language Help for the statement at the cursor position.

  • F2: Displays code element information (type details, labels, signatures) in a hover pop-up.

  • F3: Navigates directly to the definition/declaration of the highlighted code element.

  • Alt + Left Arrow: Navigates backward to the previous code location after an F3 jump.

  • Ctrl + F: Opens the Find/Replace dialog inside the source editor.

  • Ctrl + 1: Displays Quick Assist / Quick Fix options.

  • Ctrl + Space: Triggers code completion pop-ups.

  • Link with Editor: Icon on the Project Explorer toolbar that expands the package hierarchy to highlight the object currently active in the editor.

Software Logistics and First ABAP Program

Software Structure and Logistics

  • Every development object (repository object) must be assigned to an ABAP Package.

  • Every package belongs to a Software Component (e.g., ZLOCAL for non-transportable local practice objects).

  • Customer Namespace Rules: Custom packages and objects must start with the letter Z or Y to prevent naming collisions with SAP standard objects delivered in standard namespaces.

  • Transport Requests:

    • Group logically related repository changes for transport across environments (Development -> Test -> Production).

    • Contains an owner and can have multiple assigned team users.

    • Editing an object locks it within the assigned transport request, preventing modifications by users outside the request.

    • Releasing tasks and the parent transport request clears object locks and enables administrative transport into target systems.

Creating a Package

  1. Choose File -> New -> ABAP Package.

  2. Enter the Name (e.g., ZS4D400_##) starting with Z or Y, and enter a Description.

  3. Assign Software Component ZLOCAL and choose Next.

  4. Choose Create a new request, enter a request description, and choose Finish.

Developing a Console Application ("Hello World")

  • Main user interface delivery in modern ABAP uses SAP Fiori Elements; however, console classes provide quick output testing in ADT.

  • Class Creation:

    1. Choose File -> New -> ABAP Class.

    2. Enter the Package, Name (prefixed with ZCL_ or YCL_, e.g., ZCL_##_HELLO_WORLD), and Description.

    3. Maximum class name length is 30 characters consisting of A-Z, 0-9, and _.

    4. Add Interface IF_OO_ADT_CLASSRUN to enable console execution.

    5. Assign to a Transport Request and choose Finish.

  • Execution Logic:

    • Code inside METHOD if_oo_adt_classrun~main is executed when pressing F9 or selecting Run as -> ABAP Application (Console).

    • Console output command: out->write( 'Hello World' ).

  • Syntax Rules for out->write():

    • No space between write and the opening parenthesis (.

    • At least one space after opening parenthesis (.

    • At least one space before closing parenthesis ).

    • Statement ends with a period ..

  • Activation (Ctrl + F3): Compiles code into an executable runtime object. Object status (Active/Inactive) displays in the Properties view.

ABAP Language Basics and Syntax Elements

Evolution of ABAP

  • Introduced in 1983 as a procedural, statement-based language influenced by COBOL and Pascal.

  • Extended in the late 1990s with object-oriented capabilities (ABAP Objects), integrating concepts from C++ and Java.

  • Modern ABAP integrates expression-based syntax elements (e.g., VALUE #( ), CORRESPONDING #( ), string templates) alongside classic statement syntax.

ABAP Language Versions

  • Program attribute controlled by an internal Version ID determining available language features and repository access:

    • ABAP for Key Users: Restricted environment for extensions.

    • ABAP Cloud: Restricted, cloud-ready language scope enforcing released APIs.

    • Standard ABAP: Unrestricted legacy and full-scope syntax.

Core Syntax Features

  • Every ABAP statement terminates with a period .. Words are separated by at least one space.

  • The assignment operator is the equals sign =. Expressions occupy the right-hand side, target variables occupy the left-hand side.

  • Syntax is case-insensitive, though ABAP style guidelines recommend uppercase for keywords and lowercase for variables/identifiers.

Comments in ABAP

  • Full-line Comment: An asterisk * placed strictly in column 1 converts the entire line into a comment.

  • Partial/Line-end Comment: A double quote " placed in any column converts all remaining text to its right into a comment.

  • Comment Shortcuts: Select code lines and press Ctrl + < to add comments (*); press Ctrl + > to remove comments.

Working with Basic Data Objects and Data Types

Categories of Data Objects

  • Variables: Named data objects declared via DATA whose memory values change at runtime.

  • Constants: Named data objects declared via CONSTANTS whose values are defined hard-coded in source code and cannot change at runtime.

  • Literals: Anonymous, hard-coded values used directly in code:

    • Number Literals: Whole integers without quotes (e.g., 12345, default type I).

    • Text Literals: Enclosed in single quotes (e.g., 'Text', type C, trailing spaces ignored).

    • String Literals: Enclosed in back quotes (e.g., `Text`, type STRING, preserves trailing spaces).

Sources of Data Types

  • ABAP Predefined (Built-in) Types: 13 fundamental technical types.

  • Local Types (TYPES statement): Defined within an ABAP program for local reuse.

  • ABAP Dictionary Types: System-wide global types (e.g., Data Elements like /DMO/AIRPORT_ID) containing technical field attributes and semantic metadata (descriptions, UI labels).

Predefined ABAP Types

  • Complete Predefined Types (fixed technical attributes, no LENGTH needed):

    • STRING: Variable-length character string (dynamically managed memory, virtually unlimited).

    • I: 4-byte (32-bit) signed integer (range −231-2^{31} to +231−1+2^{31}-1).

    • D: Date field of length 8 formatted internally as YYYYMMDD.

    • T: Time field of length 6 formatted internally as HHMMSS (24-hour clock).

  • Incomplete Predefined Types (require explicit parameters):

    • C: Fixed-length character text (requires LENGTH n).

    • N: Fixed-length numeric text string containing digits only (requires LENGTH n).

    • P: Packed decimal number (requires LENGTH n DECIMALS m; range expands up to 16 bytes).

Variable Declaration and Inline Declarations

  • Explicit Syntax: DATA <variable_name> TYPE <type_name> [VALUE <initial_val>]. Name max 30 characters (A-Z, 0-9, _).

  • Inline Declaration: DATA(<variable_name>) = <expression>. Declares variable implicitly at first write position, inferring technical type from right-hand expression.

  • Resetting Variables: CLEAR <variable>. Resets a variable to its predefined type-specific initial value (e.g., 0 for I, spaces for C, empty for STRING). Overrides original VALUE clause.

  • Implicit Conversions: Occur when source and target types differ in assignments. May incur runtime overhead, data loss (truncation), or catchable runtime conversion errors.

Data Processing, Arithmetic Calculations, and Strings

Arithmetic Expressions

  • Operators: + (addition), - (subtraction), * (multiplication), / (division), DIV (integer division without remainder), MOD (remainder of integer division).

  • Built-in Functions: sqrt( x ) (square root), ipow( base = x exp = y ) (integer exponentiation).

  • Spacing Rules: ABAP syntax strictly requires at least one blank space between operators and operands, as well as after opening parentheses and before closing parentheses.

  • Precedence: Multiplication, division, DIV, and MOD take precedence over addition and subtraction. Parentheses ( ) override precedence.

String Processing and Formatting

  • String Templates: Enclosed in pipes |...|. Combine text literals with dynamic embedded expressions enclosed in curly brackets { expression }.

  • Spacing in Embedded Expressions: Must contain at least one space after { and before }.

  • Format Options inside String Templates:

    • Date formatting: { the_date DATE = ISO } (YYYY-MM-DD), { the_date DATE = USER }.

    • Number formatting: { my_number NUMBER = USER }, { my_number SIGN = RIGHT }, { my_number STYLE = SCIENTIFIC }.

  • String Concatenation Operator (&&): Joins character strings and expressions without adding automatic spaces: text = part1 && | | && part2.

Working with Simple Internal Tables

Concept and Syntax

  • Internal tables are dynamic data objects storing multiple rows of an identical row type in memory.

  • Simple Internal Table: An internal table whose row type is a scalar/elementary data type (e.g., i or string).

  • Table Declarations:

    • Local Table Type: TYPES tt_strings TYPE TABLE OF string.

    • Variable: DATA numbers TYPE TABLE OF i.

    • Built-in Dictionary Table Type: DATA texts TYPE string_table.

Operations on Simple Internal Tables

  • Appending Data: APPEND <value_or_expression> TO <itab>. Appends a new row to the end of the internal table.

  • Clearing Table: CLEAR <itab>. Removes all rows from the internal table, resetting row count to 0.

  • Table Expressions (Index Read): val = itab[ index ]. Reads the row at the specified 1-based integer index. Raises exception CX_SY_ITAB_LINE_NOT_FOUND if the row index does not exist.

  • Loop Processing:

  LOOP AT numbers INTO DATA(number).
    out->write( |Row: { sy-tabix } Content: { number }|
  ENDLOOP.
&nbsp;&nbsp;```
  - `sy-tabix`: System field containing the current loop row index.
  - `INTO DATA(...)`: Inline work area declaration deriving type from internal table row type.


# Control Structures and Exception Handling

## Conditional Branching

- **IF Statements**:

abap IF . ELSEIF . ELSE. ENDIF.   ```

  • Every logical condition requires a ending period ., including the ELSE keyword.

    • Comparison Operators: =, <>, >, <, >=, <=, AND, OR, NOT, IS INITIAL, IS NOT INITIAL, BETWEEN <expr1> AND <expr2>.

    • Predicate Functions: contains( ), line_exists( ) evaluate directly to boolean true/false.

    • CASE Statements:

  CASE <variable>.
    WHEN <val1>.
      <code_block_1>
    WHEN <val2>.
      <code_block_2>
    WHEN OTHERS.
      <code_block_3>
  ENDCASE.
&nbsp;&nbsp;```

## Iterations (Loops)

- **Count-Based / Conditional Loops**:

abap DO [n TIMES]. IF . EXIT. ENDIF. ENDDO.   ```

  • sy-index: Built-in iteration counter starting at 1 on the first loop pass.

  • EXIT: Aborts loop processing immediately and moves execution to code following ENDDO.

Exception Handling

  • Exceptions: Error events occurring during execution. Uncaught exceptions cause program termination and create system short dumps.

  • Catchable Exceptions: Handled gracefully using block structures:

  TRY.
      <protected_code>
    CATCH <exception_class_1>.
      <handler_code_1>
    CATCH <exception_class_2>.
      <handler_code_2>
  ENDTRY.
&nbsp;&nbsp;```
- **Common Predefined System Exception Classes**:
  - `CX_SY_ZERODIVIDE`: Division by zero.
  - `CX_SY_CONVERSION_NO_NUMBER`: Text-to-numeric string conversion failure.
  - `CX_SY_ITAB_LINE_NOT_FOUND`: Accessing non-existent internal table row index/key.


# Debugging ABAP Applications

## Debugger Basics and Breakpoints

- **Setting Breakpoints**: Double-click or right-click the left editor margin on an active code line. Breakpoints are user-specific and persistent across sessions.
- **Execution Interruption**: Reaching a breakpoint opens the Debug Perspective.

## Debug Perspective Views

- **Source Code View**: Center panel displaying active execution point.
- **Variables View**: Lists active variables, values, and system fields (`SY-SUBRC`, `ME`, `Locals`). Double-clicking variables in code adds them to top-level view.
- **Breakpoints View**: Displays, deactivates, or removes active breakpoints and watchpoints.
- **Debug View**: Displays active execution thread and call stack hierarchy.
- **ABAP Internal Table View**: Tabular inspector displaying internal table contents, columns, and filter facilities.

## Debugger Execution Control Shortcuts

- `F5` (**Step Into**): Executes a single statement; steps inside called methods/functions.
- `F6` (**Step Over**): Executes current line; runs modularization units without stepping inside.
- `F8` (**Resume**): Continues execution until next breakpoint or program completion.
- `Shift + F8` (**Run to Line**): Executes code up to current cursor position.
- `Shift + F12` (**Jump to Line**): Moves execution pointer to target line without executing intermediate code or undoing state changes.
- **Terminate**: Stops debugging and aborts program execution.

## Advanced Breakpoints and Watchpoints

- **Statement Breakpoint**: Pauses execution whenever a specified ABAP statement (e.g., `CLEAR`) executes.
- **Exception Breakpoint**: Pauses execution whenever a specified exception class is raised.
- **Conditional Breakpoint**: Standard breakpoint assigned an ABAP condition expression (e.g., `sy-index > 20`); triggers only when condition evaluates true.
- **Watchpoint**: Tracks variable memory; halts program execution when variable value changes (optional conditions can be added).

## Variable Value Manipulation

- Values of variables can be dynamically changed in Debugger via right-click -> `Change Value...` in Variables View.
- Rows in internal tables can be added (`Insert Row...`), changed (`Change Value...`), or deleted (`Delete Selected Rows...` / `Delete Rows...`) inside ABAP Internal Table View.


# Object-Oriented Programming: Local Classes

## Class Concepts and Definitions

- **Global Classes**: Defined centrally in repository Class Pools; visible system-wide.
- **Local Classes**: Defined within the `Local Types` tab of a global class program; accessible only within that program.
- **Class Structure**:

abap CLASS lcl_connection DEFINITION. PUBLIC SECTION. PROTECTED SECTION. PRIVATE SECTION. ENDCLASS.

CLASS lcl_connection IMPLEMENTATION. ENDCLASS.   ```

  • Visibility Rules:

    • PUBLIC SECTION: Accessible by all consumers outside and inside the class.

    • PROTECTED SECTION: Accessible inside the class and its subclasses.

    • PRIVATE SECTION: Accessible strictly within the defining class.

    • Declarations must follow section order: Public -> Protected -> Private.

Class Components

  • Instance Attributes (DATA): Owned per instance object; distinct values per object.

  • Static Attributes (CLASS-DATA): Shared across all instances of the class; exists once in memory.

  • Constants (CONSTANTS): Static read-only components requiring immediate value specification.

  • Instance Methods (METHODS): Operate on instance and static attributes.

  • Static Methods (CLASS-METHODS): Operate exclusively on static components.

Instantiation and Reference Variables

  • Reference Variable Declaration: DATA connection TYPE REF TO lcl_connection. (Initial value is NULL).

  • Instantiation Operator (NEW): connection = NEW #( ). Allocates instance memory and returns reference.

  • Member Access Operators:

    • Static Component Selector (=>): <class_name>=><static_component> (e.g., lcl_connection=>conn_counter).

    • Instance Component Selector (->): <reference_var>-><instance_component> (e.g., connection->carrier_id).

  • Reference Assignments: Assigning reference variables (ref2 = ref1) copies the memory pointer address, not the underlying object instance.

  • Garbage Collector: Runtime service automatically destroying unreferenced instances in memory.

  • Storing References in Tables: DATA connections TYPE TABLE OF REF TO lcl_connection. Retains active references to prevent garbage collection.

Methods and Data Encapsulation

Method Signatures and Parameter Types

  • Signature Definition Syntax:

  METHODS set_attributes
    IMPORTING
      i_carrier_id    TYPE /dmo/carrier_id DEFAULT 'LH'
      i_connection_id TYPE /dmo/connection_id OPTIONAL
    EXPORTING
      e_status        TYPE string
    CHANGING
      c_data          TYPE i
    RAISING
      cx_abap_invalid_value.
&nbsp;&nbsp;```
- **Parameter Behavior**:
  - `IMPORTING`: Input parameters received from caller. Read-only inside method. Mandatory unless defined `OPTIONAL` or given a `DEFAULT <val>`.
  - `EXPORTING`: Output parameters returned to caller. Optional for caller.
  - `CHANGING`: Input/output parameters passed into method and modified.
  - `RETURNING VALUE(r_val)`: Defines a functional method returning a single result value directly usable in expressions.
  - `RAISING`: Declares catchable exception classes raised by method.

## Method Implementation and Call Syntax

- **Implementation Syntax**:

abap METHOD set_attributes. IF i_carrier_id IS INITIAL. RAISE EXCEPTION TYPE cx_abap_invalid_value. ENDIF. me->carrier_id = i_carrier_id. ENDMETHOD.   ```

  • me->: Built-in instance self-reference variable pointing to the executing instance.

    • Call Syntax:

  connection->set_attributes(
    EXPORTING
      i_carrier_id    = 'LH'
      i_connection_id = '0400'
  ).
&nbsp;&nbsp;```
- **Call Short Forms**:
  - Keyword `EXPORTING` can be omitted if passing only importing parameters.
  - Parameter name can be omitted entirely if calling a method with a single mandatory importing parameter.
- **Functional Method Calls**: Can be embedded directly inside expressions, conditional statements, or method parameters: `out->write( connection->get_output( ) ).`

## Encapsulation Principles

- Hiding implementation details and preventing direct attribute manipulation outside the class.
- **Read-Only Attributes**: Declared in `PUBLIC SECTION` using `DATA <name> TYPE <type> READ-ONLY.` Allows public read access, restricts write access strictly to class methods.
- **Private Attributes**: Declared in `PRIVATE SECTION`. Restricts both read and write access to class methods.

## Constructors

- **Instance Constructor**:
  - Predefined method name `constructor` in `PUBLIC SECTION`.
  - Executed automatically once during `NEW #( )` instantiation.
  - Can accept `IMPORTING` parameters and raise exceptions (`RAISING`). Cannot contain `EXPORTING` or `RETURNING` parameters.
  - Instantiation with parameters: `connection = NEW #( i_carrier_id = 'LH' i_connection_id = '0400' ).`
- **Static Constructor (Class Constructor)**:
  - Predefined static method name `class_constructor` in `PUBLIC SECTION`.
  - Executed automatically once when class is first addressed in program execution.
  - Accepts no parameters and raises no exceptions.


# Data Modelling and Database Operations with ABAP SQL

## Database Architecture and Tables

- ABAP systems execute on relational database management systems (DBMS), optimized for SAP HANA.
- Multi-Tenancy: Client-specific database tables include a mandatory client key field (`CLIENT` or `MANDT` typed `abap.clnt`) as the first column.
- **ADT Table Editor Syntax**:

abap @EndUserText.label : 'Flight Connection Table' define table zaconn { key client : abap.clnt not null; key uuid : sysuuid_x16 not null; carrier_id : /dmo/carrier_id; connection_id : /dmo/connection_id; }   ```

  • Data Preview Tool: Press F8 on table definition. Allows column filtering, sorting, column reordering, and entry counts.

ABAP SQL Features

  • Database interface translates database-independent ABAP SQL into Native SQL statements.

  • Automatically injects implicit client filtering based on current logon client.

  • Host variables (ABAP variables/constants used in SQL) must be prefixed with an @ symbol.

  • System variable sy-subrc evaluates execution status: 0 = record(s) found/action successful; 4 = no record found / empty result.

  • If a query produces an empty result (sy-subrc = 4), the INTO target variables retain their pre-execution values.

SELECT SINGLE Statement Syntax

SELECT SINGLE
  FROM /dmo/connection
  FIELDS airport_from_id, airport_to_id
  WHERE carrier_id    = @c_carrier_id
    AND connection_id = @c_connection_id
  INTO ( @DATA(airport_from), @DATA(airport_to) ).

Core Data Services (ABAP CDS) View Entities

Concept and Syntax

  • ABAP CDS provides semantically rich data models defined using Data Definition Language (DDL) in Data Definition repository objects.

  • CDS View Entity Syntax:

  @AccessControl.authorizationCheck: #NOT_REQUIRED
  @EndUserText.label: 'Flight Connection View'
  define view entity /DMO/I_Connection
    as select from /dmo/connection
    association [1..1] to /DMO/I_Carrier as _Airline 
      on $projection.AirlineID = _Airline.CarrierID
  {
    key carrier_id    as AirlineID,
    key connection_id as ConnectionID,
        airport_from_id as DepartureAirport,
        _Airline
  }
&nbsp;&nbsp;```
- **Annotations**: Prefixed with `@`. Entity annotations precede `define view entity`; element annotations precede individual fields.
- **Associations**: Define cardinality and relationships to target entities. Exposing `_Airline` makes related entity fields accessible.
- **Path Expressions**: Access associated fields directly using backslash `\`: `FIELDS \_Airline-Name as carrier_name`.
- **Data Preview for CDS Views**: Press `Ctrl + F8`. Context menu option *Follow Association* traverses associations.
- **Where-Used List**: Press `Ctrl + Shift + G` on a table/view to locate dependent CDS objects.


# Structured Data Objects and Complex SQL Expressions

## Structures

- **Definitions**:
  - Global Structure Type: ABAP Dictionary structure repository object (`DEFINE STRUCTURE`).
  - Local Structure Type:
    ```abap
    TYPES: BEGIN OF st_details,
             DepartureAirport  TYPE /dmo/airport_from_id,
             DestinationAirport TYPE /dmo/airport_to_id,
             AirlineName        TYPE /dmo/carrier_name,
           END OF st_details.
&nbsp;&nbsp;&nbsp;&nbsp;```
  - Structured Variable: `DATA details TYPE st_details.`
- **Structure Component Access**: Hyphen component selector `-` (e.g., `details-DepartureAirport`). Sub-components: `nested_struct-sub_struct-field`.
- **Value Constructor (`VALUE #( )`)**:

abap details = VALUE #( DepartureAirport = 'FRA' DestinationAirport = 'JFK' AirlineName = 'Lufthansa' ).   ```

  • Structure Assignments:

    • Direct assignment (struct2 = struct1): Strictly requires compatible structure types. Incompatible char-like structure assignment executes without syntax errors but produces corrupt component data.

    • Component-by-Component Mapping: struct2 = CORRESPONDING #( struct1 ). Copies identically-named components, initializing unmapped target fields.

ABAP SQL with Structures

  • FIELDS *: Selects all view/table fields into a matching target structure.

  • INTO CORRESPONDING FIELDS OF @struct: Maps selected query columns into structure components matching by name.

  • Field Aliases (AS): Maps data source column names to structure component names (FIELDS DepartureAirport AS airport_from_id).

  • Inline Declaration (INTO @DATA(struct)): Infers structure component names and technical types dynamically from field list.

  • SQL Joins:

  SELECT SINGLE
    FROM /dmo/connection AS c
    LEFT OUTER JOIN /dmo/airport AS f
      ON c~airport_from_id = f~airport_id
    FIELDS c~carrier_id, f~name AS airport_from_name
    WHERE c~carrier_id = 'LH'
    INTO @DATA(connection_join).
&nbsp;&nbsp;```
  - Tilde `~` separates table alias from field name in join queries.


# Complex Internal Tables

## Definition and Access Types

- **Complex Internal Table**: An internal table whose row type is a structure.
- **Access Types**:
  1. **Standard Table**: Unsorted storage. Appends new records to end. Sequential search key access O(n)O(n). Default key is non-unique.
  2. **Sorted Table**: Records automatically maintained in ascending sort order by key. Binary search key access O(log⁡n)O(\log n). Key can be declared `UNIQUE` or `NON-UNIQUE`.
  3. **Hashed Table**: Managed via internal hash algorithm. Direct key access O(1)O(1). Key must be declared `UNIQUE`.
- **Declarations**:

abap DATA connections TYPE STANDARD TABLE OF st_connection WITH NON-UNIQUE DEFAULT KEY.

DATA connections_sorted TYPE SORTED TABLE OF st_connection WITH UNIQUE KEY carrier_id connection_id.   ```

  • Work Areas: Structured variables typed LIKE LINE OF <itab> used for buffer operations.

Operations on Complex Internal Tables

  • Appending Row: APPEND VALUE #( carrier_id = 'LH' connection_id = '0400' ) TO connections.

  • Populating Multiple Rows: carriers = VALUE #( ( carrier_id = 'AA' ) ( carrier_id = 'LH' ) ).

  • Copying Table Data: connections = CORRESPONDING #( carriers ). Maps matching field names row-by-row.

  • Table Expressions (Key Read): connection = connections[ carrier_id = 'LH' connection_id = '0400' ]. Raises CX_SY_ITAB_LINE_NOT_FOUND if missing.

  • Looping with Filters: LOOP AT connections INTO connection WHERE airport_from_id = 'FRA'.

  • Modifying Table Rows:

    • Key Search Update: MODIFY TABLE itab FROM wa. (Uses primary key values in wa to locate target row and update non-key fields).

    • Index Search Update: MODIFY itab FROM wa INDEX 1.

    • Current Loop Row Update: MODIFY itab FROM wa. (Valid strictly inside LOOP AT ... ENDLOOP).

ABAP SQL with Internal Tables

SELECT
  FROM /DMO/I_Airport
  FIELDS AirportID, Name
  WHERE City = 'London'
  INTO TABLE @DATA(airports_inline).
  • SQL Unions: UNION ALL merges multiple SELECT result sets without duplicate removal. UNION merges sets and removes duplicate rows.

Database Updates Using Business Objects and EML

RESTful Application Programming (RAP) Business Objects

  • Consists of a CDS View Entity (data structure), Behavior Definition (.bdef), and Behavior Implementation Pool (ZBP_...).

  • Operations: Standard CRUD (Create, Read, Update, Delete) + Validations, Determinations, Actions.

  • Scenarios: Managed (RAP runtime handles database persistence) vs Unmanaged (developer custom code handles persistence).

Entity Manipulation Language (EML) Statements

  • Reading BO Data:

  READ ENTITIES OF /DMO/R_AgencyTP
    ENTITY Agency
    ALL FIELDS WITH keys_tab
    RESULT result_tab.
&nbsp;&nbsp;```
- **Modifying BO Data**:

abap MODIFY ENTITIES OF /DMO/R_AgencyTP ENTITY Agency UPDATE FIELDS ( Name ) WITH update_tab.   ```

  • Persisting Changes: COMMIT ENTITIES. Triggers the RAP save sequence to persist transactional buffer updates to database tables (used outside behavior implementation classes).

  • Derived Behavior Types:

    • TYPE TABLE FOR READ IMPORT <bdef>: Key fields + %is_draft + %control structure.

    • TYPE TABLE FOR READ RESULT <bdef>: BO entity fields + %is_draft.

    • TYPE TABLE FOR UPDATE <bdef>: Key & data fields + %control structure + %is_draft.

RESTful Application Programming Model (RAP) Architecture

Development Workflow and Artifacts

  1. Database Table: Storage table containing client, primary UUID key, data fields, and administrative ETag fields.

  2. Data Definition (CDS View Entity): Defines root data model entity.

  3. Behavior Definition: Defines transactional capabilities (create, update, delete, draft, validations, determinations).

  4. Behavior Pool Class: ABAP global class (ZBP_...) implementing behavior logic in local classes.

  5. Service Projection: Exposes tailored view entity projection, behavior projection, and Metadata Extension for specific UI applications.

  6. Service Definition: Defines entity scope exposed to consumer.

  7. Service Binding: Binds service definition to a protocol (e.g., OData V4 - UI). Published to enable Fiori preview.

Administrative Fields and ETags

  • Mandatory fields for RAP administrative concurrency and generator compliance:

    • client : abap.clnt not null;

    • uuid : sysuuid_x16 not null; (Automatic key assignment)

    • local_created_by : abp_creation_user;

    • local_created_at : abp_creation_tstmpl;

    • local_last_changed_by : abp_locinst_lastchange_user;

    • local_last_changed_at : abp_locinst_lastchange_tstmpl; (Used for local ETag control)

    • last_changed_at : abp_lastchange_tstmpl; (Used for total ETag control)

Naming Conventions Summary

  • Active Table: Z##ACONN

  • Draft Table: Z##DCONN

  • Root Data Definition: Z##_R_Connection (Alias: Connection)

  • Behavior Implementation Class: ZBP_##_CONNECTION

  • Projection View: Z##_C_Connection

  • Service Definition: Z##_CONNECTION

  • Service Binding: Z##_UI_Connection_O4

Adding Business Logic in RAP: Validations and Determinations

Validations

  • Defined in Behavior Definition: validation CheckSemanticKey on save { create; update; }

  • Implementation method signature in behavior pool: FOR VALIDATE ON SAVE

  • Execution Steps:

    1. Read active entity fields via EML READ ENTITIES OF ... IN LOCAL MODE.

    2. Evaluate business logic consistency.

    3. If invalid: create message object via me->new_message( id = 'ZS4D400' number = '001' severity = ms-error v1 = ... ).

    4. Append entry to implicit method table reported-<entity> setting %tky, %msg, and highlighting field elements %element-<field> = if_abap_behv=>mk-on.

    5. Append entry to implicit method table failed-<entity> setting %tky to abort the save process.

Determinations

  • Defined in Behavior Definition: determination GetCities on save { field AirportFromID, AirportToID; }

  • Implementation method signature in behavior pool: FOR DETERMINE ON SAVE

  • Execution Steps:

    1. Read entity key fields via EML READ ENTITIES OF ... IN LOCAL MODE.

    2. Query database/CDS views to calculate derived field values.

    3. Populate internal update table typed TYPE TABLE FOR UPDATE <bdef>.

    4. Execute update in buffer via EML MODIFY ENTITIES OF ... IN LOCAL MODE ENTITY Connection UPDATE FIELDS ( CityFrom CountryFrom ) WITH connections_upd REPORTED DATA(reported_records).

    5. Pass reported messages back to caller: reported-connection = CORRESPONDING #( reported_records-connection ).

User Experience Enhancements and Input Helps in RAP

Field Control and Metadata Extensions

  • Static Read-Only Control: In Behavior Definition: field ( readonly ) CityFrom, CityTo, CountryFrom, CountryTo;

  • Metadata Extension (.asddmxt):

    • Requires annotation @Metadata.allowExtensions: true on CDS projection view entity.

    • Organizes UI column sequence and form field order using positions:

    • @UI.lineItem: [ { position: 10 } ] (List page table columns).

    • @UI.identification: [ { position: 10 } ] (Object page form fields).

Value Help (Input Help)

  1. Create Value Help CDS View Entity selecting candidate lookup values (e.g., Z##_I_CarrierVH selecting from /dmo/carrier returning CarrierID and Name).

  2. Annotate value help view elements with @UI.lineItem for hit list layout.

  3. Link value help entity to target element in projection view entity: abap @Consumption.valueHelpDefinition: [{ entity: { name: 'Z##_I_CarrierVH', element: 'CarrierID' } }] CarrierID; &nbsp;&nbsp;&nbsp;

Unit Learning Assessments and Solutions Review

Unit 1 Assessment

  1. An ABAP Cloud Project in ABAP Development Tools (ADT) allows you to connect to what kinds of system?

    • Correct Answers: A (SAP BTP ABAP instance), B (On-Premise ABAP system), C (Embedded ABAP instance in SAP S/4HANA Cloud)

  2. In ABAP source code, how do you navigate to the definition of a development object?

    • Correct Answer: C (Position the cursor on the name of the object and press F3)

  3. What must you do when you create an ABAP package?

    • Correct Answers: A (Use the letter Z or Y as the first character in the name), C (Assign the package to a software component)

  4. Which of the following characters is not allowed in the name of an ABAP class?

    • Correct Answer: C ($)

Unit 2 Assessment

  1. Which of the following can you use to denote a comment in ABAP?

    • Correct Answers: B (* at the beginning of a line), D (" anywhere in the line)

  2. Which of the following predefined ABAP types are complete?

    • Correct Answers: B (D), D (I)

  3. You declare a variable as follows: DATA var TYPE I VALUE 100. Subsequently, you use the statement CLEAR var. What is the value of var after the CLEAR statement?

    • Correct Answer: A (0)

  4. The result of the expression result = var MOD 2. is 1. What does this tell you about the value of variable var?

    • Correct Answer: B (var is an odd number)

  5. You want to concatenate two strings. Which is the correct operator?

    • Correct Answer: D (&&)

  6. When you declare an internal table, you must specify how many rows it may contain.

    • Correct Answer: False

  7. What is the work area of an internal table?

    • Correct Answer: C (A variable with the same type as the row type of the internal table)

  8. The IF condition IF a > 10. is followed by the ELSEIF condition ELSEIF a = 25. The variable a has the value 25. Which code branch or branches are executed?

    • Correct Answer: A (The branch introduced by IF a > 10.)

  9. How can you exit a loop in ABAP?

    • Correct Answers: A (After a certain number of repetitions), C (When a particular condition is met)

  10. Which of the following statements about exceptions are true?

    • Correct Answers: A (All uncaught exceptions lead to runtime errors), C (Some exceptions are catchable, others are uncatchable)

  11. What information do you see when you position the mouse pointer over a variable in the debugger?

    • Correct Answer: B (The current contents of the variable)

  12. When you press F8 (Continue) in the debugger, where could the program processing next stop?

    • Correct Answers: B (At a subsequent breakpoint), C (At the end of the program)

Unit 3 Assessment

  1. In which order do you define the visibility sections of a class?

    • Correct Answer: A (PUBLIC SECTION. PROTECTED SECTION. PRIVATE SECTION.)

  2. You have defined a class containing instance attributes and static attributes. You have also declared a reference variable but not yet created a new instance of the class. Which components of the class can you access at this point, and how?

    • Correct Answer: D (Static components using the name of the class)

  3. You have declared two reference variables, ref1 and ref2. ref1 points to an object. You now execute the statement ref2 = ref1. What happens?

    • Correct Answer: B (The ABAP system assigns the address of the object to which ref1 is pointing to reference variable ref2. There is only one object)

  4. A class my_class contains the public static method my_method. What is the correct code to call this method?

    • Correct Answer: D (my_class=>my_method( ).)

  5. A functional method must have:

    • Correct Answer: D (Exactly one returning parameter)

  6. Your class contains a public instance attribute attr. How could you ensure that its value can only be changed within the class?

    • Correct Answers: A (Make it a private attribute), C (Leave it in the public section but use the READ-ONLY addition)

  7. Which of the following signature elements may an instance constructor have?

    • Correct Answers: A (Importing parameters), D (Exceptions)

  8. The static constructor is executed when the class is addressed for the first time. When might this be?

    • Correct Answers: B (When you call a static method of the class), C (When you instantiate the class)

Unit 4 Assessment

  1. Which part of SQL is represented by ABAP SQL?

    • Correct Answer: C (Data Manipulation Language)

  2. What is the correct sequence of clauses in the SELECT SINGLE statement?

    • Correct Answer: C (SELECT SINGLE FROM... FIELDS... INTO... WHERE...)

  3. Which of the following are valid data sources for a CDS view entity?

    • Correct Answers: B (A database table), C (Another CDS view entity)

  4. You are writing a SELECT statement that reads data using a CDS view entity. In the field list, you want to read a field from an associated table. What do you use?

    • Correct Answer: B (A path expression)

Unit 5 Assessment

  1. You declare a variable using the statement DATA struct TYPE <type>. Which of the following can you use to declare a structure?

    • Correct Answers: A (A database table), C (A CDS view)

  2. A structure struct contains a component comp. How do you address the component?

    • Correct Answer: B (struct-comp)

Unit 6 Assessment

  1. Which of the following statements is true for a standard internal table?

    • Correct Answer: B (The key is always non-unique)

  2. The type tt_table is defined as follows: TYPES tt_table TYPE STANDARD TABLE OF st_connection WITH NON-UNIQUE KEY carrier_id connection_id. Which DATA statement would you use to create an internal table with this type?

    • Correct Answer: A (DATA table TYPE tt_table.)

  3. Which of the following can you use to fill an internal table?

    • Correct Answers: B (VALUE #( )), D (APPEND)

  4. You want to read data from two database tables so that the SELECT statement returns a single result set that contains no duplicate entries. Which of the following techniques would you use?

    • Correct Answer: B (UNION)

Unit 7 Assessment

  1. In our scenario, what is coded in a behavior implementation?

    • Correct Answers: A (Validations), B (Determinations)

  2. In the READ ENTITIES statement, you use an internal table with a special type (TYPE TABLE FOR READ RESULT). How is this type created?

    • Correct Answer: C (The system creates it automatically)

Unit 8 Assessment

  1. Which of the following can you use to specify the data type of a column in a database table?

    • Correct Answer: B (Data element)

  2. When you create a database table to generate a RAP application, you must create a client field. Which data type must it have?

    • Correct Answer: B (The built-in ABAP Dictionary type abap.clnt)

  3. Which of the following parts of a behavior definition are generated automatically?

    • Correct Answers: A (Draft enabling), D (Create, update, and delete operations)

  4. You need to display an error text. Where do you create it?

    • Correct Answer: C (In a message class)

  5. When you create a validation, what does the system generate automatically?

    • Correct Answer: A (An empty method in the local class of the behavior implementation)

  6. In the validation, you use the READ ENTITIES statement to read the data entered by the user. Which parameter of the validation method do you use to ensure that the correct data is retrieved?

    • Correct Answer: C (KEYS)

  7. Where do you declare fields as read-only?

    • Correct Answer: C (In the behavior definition)

  8. What does the annotation @Consumption.ValueHelpDefinition specify?

    • Correct Answers: B (A CDS view that provides the hit list), D (The field that provides the selected value)