Skip to Content
Technical Articles
Author's profile photo Andrea Schlotthauer

ABAP CDS Cheat Sheet: Amounts and Quantities in ABAP CDS

In ABAP CDS, a special handling for amounts and quantities is implemented. If differs from DDIC amount and quantity handling and it has recently been overhauled. Read this blog post and learn about ABAP CDS amount and quantity fields, conversion functions, and handling of amounts and quantities in expressions.

Contents:

  • CDS Amount Field
  • CDS Quantity Field
  • CDS Calculated Quantity with Calculated Unit
  • Unit and Currency Conversion Functions
  • Amounts and Quantities in Expressions
    • Amounts and quantities in arithmetic expressions
    • Amounts and quantities in aggregate functions
    • Amounts and quantities in simple and complex case expressions
    • Amounts and quantities in comparisons
    • Amounts and quantities in UNION views and INTERSECT views

CDS Amount Field

  • Field that stores an amount in a specific currency.
  • Possible data types: CURR, DECFLOAT34, DEC, and FLTP.
  • Reference to a currency key using the annotation @Semantics.amount.currencyCode is mandatory.
  • A currency key must have data type CUKY and it can contain a currency ID from the DDIC database table TCURC.

Further details: ABAP CDS – Amount Fields on SAP Help Portal.

CDS Quantity Field

  • Field that stores a quantity in a specific unit.
  • Possible data types: QUAN, DECFLOAT16, DECFLOAT34, DEC, FLTP, INT1, INT2, or INT4.
  • Reference to a unit of measurement key using the annotation @Semantics.quantity.unitOfMeasure is mandatory.
  • A unit of measurement key must have data type UNIT and can contain a unit ID from the DDIC database table T006.

Further details: ABAP CDS – Quantity Fields on SAP Help Portal.

CDS Calculated Quantity with Calculated Unit

This is a new feature that was first released with kernel release 7.84, SAP BTP ABAP Environment 2105, ABAP release 7.56. It is available in CDS view entities and in CDS projection views.

  • A calculated quantity is a field that stores a quantity in a self-defined unit.
  • It is always the result of a calculation using amounts and quantities.
  • A calculated quantity always has data type DECFLOAT34.
  • A reference to a calculated unit using the annotation @Semantics.quantity.unitOfMeasure: ‘calculatedUnit’ is mandatory.
  • A calculated unit has data type CHAR and specifies a self-defined unit, such as €/m2 (cost per square meter of an apartment, for example).

Further details:

Example

Arithmetic expression Result
770 € (Amount) / 100m² (Quantity) 7,70€/m² (Calculated Quantity)

The arithmetic expression 770€ / 100 mcalculates cost per square meter. It divides an amount by a quantity. The result of this calculation is a calculated quantity that has calculated unit reference assigned. This calculated unit is not registered in the unit check table T006.

Example

In the following CDS view entity, the field rent_per_size divides the amount of the rent for an apartment by the apartment size. The result is the cost per square meter.

  • Field rent_curr has data type CURR and a currency key reference. It is converted into data type DECFLOAT34 using the conversion function CURR_TO_DECFLOAT_AMOUNT.
  • Field apartment_size has data type QUAN(10,2) and a unit key reference.
  • The calculated unit is defined by means of a concatenation of a currency code, a forward slash, and the apartment unit. The resulting calculated unit is EUR/MTK, MTK being the unit ID for square meter.
@AccessControl.authorizationCheck: #NOT_ALLOWED 
@EndUserText.label: 'CDS view entity, calculated quantity' 

define view entity DEMO_CDS_CALCULATED_QUANTITY 
  as select from demo_rent 
{ 
  key apartment_id                     as ApartmentId, 
      apartment_size                   as ApartmentSize, 
      apartment_unit                   as ApartmentUnit, 
      currency                         as Currency, 
       
      // currency field and unit field in arith expression 
      @Semantics.quantity.unitOfMeasure: 'calculatedUnit' 
      curr_to_decfloat_amount(rent_curr) / apartment_size 
                                       as rent_per_size,
      concat( concat(currency, '/' ), apartment_unit )  
                                       as calculatedUnit 
} 

If data is inserted into the underlying database talbe demo_rent, the data preview might look as follows:

In analytical projection views, the calculated quantity and the calculated unit can be defined as virtual elements using the keyword VIRTUAL, as shown in the following example.

@EndUserText.label: 'CDS projection view, analytical query'
@AccessControl.authorizationCheck: #NOT_ALLOWED
define transient view entity DEMO_ANALYTICAL_QUERY_ELEM
  provider contract analytical_query
  as projection on DEMO_CDS_CUBE_VIEW
{
  @AnalyticsDetails.query.axis: #COLUMNS
  @Semantics.amount.currencyCode: 'currency'
  curr_to_decfloat_amount(  paymentsum ) as paymentsum,
  
  virtual unitPrice : abap.char( 10 ),
  
  @EndUserText.label: 'price'
  @Aggregation.default: #FORMULA
  @AnalyticsDetails.query.axis: #COLUMNS
  @Semantics.quantity.unitOfMeasure: 'unitPrice'
  $projection.paymentsum / $projection.distance as price
        
}

Unit and Currency Conversion Functions

Function Effect
UNIT_CONVERSION( quantity              => arg1,
source_unit       => arg2,
target_unit        => arg3[,
client                  => arg4][,
error_handling => arg5])

Performs a unit conversion for arg1.

Has been available “forever”, i.e. since ABAP release 7.40.

Available in CDS DDIC-based views and in CDS view entities.

CURRENCY_CONVERSION(
  amount                        => arg1,
  source_currency        => arg2,
  target_currency         => arg3,
  exchange_rate_date => arg4[,
  exchange_rate_type => arg5][,
  client                            => arg6][,
  round                           => arg7][,
  decimal_shift              => arg8][,
  decimal_shift_back   => arg9][,
  error_handling           => arg10])

Performs a currency conversion for arg1.

Has been available “forever”, i.e. since ABAP release 7.40.

Available in CDS DDIC-based views and in CDS view entities.

GET_NUMERIC_VALUE( arg )

Returns the numeric value of a currency or quantity field without its currency or unit key.

Available since kernel release 7.83, SAP BTP ABAP Environment 2102, ABAP release 7.56.

Available in CDS view entities.

CURR_TO_DECFLOAT_AMOUNT( arg )

Converts a currency field of data type CURR into a currency field of data type DECFLOAT34.

Available since kernel release 7.83, SAP BTP ABAP Environment 2102, ABAP release 7.56.

Available in CDS view entities.

Note: DECIMAL_SHIFT is available in the obsolete CDS DDIC-based views. It is not available in the “new world” of CDS view entities.

Further info on SAP Help Portal, Unit and Currency Conversion Functions

Example

The following CDS view entity applies the function GET_NUMERIC_VALUE to calculate the number of bookings. It divides the total value of current bookings (field paymentsum) by the price of a flight (field price). This would not be possible without the function GET_NUMERIC_VALUE, since elements of data type CURR are not allowed in arithmetic expressions.

Details on the elements:

  • paymentsum has data type CURR, a reference annotation that assigns a currency key, and it contains the total value of current bookings.
  • price has data type CURR, a reference annotation that assigns a currency key, and it contains the price of a flight.
  • number_of_bookings has data type DECFLOAT34 and it has no currency key assigned.
AccessControl.authorizationCheck: #NOT_REQUIRED 
@EndUserText.label: 'CDS view entity, GET_NUMERIC_VALUE' 
@Metadata.ignorePropagatedAnnotations: true 

define view entity DEMO_CDS_GET_NUMERIC_VALUE 
  as select from sflight 
{ 
  key carrid, 
  key connid, 
  key fldate, 
      @Semantics.amount.currencyCode: 'currency' 
      price, 
      currency, 
      @Semantics.amount.currencyCode: 'currency' 
      paymentsum, 
      GET_NUMERIC_VALUE( paymentsum ) 
        / GET_NUMERIC_VALUE( price ) as number_of_bookings 
} 

Amounts and Quantities in Expressions

In the “new world” of CDS view entities, amounts and quantities are considered in expressions, union views, and intersect views. Special rules apply how amounts and quantities can be combined:

  • Amounts and quantities in arithmetic expressions
  • Amounts and quantities in aggregate functions
  • Amounts and quantities in simple and complex case expressions
  • Amounts and quantities in comparisons
  • Amounts and quantities in UNION and INTERSECT views

Note: Cast expressions do not handle amounts. Only the target type CURR requires a reference to a currency key.

Amounts and quantities in arithmetic expressions

Release info: available since kernel release 7.84, SAP BTP ABAP Environment 2105, ABAP release  7.56

operand / operator / * +, –
amount, amount calculated quantity calculated quantity amount
quantity, quantity calculated quantity calculated quantity quantity
calculated quantity, amount calculated quantity calculated quantity amount
amount, quantity calculated quantity calculated quantity
calculated quantity, number calculated quantity calculated quantity
calculated quantity, quantity, calculated quantity calculated quantity quantity
calculated quantity, calculated quantity calculated quantity calculated quantity calculated quantity
amount, number amount amount
number, amount calculated quantity amount
quantity, number quantity quantity
number, quantity calculated quantity quantity

Further details: Amounts and Quantities in Arithmetic Expressions on SAP Help Portal

Amounts and quantities in aggregate functions

Release info: available since kernel release 7.84, SAP BTP ABAP Environment 2105, ABAP release 7.56

If the operand of an aggregate function is a CDS amount field, a CDS quantity field, or a CDS calculated quantity, the result type might require a reference annotation as well. The following table shows the result type depending on the operand type of all available aggregate functions.

Aggregate Function Type of Operand Result Type
MAX, MIN, SUM, AVG amount amount
MAX, MIN, SUM, AVG quantity quantity
MAX, MIN, SUM, AVG calculated quantity calculated quantity
COUNT amount, quantity, calculated quantity number of type INT4

Further details: Amounts and Quantities in Aggregate Expressions on SAP Help Portal.

Amounts and quantities in simple and complex case expressions

Release info: available since kernel release 7.84, SAP BTP ABAP Environment 2105, ABAP release 7.56

The result data type of a case expression (simple and complex) is determined by all THEN branches and the ELSE branch. If the result data type is a CDS amount field, a CDS quantity field, or a CDS calculated quantity, a reference annotation must be assigned. The following table shows how the result data type is calculated if one or more of the operands are amount and/or quantity fields.

Operand1 / Operand2 Amount Quantity Calculated Quantity Number
Amount amount calculated quantity calculated quantity calculated quantity
Quantity calculated quantity quantity calculated quantity calculated quantity
Calculated Quantity calculated quantity calculated quantity calculated quantity calculated quantity
Number calculated quantity calculated quantity calculated quantity number

Further details on SAP Help Portal:

Example

The example shows a CDS view entity with two complex case distinctions using amount and quantity fields.

@AccessControl.authorizationCheck: #NOT_REQUIRED 

define view entity DEMO_CDS_COMPLEX_CASE_1 
  as select from DEMO_CDS_CALC_QUANTITY_BASE 
{ 
  key Id, 

      //amounts and calculated quantities are compatible, 
      //result is a calculated quantity 

      @Semantics.quantity.unitOfMeasure: 'Calcunit' 
      case 
      when Char1 = abap.char'A' 
      then Dec10                //cuky reference -> amount field 
      when Char1 = abap.char'B' 
      then 100 / Dec10          //calculated quantity 
      else 0 
      end                                   as calcQuan, 
      Cuky, 
      concat( concat( Cuky , '/' ), Unit2 ) as calcUnit, 


      //CURR requires conversion to DECFLOAT34 

      @Semantics.amount.currencyCode : 'cuky' 
      case when Char1 = abap.char'A' 
      then CURR_TO_DECFLOAT_AMOUNT( Curr102 ) 
      else Dec10                //cuky reference 
      end                                   as CurrConv 
} 

Amounts and quantities in comparisons

Release info: available since kernel release 7.87, ABAP release 7.57.

If one of the operands of a comparison is a CDS amount field, a CDS quantity field, or a CDS calculated quantity, special rules apply:

  • Both operands must have the same reference type. Both must be either amounts, or quantities, or calculated quantities. Comparing operands with references of different types (currency key, unit key, or calculated unit) results in a syntax check warning.
  • An operand of type CURR can only be compared with another operand of type CURR. The number of decimal places of both operands must match exactly.

The following table shows the possible combinations of operands in comparisons. Number refers to an operand of a numeric data type without reference annotation that turns it into an amount or quantity field.

Type of Operand Comment
amount, number syntax check warning occurs.
Exception: if number is specified as literal, no syntax check warning occurs.
amount, amount Ok.
Note: Elements of data type CURR must have exactly the same number of decimal places.
quantity, number syntax check warning occurs.
Exception: if number is specified as literal, no syntax check warning occurs.
quantity, quantity ok
amount, quantity syntax check warning occurs.
amount, calculated quantity syntax check warning occurs.
quantity, calculated quantity syntax check warning occurs.
calculated quantity, number syntax check warning occurs.
Exception: if number is specified as literal, no syntax check warning occurs.
calculated quantity, calculated quantity ok

Further details: Comparisons with Amounts and Quantities  on SAP Help Portal.

Amounts and quantities in UNION views and INTERSECT views

In UNION views and INTERSECT views, the data types of elements of different branches must match. For CDS amount fields, CDS quantity fields, and CDS calculated quantities, this implies:

  • Calculated quantity fields can be merged only with other calculated quantity fields.
  • Amount fields and quantity fields can be merged with each other, as long as the data types match.
  • For amount fields of type CURR, the number of decimal places must match exactly in all UNION branches.
  • Elements of data type CURR are incompatible to any other data type. The function CURR_TO_DECFLOAT_AMOUNT can be used to convert an amount field of data type CURR into an amount field of data type DECFLOAT34.

Questions, comments, or further details required? Use the Comments section below. Discussions are welcome.

Don’t miss out on ABAP CDS News. Follow my profile Andrea Schlotthauer for similar blog posts.

Assigned Tags

      18 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Shai Sinai
      Shai Sinai

      Thanks for the detailed overview.

       

      What would be the result of GET_NUMERIC_VALUE ( 60.00 JPY )?

      (6000 JPY in external format)

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      Hi,

      the value stays exactly the same.

      The function removes the reference to a currency key and it converts the data type to DECFLOAT34. If arg has data type CURR, an implicit decimal shift takes place.

      Purpose: strict checks have been implemented for calculations with amounts in expressions and with this function, some limitations can be circumvented.

      Docu on SAP Help Portal.

      Does that answer your question? Any further issues?

      Author's profile photo Shai Sinai
      Shai Sinai

      Almost.

      The statement "If arg has data type CURR, an implicit decimal shift takes place." is quite amorphic.

      I brought JPY as an example. The (external) value of 6000 JPY is internally stored in ABAP as 60.00 JPY. What would be the result of GET_NUMERIC_VALUE? 6000 or 60.00?

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      It depends how the value 60.00 JPY is stored in your system:

      • If the value is stored as DEC(x,2), the value remains 60.00. No decimal shift takes place.
      • If the value is stored in a CURR(x,2) column, an implicit DECIMAL_SHIFT statement is generated.

      The decimal shift calculates the difference between the number of decimal places of the currency and the number of decimal places of the column.

      JPY does not have any decimal places. Your column apparently has two decimal places.

      2 - 0 = 2. The comma is shifted two places to the right. In other words, the value is multiplied by 100. The result of GET_NUMERIC_VALUE is 6000.

       

      Author's profile photo Shai Sinai
      Shai Sinai

      Thanks. That answers my question.

      Author's profile photo Thomas Wolf
      Thomas Wolf

      Hi,

      I have 2 CDS Views; one read aggregation (SUM) in EKBE (Po History) for field DMBTR (CURR13.2)

      DMBTR is always positive but SHKZG H or S needs to handle it positive or negative.

      For a PO line I want to have the total amount of DMBTR

      --> SUM DMBTR S subtracted by SUM DMBTR H into new field.

      But the value of the new field is zero even if there is a value in DMBTR S.

      Function GET_NUMERIC_VALUE or CURR_TO_DECFLOAT_AMOUNT are not available in Eclipse ("Specified Function xxx is not known as a predefined function")

      ABAP Kernel 785 Patch Level 232
      SAP_BASIS 756 0001
      SAP_ABA 75G 0001
      S4CORE 106 0001

      How can I add these functions into CDS View? or even get the calculation done?

      Best regards,

      Thomas

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      Hi Thomas,

      both functions GET_NUMERIC_VALUE and CURR_TO_DECFLOAT_AMOUNT are available in CDS view entities (DEFINE VIEW ENTITY) as of release 7.83.

      I suspect your views are classic CDS views (DEFINE VIEW). Please check.

      You can migrate your CDS views to CDS view entities as described in the following blog post: A new generation of CDS views: how to migrate your CDS views to CDS view entities | SAP Blogs

      If you use CDS view entities and you work on release 7.85, then both functions should be available. If you get an error, it is a bug. Please open an incident on BC-DWB-DIC.

      Best regards

      Andrea

      Author's profile photo Thomas Wolf
      Thomas Wolf

      Hi Andrea,

      thanks for the Reply.

      Indeed I used the "old" CDS view for this. Now the functions are available.

      because of SAP note https://launchpad.support.sap.com/#/notes/3213096 I could not use the CDS directly.

      another problem was the association...when one entry is not available ( no H in EKBE ) the calculation also does not calculate 10.000 - 0 ... it just do nothing and set to 0.

      I had to add a case line...when H is NULL then S ELSE do H - S (converted with CURR_TO_DECFLOAT_AMOUNT before )

      So I think my problem is solved...but handling this in CDS is not very easy. with ABAP SQL it would take 4 lines of code

       

      Thank you very much!

      Best regards,

      Thomas

      Author's profile photo Shavneet Singh
      Shavneet Singh

      Hello Andrea ,

      I have a CDs View where i calculate the Total Bid value , from the fields of EKPO table.

      Something like this :

      key Item.ebeln as PO,

      max( CURR_TO_DECFLOAT_AMOUNT(Item.netpr ) * GET_NUMERIC_VALUE(Item.ktmng) ) as TotalBidValue.

      Now this TotalbidValue is used in the projection view.

      IT is giving me error : Entity ZC_HEADERU01TP contains the unsupported datatype DECFLOAT34.

      How to resolve this ?, as after using these functions , data type for the new field is DECFLOAT34 , which is not supported.

       

      Thanks and Regards ,

      Shavneet

       

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      Hi Shnaveet,

      what kind of projection view is that? Which provider contract does the projection view have? Or none at all?

      Which release do you work on?

      Can you try casting to another data type?

      I have tried to reproduce the scenario and i do not get any error message for DECFLOAT34 in a projection view.

      The field TotalBidValue has data type DECFLOAT34 here and there is no error message.

      Please provide further details.

      Author's profile photo Stefan Siemes
      Stefan Siemes

      Can you show how to implment these new calculated quantities in an OData service?

      System: ABAP 7.56

      Example (Maintenance Hours per Usage (e.g. km, runtime, etc.):

      concat( concat( EinheitIHZeit, '/'), EinheitBetriebswert) as EinheitCalc
      @Semantics.quantity.unitOfMeasure: 'EinheitCalc'
      IHZeit / Betriebswert as IstZeitProBetriebswert
      • An OData v2 Service Binding does not accept DECFLOAT34 data type at all
      • An OData v4 Service Binding does accept the DECFLOAT34, but fails in the gateway client with error code 036 (No configuration for unit of measure '...' )screenshot

      This is very inconvenient ...

      Thanks!

       

      Author's profile photo Martin Sautter
      Martin Sautter

      Hi,

      wouldnt it be much easier  to stop all this cumbersome CDS analytics query syntax
      and to use the BW Eclipse query designer
      which has got all this already
      and to enable teh BW Eclipse query designer to generate a Fiori App ?0

       

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      Hi,

      this amount and quantity handling is available in CDS view entities in general, not just for analytical queries. So it can be used in transactional apps as well. Many more use cases than just analytical queries.

      "enable teh BW Eclipse query designer to generate a Fiori App ?" -> Andreas Riehl can maybe answer this.

      Author's profile photo Stefan Unnebrink
      Stefan Unnebrink

      Dear Martin,

      it is a good question. I agree that CDS language is not the best choice for modelling an analytical query and annotations are not the best way to express core features (e.g. AnalyticsDetails.query.formula). I think with the new "transient view entities with provider contract analytical_query" we made good progress to overcome some CDS/SQL limitations. E.g. you can use native CDS formulas instead of the annotation AnalyticsDetails.query.formula.

      But we at SAP decided to go for CDS analytics query (in short CDS query) for the following reasons: (in the following I will call the object you store with the BW Eclipse query designer in short BW-query)

      1. CDS views have a different lifecycle then a BW query.
        1. BW query is delivered in so called D-version has to be activated by the customer
        2. Where-use check will break from cube to query
      2. Different extensibility concepts
      3. Different concept for start authorization (cloud enablement)
      4. Seamless tool integration for CDS query with other objects (CDS, services) in ADT, e.g. navigation to CDS cube, lookup entities etc.
      5. In the BW tool you see the BW names but not the CDS names
      6. In the BW tool there is no native support for Consumption.derivation. Instead you have to define an "exit variable" and write some ABAP code
      7. ...

      We could have solved some of these limitations but some others are fundamental such that the BW query always would work like a foreign body.

      Of course you can create BW queries on top of CDS providers. In the on-prem world this is technically possible. It is especially useful, if you need a feature which is not (yet) provided by the CDS query. But you have to be aware of the limitations.

       

      Author's profile photo Frederik Ulf Hansen
      Frederik Ulf Hansen

      What ABAP CDS views are really missing is a graphical modeler like we use for calculation views which is so nice. It seems strange that this has not been by prioritized. Stefan Unnebrink are there any plans for this? It would help customers a lot and make ABAP CDS views much more user friendly

       

      BR Frederik

      Author's profile photo Stefan Unnebrink
      Stefan Unnebrink

      Thanks for the input. There are discussions about it but no finalized plans. Only in cloud there exists a query modelling tools for key users.

      Author's profile photo Dhanunjai Gandavarapu
      Dhanunjai Gandavarapu

      Hi Andrea,

      I'm getting the following errors.

      1. When we tried to reuse the field in the same cds entity using $projection getting the error "$projection expression cannot be reused".

      %24projection%20expression%20cannot%20be%20reused

      $projection expression cannot be reused

          2. Getting the error when trying to create the cds projection of type analytical query. The error is "Provider contract AQ is not supported yet".

      Provider%20contract%20AQ%20is%20not%20supported%20yet.

      Provider contract AQ is not supported yet.

       

      S/4 HANA version is 2021 SP Stack 01 (02/2022).

       

      Thanks,

      Dhanunjai Gandavarapu.

      Author's profile photo Andrea Schlotthauer
      Andrea Schlotthauer
      Blog Post Author

      Hi Dhanunjai Gandavarapu,

      1. $projection is available as of 2021, so it should be supported. I could not reproduce the error, not even in an 2021 system. Can you please open an incident on

        BC-DWB-DIC for further investigation?

      2. Analytical projection views are available as of SAP S/4HANA and SAP S/4HANA Cloud, private edition as of 2022. So unfortunately, your release does not support this feature.

       

      Best

      Andrea