sap-abap-cds

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SAP ABAP CDS (Core Data Services)

SAP ABAP CDS(Core Data Services)

Related Skills

相关技能

  • sap-abap: Use for ABAP programming patterns used with CDS or when implementing EML statements in ABAP
  • sap-btp-cloud-platform: Use for CDS deployment scenarios on BTP or ABAP Environment configurations
  • sap-fiori-tools: Use when building Fiori Elements applications that consume CDS views or working with UI annotations
  • sap-cap-capire: Use for comparing CDS syntax between ABAP and CAP or when integrating ABAP CDS with CAP services
  • sap-api-style: Use when documenting CDS-based OData services or following API documentation standards
  • sap-abap:适用于与CDS搭配使用的ABAP编程模式,或在ABAP中实现EML语句的场景
  • sap-btp-cloud-platform:适用于BTP上的CDS部署场景或ABAP环境配置
  • sap-fiori-tools:适用于构建消费CDS视图的Fiori Elements应用,或处理UI注解的场景
  • sap-cap-capire:适用于对比ABAP与CAP的CDS语法,或集成ABAP CDS与CAP服务的场景
  • sap-api-style:适用于编写基于CDS的OData服务文档,或遵循API文档规范的场景

Table of Contents

目录

1. CDS View Fundamentals

1. CDS视图基础

View Types

视图类型

TypeSyntaxDatabase ViewSince
CDS View
DEFINE VIEW
Yes7.4 SP8
CDS View Entity
DEFINE VIEW ENTITY
No7.55
Recommendation: Use CDS View Entities for new development.
类型语法是否生成数据库视图始于版本
CDS View
DEFINE VIEW
7.4 SP8
CDS View Entity
DEFINE VIEW ENTITY
7.55
推荐:新开发请使用CDS View Entities。

Basic CDS View Syntax

基础CDS视图语法

sql
@AbapCatalog.sqlViewName: 'ZCDS_EXAMPLE_V'
@AbapCatalog.compiler.CompareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Example CDS View'

define view ZCDS_EXAMPLE
  as select from db_table as t
{
  key t.field1,
      t.field2,
      t.field3 as AliasName
}
sql
@AbapCatalog.sqlViewName: 'ZCDS_EXAMPLE_V'
@AbapCatalog.compiler.CompareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Example CDS View'

define view ZCDS_EXAMPLE
  as select from db_table as t
{
  key t.field1,
      t.field2,
      t.field3 as AliasName
}

CDS View Entity Syntax (7.55+)

CDS View Entity语法(7.55+)

sql
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Example View Entity'

define view entity Z_CDS_EXAMPLE
  as select from db_table as t
{
  key t.field1,
      t.field2,
      t.field3 as AliasName
}
Key Difference: View entities omit
@AbapCatalog.sqlViewName
- no SQL view generated.
sql
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Example View Entity'

define view entity Z_CDS_EXAMPLE
  as select from db_table as t
{
  key t.field1,
      t.field2,
      t.field3 as AliasName
}
核心差异:View Entity无需配置
@AbapCatalog.sqlViewName
,不会生成SQL视图。

Eclipse ADT Setup

Eclipse ADT设置步骤

  1. FileNewOtherCore Data ServicesData Definition
  2. Enter name, description, and package
  3. Select template (view, view entity, etc.)

  1. 文件新建其他Core Data Services数据定义
  2. 输入名称、描述和包名
  3. 选择模板(视图、视图实体等)

2. Essential Annotations

2. 核心注解

Core Annotations

基础注解

Essential annotations for CDS development:
  • @AbapCatalog.sqlViewName
    - SQL view name (max 16 chars)
  • @AbapCatalog.compiler.CompareFilter
    - Optimize WHERE clauses
  • @AccessControl.authorizationCheck
    - Set to #NOT_REQUIRED, #CHECK, #MANDATORY, or #NOT_ALLOWED
  • @EndUserText.label
    - User-facing description
  • @Metadata.allowExtensions
    - Allow view extensions
Complete Reference: See
references/annotations-reference.md
for 50+ annotations with examples.
CDS开发必备注解
  • @AbapCatalog.sqlViewName
    - SQL视图名称(最多16个字符)
  • @AbapCatalog.compiler.CompareFilter
    - 优化WHERE子句
  • @AccessControl.authorizationCheck
    - 可选值:#NOT_REQUIRED、#CHECK、#MANDATORY、#NOT_ALLOWED
  • @EndUserText.label
    - 面向用户的描述
  • @Metadata.allowExtensions
    - 允许视图扩展
完整参考:查看
references/annotations-reference.md
获取50+带示例的注解说明。

Semantics Annotations (Currency/Quantity)

语义注解(货币/数量)

Required for CURR and QUAN data types to avoid error SD_CDS_ENTITY105:
sql
-- Currency fields
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
amount,

-- Quantity fields
@Semantics.unitOfMeasure: true
meins,
@Semantics.quantity.unitOfMeasure: 'meins'
quantity
处理CURR和QUAN数据类型时必须配置,避免出现SD_CDS_ENTITY105错误:
sql
-- 货币字段
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
amount,

-- 数量字段
@Semantics.unitOfMeasure: true
meins,
@Semantics.quantity.unitOfMeasure: 'meins'
quantity

UI Annotations (Fiori Elements)

UI注解(Fiori Elements)

sql
@UI.lineItem: [{ position: 10 }]
@UI.identification: [{ position: 10 }]
@UI.selectionField: [{ position: 10 }]
field1,

@UI.hidden: true
internal_field
sql
@UI.lineItem: [{ position: 10 }]
@UI.identification: [{ position: 10 }]
@UI.selectionField: [{ position: 10 }]
field1,

@UI.hidden: true
internal_field

Consumption Annotations (Value Help)

消费注解(值帮助)

sql
@Consumption.valueHelpDefinition: [{
  entity: { name: 'I_Currency', element: 'Currency' }
}]
waers
For complete annotation reference, see
references/annotations-reference.md
.

sql
@Consumption.valueHelpDefinition: [{
  entity: { name: 'I_Currency', element: 'Currency' }
}]
waers
完整注解参考请查看
references/annotations-reference.md

3. Expressions and Operations

3. 表达式与运算

CASE Expressions

CASE表达式

Simple CASE (single variable comparison):
sql
case status
  when 'A' then 'Active'
  when 'I' then 'Inactive'
  else 'Unknown'
end as StatusText
Searched CASE (multiple conditions):
sql
case
  when amount > 1000 then 'High'
  when amount > 100 then 'Medium'
  else 'Low'
end as AmountCategory
简单CASE(单变量比较):
sql
case status
  when 'A' then 'Active'
  when 'I' then 'Inactive'
  else 'Unknown'
end as StatusText
搜索CASE(多条件判断):
sql
case
  when amount > 1000 then 'High'
  when amount > 100 then 'Medium'
  else 'Low'
end as AmountCategory

Comparison Operators

比较运算符

Standard operators:
=
,
<>
,
<
,
>
,
<=
,
>=
Special operators:
BETWEEN x AND y
,
LIKE
,
IS NULL
,
IS NOT NULL
Complete Reference: See
references/expressions-reference.md
for all operators and expressions.
标准运算符
=
,
<>
,
<
,
>
,
<=
,
>=
特殊运算符
BETWEEN x AND y
,
LIKE
,
IS NULL
,
IS NOT NULL
完整参考:查看
references/expressions-reference.md
获取所有运算符和表达式说明。

Arithmetic Operations

算术运算

sql
quantity * price as TotalAmount,
amount / 100 as Percentage,
-amount as NegatedAmount
sql
quantity * price as TotalAmount,
amount / 100 as Percentage,
-amount as NegatedAmount

Session Variables

会话变量

Available system variables (SY fields equivalent):
  • $session.user
    (SY-UNAME) - Current user
  • $session.client
    (SY-MANDT) - Client
  • $session.system_language
    (SY-LANGU) - Language
  • $session.system_date
    (SY-DATUM) - Current date
Complete Reference: See
references/expressions-reference.md
for all system variables.
sql
$session.user as CurrentUser,
$session.system_date as Today

可用系统变量(等价于SY字段):
  • $session.user
    (SY-UNAME) - 当前用户
  • $session.client
    (SY-MANDT) - 客户端
  • $session.system_language
    (SY-LANGU) - 系统语言
  • $session.system_date
    (SY-DATUM) - 当前日期
完整参考:查看
references/expressions-reference.md
获取所有系统变量说明。
sql
$session.user as CurrentUser,
$session.system_date as Today

4. Built-in Functions

4. 内置函数

CDS provides comprehensive built-in functions for string, numeric, and date operations.
CDS提供了完善的内置函数,支持字符串、数值和日期运算。

Key Function Categories

核心函数分类

  • String Functions: concat(), length(), substring(), upper(), lower(), replace()
  • Numeric Functions: abs(), ceil(), floor(), round(), division()
  • Date Functions: dats_add_days(), dats_add_months(), dats_days_between()
  • CAST Expression: Convert between ABAP data types
Complete Reference: See
references/functions-reference.md
for all 50+ functions with examples.
  • 字符串函数:concat()、length()、substring()、upper()、lower()、replace()
  • 数值函数:abs()、ceil()、floor()、round()、division()
  • 日期函数:dats_add_days()、dats_add_months()、dats_days_between()
  • CAST表达式:用于ABAP数据类型之间的转换
完整参考:查看
references/functions-reference.md
获取50+带示例的函数说明。

Quick Examples

快速示例

sql
-- String operations
concat(first_name, last_name) as FullName,
upper(name) as UpperName,
substring(description, 1, 10) as ShortDesc

-- Numeric operations  
abs(amount) as AbsoluteAmount,
round(value, 2) as RoundedValue,
division(10, 3, 2) as PreciseDivision

-- Date operations
dats_add_days(current_date, 7) as NextWeek,
dats_days_between(start_date, end_date) as Duration

-- Type conversion
cast(field as abap.char(10)) as TextField,
cast(amount as abap.curr(15,2)) as CurrencyField

**ABAP Types**: `abap.char()`, `abap.numc()`, `abap.int4`, `abap.dats`, `abap.tims`, `abap.curr()`, `abap.cuky`, `abap.quan()`, `abap.unit()`

---
sql
-- 字符串操作
concat(first_name, last_name) as FullName,
upper(name) as UpperName,
substring(description, 1, 10) as ShortDesc

-- 数值操作  
abs(amount) as AbsoluteAmount,
round(value, 2) as RoundedValue,
division(10, 3, 2) as PreciseDivision

-- 日期操作
dats_add_days(current_date, 7) as NextWeek,
dats_days_between(start_date, end_date) as Duration

-- 类型转换
cast(field as abap.char(10)) as TextField,
cast(amount as abap.curr(15,2)) as CurrencyField

**ABAP类型**`abap.char()`, `abap.numc()`, `abap.int4`, `abap.dats`, `abap.tims`, `abap.curr()`, `abap.cuky`, `abap.quan()`, `abap.unit()`

5. Joins

5. 连接查询

Join Types

连接类型

sql
-- INNER JOIN (matching rows only)
inner join makt as t on m.matnr = t.matnr

-- LEFT OUTER JOIN (all from left, matching from right)
left outer join marc as c on m.matnr = c.matnr

-- RIGHT OUTER JOIN (all from right, matching from left)
right outer join mvke as v on m.matnr = v.matnr

-- CROSS JOIN (cartesian product)
cross join t001 as co

sql
-- INNER JOIN(仅返回匹配行)
inner join makt as t on m.matnr = t.matnr

-- LEFT OUTER JOIN(返回左表所有行,右表匹配行)
left outer join marc as c on m.matnr = c.matnr

-- RIGHT OUTER JOIN(返回右表所有行,左表匹配行)
right outer join mvke as v on m.matnr = v.matnr

-- CROSS JOIN(笛卡尔积)
cross join t001 as co

6. Associations

6. 关联关系

Associations define relationships between entities (join-on-demand):
关联用于定义实体之间的关系(按需连接):

Defining Associations

定义关联

sql
define view Z_ASSOC_EXAMPLE as select from scarr as c
  association [1..*] to spfli as _Flights
    on $projection.carrid = _Flights.carrid
  association [0..1] to sairport as _Airport
    on $projection.hub = _Airport.id
{
  key c.carrid,
      c.carrname,
      c.hub,

      // Expose associations
      _Flights,
      _Airport
}
sql
define view Z_ASSOC_EXAMPLE as select from scarr as c
  association [1..*] to spfli as _Flights
    on $projection.carrid = _Flights.carrid
  association [0..1] to sairport as _Airport
    on $projection.hub = _Airport.id
{
  key c.carrid,
      c.carrname,
      c.hub,

      // 暴露关联
      _Flights,
      _Airport
}

Cardinality Notation

基数表示

Syntax mapping:
  • [0..1]
    or
    [1]
    association to one
    (LEFT OUTER MANY TO ONE)
  • [1..1]
    association to one
    (exact match)
  • [0..*]
    or
    [*]
    association to many
    (LEFT OUTER MANY TO MANY)
  • [1..*]
    association to many
    (one or more)
Complete Reference: See
references/associations-reference.md
for detailed cardinality guide.
语法映射
  • [0..1]
    [1]
    association to one
    (左外连接多对一)
  • [1..1]
    association to one
    (精确匹配)
  • [0..*]
    [*]
    association to many
    (左外连接多对多)
  • [1..*]
    association to many
    (一对多,至少一个匹配)
完整参考:查看
references/associations-reference.md
获取详细的基数指南。

New Cardinality Syntax (Release 2302+)

新基数语法(2302版本及以上)

sql
association to one _Customer on ...   -- [0..1]
association to many _Items on ...      -- [0..*]
sql
association to one _Customer on ...   -- [0..1]
association to many _Items on ...      -- [0..*]

Using Associations

使用关联

sql
-- Expose for consumer use
_Customer,

-- Ad-hoc field access (triggers join)
_Customer.name as CustomerName
sql
-- 暴露给消费者使用
_Customer,

-- 临时字段访问(触发连接)
_Customer.name as CustomerName

Path Expressions with Filter

带过滤的路径表达式

sql
-- Filter with cardinality indicator
_Items[1: Status = 'A'].ItemNo
For complete association reference, see
references/associations-reference.md
.

sql
-- 带基数标识的过滤
_Items[1: Status = 'A'].ItemNo
完整关联参考请查看
references/associations-reference.md

7. Input Parameters

7. 输入参数

Defining Parameters

定义参数

sql
define view Z_PARAM_EXAMPLE
  with parameters
    p_date_from : dats,
    p_date_to   : dats,
    @Environment.systemField: #SYSTEM_LANGUAGE
    p_langu     : spras
  as select from vbak as v
{
  key v.vbeln,
      v.erdat,
      v.erzet
}
where v.erdat between :p_date_from and :p_date_to
sql
define view Z_PARAM_EXAMPLE
  with parameters
    p_date_from : dats,
    p_date_to   : dats,
    @Environment.systemField: #SYSTEM_LANGUAGE
    p_langu     : spras
  as select from vbak as v
{
  key v.vbeln,
      v.erdat,
      v.erzet
}
where v.erdat between :p_date_from and :p_date_to

Parameter Reference

参数引用

Use colon notation
:p_date_from
or
$parameters.p_date_from
Calling from ABAP:
abap
SELECT * FROM z_param_example(
  p_date_from = '20240101',
  p_date_to   = '20241231',
  p_langu     = @sy-langu
) INTO TABLE @DATA(lt_result).

使用冒号语法
:p_date_from
$parameters.p_date_from
从ABAP调用示例
abap
SELECT * FROM z_param_example(
  p_date_from = '20240101',
  p_date_to   = '20241231',
  p_langu     = @sy-langu
) INTO TABLE @DATA(lt_result).

8. Aggregate Expressions

8. 聚合表达式

Aggregate Functions

聚合函数

sql
define view Z_AGG_EXAMPLE as select from vbap as i
{
  i.vbeln,
  sum(i.netwr) as TotalAmount,
  avg(i.netwr) as AvgAmount,
  max(i.netwr) as MaxAmount,
  min(i.netwr) as MinAmount,
  count(*) as ItemCount
}
group by i.vbeln
having sum(i.netwr) > 1000

sql
define view Z_AGG_EXAMPLE as select from vbap as i
{
  i.vbeln,
  sum(i.netwr) as TotalAmount,
  avg(i.netwr) as AvgAmount,
  max(i.netwr) as MaxAmount,
  min(i.netwr) as MinAmount,
  count(*) as ItemCount
}
group by i.vbeln
having sum(i.netwr) > 1000

9. Access Control (DCL)

9. 访问控制(DCL)

Basic DCL Structure

基础DCL结构

sql
@MappingRole: true
define role Z_CDS_EXAMPLE_DCL {
  grant select on Z_CDS_EXAMPLE
    where (bukrs) = aspect pfcg_auth(F_BKPF_BUK, BUKRS, ACTVT = '03');
}
sql
@MappingRole: true
define role Z_CDS_EXAMPLE_DCL {
  grant select on Z_CDS_EXAMPLE
    where (bukrs) = aspect pfcg_auth(F_BKPF_BUK, BUKRS, ACTVT = '03');
}

Authorization Check Options

权限检查选项

Available values:
  • #NOT_REQUIRED
    - No authorization check
  • #CHECK
    - Warning if no DCL exists
  • #MANDATORY
    - Error if no DCL exists
  • #NOT_ALLOWED
    - DCL ignored if exists
Complete Reference: See
references/access-control-reference.md
for detailed DCL patterns.
可选值
  • #NOT_REQUIRED
    - 无权限检查
  • #CHECK
    - 无DCL时抛出警告
  • #MANDATORY
    - 无DCL时抛出错误
  • #NOT_ALLOWED
    - 忽略已有的DCL
完整参考:查看
references/access-control-reference.md
获取详细的DCL模式说明。

Condition Types

条件类型

PFCG Authorization:
where (field) = aspect pfcg_auth(AUTH_OBJECT, AUTH_FIELD, ACTVT = '03')
Literal Condition:
where status <> 'DELETED'
User Aspect:
where created_by ?= aspect user
Combined:
where (bukrs) = aspect pfcg_auth(...) and status = 'ACTIVE'
For complete access control reference, see
references/access-control-reference.md
.

PFCG权限
where (field) = aspect pfcg_auth(AUTH_OBJECT, AUTH_FIELD, ACTVT = '03')
字面量条件
where status <> 'DELETED'
用户维度
where created_by ?= aspect user
组合条件
where (bukrs) = aspect pfcg_auth(...) and status = 'ACTIVE'
完整访问控制参考请查看
references/access-control-reference.md

10. Data Retrieval from ABAP

10. 从ABAP中获取数据

Standard SELECT

标准SELECT查询

abap
SELECT * FROM zcds_example
  WHERE field1 = @lv_value
  INTO TABLE @DATA(lt_result).
abap
SELECT * FROM zcds_example
  WHERE field1 = @lv_value
  INTO TABLE @DATA(lt_result).

SALV IDA (Integrated Data Access)

SALV IDA(集成数据访问)

abap
cl_salv_gui_table_ida=>create_for_cds_view(
  CONV #( 'ZCDS_EXAMPLE' )
)->fullscreen( )->display( ).

abap
cl_salv_gui_table_ida=>create_for_cds_view(
  CONV #( 'ZCDS_EXAMPLE' )
)->fullscreen( )->display( ).

11. Common Errors and Solutions

11. 常见问题与解决方案

SD_CDS_ENTITY105: Missing Reference Information

SD_CDS_ENTITY105:缺失参考信息

Problem: CURR/QUAN fields without reference
Solution: Add semantics annotations
sql
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
netwr
Or import currency from related table:
sql
inner join t001 as c on ...
{
  c.waers,
  @Semantics.amount.currencyCode: 'waers'
  v.amount
}
问题:CURR/QUAN字段未配置参考字段
解决方案:添加语义注解
sql
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
netwr
或从关联表引入货币字段:
sql
inner join t001 as c on ...
{
  c.waers,
  @Semantics.amount.currencyCode: 'waers'
  v.amount
}

Cardinality Warnings

基数警告

Problem: Cardinality doesn't match actual data
Solution: Define cardinality matching data model
sql
association [0..1] to ...  -- Use for optional relationships
association [1..*] to ...  -- Use for required one-to-many
For complete troubleshooting guide, see
references/troubleshooting.md
.

问题:基数与实际数据不匹配
解决方案:定义与数据模型匹配的基数
sql
association [0..1] to ...  -- 用于可选关系
association [1..*] to ...  -- 用于必填的一对多关系
完整排查指南请查看
references/troubleshooting.md

12. Useful Transactions and Tables

12. 常用事务码与表

Key Transactions

核心事务码

  • SDDLAR - Display/repair DDL structures
  • RSRTS_ODP_DIS - TransientProvider preview
  • RSRTS_QUERY_CHECK - CDS query metadata validation
  • SE63 - Translation (EndUserText)
  • SE11 - ABAP Dictionary
  • SU21 - Authorization objects
  • SDDLAR - 展示/修复DDL结构
  • RSRTS_ODP_DIS - 瞬态提供程序预览
  • RSRTS_QUERY_CHECK - CDS查询元数据校验
  • SE63 - 翻译(EndUserText)
  • SE11 - ABAP字典
  • SU21 - 权限对象

Important Tables

重要表

  • DDHEADANNO - Header-level annotations
  • CDSVIEWANNOPOS - CDS view header annotations
  • CDS_FIELD_ANNOTATION - Field-level annotations
  • ABDOC_CDS_ANNOS - SAP annotation definitions
  • DDHEADANNO - 头层级注解
  • CDSVIEWANNOPOS - CDS视图头注解
  • CDS_FIELD_ANNOTATION - 字段层级注解
  • ABDOC_CDS_ANNOS - SAP注解定义

API Class

API类

CL_DD_DDL_ANNOTATION_SERVICE
- Programmatic annotation access:
  • get_annos()
    - Get all annotations
  • get_label_4_element()
    - Get @EndUserText.label

CL_DD_DDL_ANNOTATION_SERVICE
- 程序化访问注解:
  • get_annos()
    - 获取所有注解
  • get_label_4_element()
    - 获取@EndUserText.label值

Bundled Resources

配套资源

Reference Documentation

参考文档

For detailed guidance, see the reference files in
references/
:
  • annotations-reference.md
    - Complete annotation catalog
  • functions-reference.md
    - All built-in functions with examples
  • associations-reference.md
    - Associations and cardinality guide
  • access-control-reference.md
    - DCL and authorization patterns
  • expressions-reference.md
    - Expressions and operators
  • troubleshooting.md
    - Common errors and solutions
如需详细指导,请查看
references/
目录下的参考文件:
  • annotations-reference.md
    - 完整注解目录
  • functions-reference.md
    - 所有内置函数及示例
  • associations-reference.md
    - 关联与基数指南
  • access-control-reference.md
    - DCL与权限模式
  • expressions-reference.md
    - 表达式与运算符
  • troubleshooting.md
    - 常见错误与解决方案

Templates

模板

For templates, see
templates/
:
  • basic-view.md
    - Standard CDS view template
  • parameterized-view.md
    - View with input parameters
  • dcl-template.md
    - Access control definition

如需模板,请查看
templates/
目录:
  • basic-view.md
    - 标准CDS视图模板
  • parameterized-view.md
    - 带输入参数的视图
  • dcl-template.md
    - 访问控制定义模板

Source Documentation

源文档