CDS View Entities

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Most business questions are answered by combining and reshaping data that sits in several database tables: which claims belong to which employee, which claims are still open, what a claim is worth in words a screen can show. A CDS view entity lets you describe such a result once, in a small text file, and store it in the system under a name. After that, programs, screens and web services read the view as if it were a table, and the database does the work. This page explains what a view entity is, how its select list is written, the expressions you can use in it, how input parameters and client handling behave, and how SAP layers view entities on top of each other. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). View entities exist in ABAP Cloud and in classic Standard ABAP, on premise and in the Public Edition alike; in ABAP Cloud a view may select only from data sources that are released for it, a rule that ABAP Language Versions and Released APIs explains.

Before you read

Key terms

  • Core data services (CDS): the part of ABAP in which you describe data models, such as views, as text that the system turns into database objects.

  • CDS view entity: a view defined in ABAP CDS with DEFINE VIEW ENTITY that selects data from one or more data sources and can be read like a table.

  • Select list: the part in braces that names the elements (the columns) of the view.

  • Input parameter: a value that the reader of a view entity hands in when reading it, for example a status to filter by.

  • Client handling: the automatic restriction of a client-dependent view to the rows of the client the program runs in.

  • Virtual data model (VDM): SAP’s layered set of CDS views, in which each layer has a defined purpose and a name prefix.

What a view entity is

Think of a saved query that has a name. A database table stores rows; a view stores no rows at all, only the description of how to compute rows from other things when somebody asks. The SAP documentation defines a CDS view entity as a CDS entity whose main purpose is to select data from one or more data sources, such as database tables, and says that view entities can be enriched with meaning through annotations, which are short @ lines that attach metadata to the view.

You write a view entity in ABAP Development Tools (ADT) as a data definition. The definition is a source text with a fixed outline: optional annotations at the top, the statement DEFINE VIEW ENTITY with a name, optional input parameters, AS SELECT FROM a data source, the element list in braces, and then optional clauses such as WHERE or GROUP BY. The name has at most 30 characters, is not case-sensitive, lives in the namespace shared by all global types of the system, and must be the same as the name of the data definition. After the view has been transported its name can no longer be changed.

Two points help a newcomer. First, defining views is usually the task of the people who design the data model; most ABAP programmers only read views with SELECT, and a view must stay stable enough for that. Second, a view has no runtime logic of its own: the select statement, its expressions and its functions are evaluated by the database when a program, a screen or a service reads the view.

A first view entity: ZI_ExpClaim

The running example of this section is an expense-claim system. The database table ZEXP_CLAIM (see the page on dictionary tables) holds one row per claim, with the key CLAIM_ID, the columns EMPLOYEE_ID, STATUS, CURRENCY_CODE and TOTAL_AMOUNT, and two audit columns. The view entity below exposes the claim in a form that other objects can build on. The status codes A for approved and R for rejected, and the threshold 1000, are invented for this example.

@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Expense claim'
@Metadata.ignorePropagatedAnnotations: true
define view entity ZI_ExpClaim
  as select from zexp_claim
{
  key claim_id      as ClaimId,
      employee_id   as EmployeeId,
      status        as Status,
      currency_code as CurrencyCode,

      @Semantics.amount.currencyCode: 'CurrencyCode'
      total_amount  as TotalAmount,

      case status
        when 'A' then 'Approved'
        when 'R' then 'Rejected'
        else 'Open'
      end                                   as StatusText,

      case
        when total_amount >= 1000 then 'large'
        else 'small'
      end                                   as SizeClass,

      concat_with_space( claim_id, status, 1 ) as Label
}

Requires an SAP system; not run here. The view is an illustration built on the example table ZEXP_CLAIM; it does not belong to the local lab, which has no CDS.

Reading it from the top:

  • @AccessControl.authorizationCheck: #NOT_REQUIRED says that no access control is required for this teaching view; a real view that exposes business data would be protected by an access control. The SAP template for view entities uses this value as its default, which declares access control as optional.

  • @EndUserText.label is a short description for people.

  • @Metadata.ignorePropagatedAnnotations: true switches off the automatic inheritance of annotations from the data sources. The SAP template sets it so that a view in a higher layer stays stable even if an annotation of a lower layer is added or changed. The SAP documentation warns that it can also remove mandatory annotations, such as the currency reference of an amount, which then have to be written again; that is why the amount carries its own @Semantics.amount.currencyCode line.

  • ZI_ExpClaim is the name; the table zexp_claim after FROM is the data source.

  • The braces hold the select list, explained next.

The select list

The select list names the elements of the view; the elements become the components of the structured type that the view defines, and ABAP programs can type a variable with them. The names in the list must be unique, and they share their namespace with the names of the view’s input parameters.

  • key marks an element as part of the key of the view. Keys must stand at the beginning of the list. In a view entity the key mainly documents the meaning of the data model; the SAP samples state explicitly that keys do not define unique rows in the result.

  • as alias gives an element another name. Here the database column claim_id is exposed as ClaimId, in the camel-case style that SAP uses for view elements. An alias is optional for a plain field and mandatory for every other kind of element: literals, parameters, session variables, calculations, function calls, case distinctions and casts.

  • An element can be a field of the data source, a field reached through an association path, a literal, an input parameter, a session variable, an aggregate, an arithmetic expression, a built-in function, a case distinction or a cast. If the view reads several data sources with joins, every element must be prefixed with the name or alias of its source, even when the field name is unique.

  • An annotation written directly above an element, like the currency reference above TotalAmount, belongs to that element only.

Expressions in the select list

The database evaluates every expression when the view is read. The table lists the kinds you meet first; the keyword documentation has the complete set.

Expression What it does Example from this page

Literal

A fixed value. Typed literals state their dictionary type, as in abap.dec'0.9'; untyped literals such as 'small' do not.

'small'

Arithmetic

Adds, subtracts, multiplies or divides numeric operands.

seatsmax - seatsocc in the SAP sample

CAST

Converts a value to another type, for example a decimal number to a character string.

cast( total_amount as abap.dec(17,2) )

CASE

Chooses a result by comparing a value, or by checking conditions in order.

StatusText, SizeClass

Built-in function

Numeric, string, date and time, conversion and COALESCE functions evaluated by the database.

concat_with_space( claim_id, status, 1 )

Session variable

A value of the current session, such as $session.user or $session.client.

$session.user

Aggregate

SUM, COUNT, AVG and the like, used together with GROUP BY.

sum( ... ) on the code pushdown page

Two more expression forms deserve a sentence. A reuse expression refers to an element defined earlier in the same list with the prefix $projection., which saves repeating a calculation; the SAP sample uses it inside a cast. A path expression follows an association to a field of another entity; associations have their own page.

CAST

CAST( operand AS dtype ) converts the operand and gives the result the type dtype. The operand can be a field, a literal, a parameter, a session variable, another expression or a nested cast. The type can be a built-in dictionary type, a data element or a user-defined CDS type. Which pairs of types can be converted into each other is fixed by a table in the keyword documentation, with its own rules per pair, so check it before you cast. With the addition PRESERVING TYPE the semantic information of a data element or simple type is kept; the documentation recommends it when a case distinction would otherwise lose the data element.

CASE

There are two forms. The simple form compares one value with several others and returns the result of the first match, as StatusText does with status. The searched form checks conditions in order and returns the result of the first true one, as SizeClass does. Without ELSE the result is the null value. Nested CASE expressions are evaluated from the inside out.

Built-in functions

Built-in functions are the second large family. The keyword documentation groups them into numeric functions, string functions, the COALESCE function (which returns its first argument unless that is null, and then the second), special functions such as type, unit and currency conversion, and date, time and time stamp functions. The SAP sample view shows many of them: abs, ceil, floor, div, mod and round for numbers; concat, concat_with_space, left, right, lower, upper, lpad, rpad, replace and substring for text; dats_days_between and dats_add_days for dates. A function can take fields, literals and parameters as arguments, as long as the data types fit.

Input parameters

Sometimes a view needs a value that only the reader knows, such as the status to look at. A view entity can declare input parameters with WITH PARAMETERS, between the view name and AS SELECT. A parameter must have an elementary type, and inside the view it is written $parameters.name. Parameters can be used as an element (with a mandatory alias), inside arithmetic expressions, casts, case distinctions and functions, and on the right side of a condition in WHERE, HAVING, an ON condition or a path filter.

@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Expense claims of one status'
define view entity ZI_ExpClaimByStatus
  with parameters
    p_status : abap.char(1)
  as select from zexp_claim
{
  key claim_id as ClaimId,
      employee_id as EmployeeId,
      status as Status
}
where status = $parameters.p_status

A program passes the parameter in parentheses after the name of the view, as in this SELECT:

SELECT FROM zi_expclaimbystatus( p_status = 'A' )
       FIELDS ClaimId, EmployeeId
       ORDER BY ClaimId
       INTO TABLE @DATA(approved).

Requires an SAP system; not run here. Both listings are illustrations that follow the pattern of the SAP view Demo_Cds_Param_View_Entity, which uses three parameters in its WHERE clause.

Client handling

A client is a self-contained set of business data inside one SAP system, and most tables carry a client column as the first key field. A programmer on the classic side learned to remember it in every statement. A view entity does it for you, and there is nothing to write.

The view is client-dependent when at least one of its data sources is, and client-independent when none is; unlike the older DDIC-based CDS views, this is not set by an annotation. For a client-dependent view the system filters on the client held in the session variable $session.client, which is filled with the client of the current session by default. It adds the comparison of the client columns to the ON conditions of joins, and it adds a WHERE condition for the client to client-dependent tables. That is why ZI_ExpClaim does not select the client column: the view cannot return rows of another client, and a single read cannot mix clients. The addition USING ALL CLIENTS is not allowed for view entities.

Layers and naming: I_, R_ and C_

A single view rarely does everything. SAP builds its data models as a stack of views, each layer reading the one below. The SAP documentation says the same of its own advice: view entities form the base layer of an application, and further layers on top of them fine-tune the model for a scenario. A view entity can select from another view entity, which is called nesting; there is no technical limit to the depth, but the documentation advises against recursive references and too many levels, because the model becomes complex and error-prone. A nested view inherits the annotations of the view below unless you switch that off, as ZI_ExpClaim does.

The ABAP RESTful Application Programming Model (RAP) guide gives the naming convention for the layers. Its general rule for a development object name is a namespace, a prefix and a suffix around the object name. For CDS entities the prefixes are as follows.

Prefix Meaning in the RAP guide In the expense-claim example

I_

An interface view.

ZI_ExpClaim: the claim as the rest of the model sees it.

R_

The base CDS view entity (of a business object).

Not used in the running example: its root entity is the interface view ZI_ExpClaim, covered in the RAP pages.

C_

A projection view; the C stands for the consumption layer.

ZC_ExpClaim: the projection of the claim for one app, covered in the RAP pages.

E_

An extension include view.

Not used here.

The guide adds the suffix TP to mark a view that takes part in transactional processing, and states that a metadata extension has the same name as the CDS entity it belongs to. The customer prefix, here Z, is put in front by the organisation: the guide asks you to use your own reserved namespace, and says the namespace /DMO/ is only for demos.

Independently of names, SAP’s virtual data model (VDM) classifies its views with the annotation @VDM.viewType, whose values are #BASIC for reusable interface views that form the core data, #COMPOSITE for reusable views composed from basic ones, #CONSUMPTION for views that serve a specific application, #TRANSACTIONAL for composite views that define the transactional runtime of an object, #EXTENSION and #DERIVATION_FUNCTION. The documentation states that VDM annotations have no influence on runtime; they let tools such as view browsers read the layers correctly.

flowchart TD T[(Database table ZEXP_CLAIM)] --> I[ZI_ExpClaim: interface view and root of the business object] I --> C1[ZC_ExpClaim: projection for the claim app] I --> C2[ZC_ExpClaimApprover: projection for another app]

The diagram shows the direction of reading: every layer selects from the one above it in the picture, and consumers such as an app read only the top layer. Older books describe views in the DDIC-based style, with an @AbapCatalog.sqlViewName annotation and a second, generated database view; for new work the view entity is the form to learn, and the notes above on client handling and annotations mark the places where its behaviour differs from the older form.

Properties that live outside the view

The source of a view entity holds its select statement, its keys and its annotations. Other properties are set by separate objects that point at the view: entity extensions add fields, associations or annotations without changing the view, metadata extensions add annotations, access controls restrict who may see rows, and entity buffers set buffering. The next pages of this section cover associations, annotations and metadata extensions, and access control. In ADT, the Active Annotations view shows which annotations a view really has, including inherited ones, and the Dependency Analyzer shows its data sources as a tree.

Summary

  • A CDS view entity is a named, stored query that selects from tables or other views; programs read it with SELECT, and the database evaluates its expressions.

  • DEFINE VIEW ENTITY is followed by optional parameters, the data source, a select list in braces and optional clauses; keys come first in the list and every calculated element needs an alias.

  • CAST converts types, CASE chooses a result in a simple or searched form, and built-in functions work on numbers, text, dates and null values.

  • Input parameters are declared with WITH PARAMETERS, used as $parameters.name and passed in parentheses by the reader.

  • Client handling is automatic: a view is client-dependent when a data source is, and the system adds the client conditions through $session.client.

  • SAP layers views and names them I_ (interface), R_ (base of a business object) and C_ (projection); this page’s listings require an SAP system and were not run here.