ABAP Blog Posts
cancel
Showing results for 
Search instead for 
Did you mean: 

Creating custom functions in ABAP CDS 

A CDS Scalar function ( This feature is supported as of SAP S/4HANA 2023 FPS 00 ) allows us to define a custom function directly on SAP HANA database using SQLSCRIPT and then reuse it in CDS view entities.

There are 3 parts in CDS scalar function –

  1. A CDS scalar function definition — this defines in and out parameters.

There will be one or many input parameters and exactly one output parameter.

sanjay22_0-1762237341694.png

sanjay22_1-1762237384367.png

sanjay22_2-1762237408256.png

Lets make this a CDS scalar function which will accept a date and returns weekday value.

sanjay22_3-1762237443647.png

2. Define the CDS scalar function implementation reference. This refer to an AMDP class and method having the logic. This part won’t have actual implementation.

It follows the scalar function name followed by _SQL

sanjay22_4-1762237518331.png

sanjay22_5-1762237555885.png

Click on next and provide an AMDP class and its method which will hold the implementation logic.

sanjay22_6-1762237585232.png

Next, lets create our AMDP class (ZCL_AMDP_SF) and a static method (get_weekday)

sanjay22_7-1762237625356.png

Here below is the Code snippet for AMDP Class and method

CLASS zcl_amdp_sf DEFINITION
  PUBLIC
  FINAL
  CREATE PUBLIC .

  PUBLIC SECTION.
    INTERFACES if_amdp_marker_hdb.
    CLASS-METHODS get_weekday FOR SCALAR FUNCTION zcds_scalar_func.

  PROTECTED SECTION.
  PRIVATE SECTION.
ENDCLASS.



CLASS zcl_amdp_sf IMPLEMENTATION.
  METHOD get_weekday BY DATABASE FUNCTION FOR HDB LANGUAGE SQLSCRIPT OPTIONS READ-ONLY.

    declare weekday_num int;
    weekday_num := weekday( input_Date );
    IF :weekday_num = 0 THEN result = 'MON'; END if;
    IF :weekday_num = 1 THEN result = 'TUE'; END if;
    IF :weekday_num = 2 THEN result = 'WED'; END if;
    IF :weekday_num = 3 THEN result = 'THU'; END if;
    IF :weekday_num = 4 THEN result = 'FRI'; END if;
    IF :weekday_num = 5 THEN result = 'SAT'; END if;
    IF :weekday_num = 6 THEN result = 'SUN'; END if;
  ENDMETHOD.

ENDCLASS.

 

In the implementation , we have added logic to find the number as per input date and using if else   logic we are providing 3 char weekday name for same.

 

To test this, we have to create another CDS view which will call this CDS scalar function.

sanjay22_8-1762237793183.png

 

Let’s execute the CDS view to get output of Scalar function.

sanjay22_9-1762237832394.png

 

Labels in this area