sap-abap-cds by secondsky/sap-skills
npx skills add https://github.com/secondsky/sap-skills --skill sap-abap-cds快速参考 : https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/abencds.html | SAP 速查表: https://github.com/SAP-samples/abap-cheat-sheets/blob/main/15_CDS_View_Entities.md
| 类型 |
|---|
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 语法 |
|---|
| 数据库视图 |
|---|
| 起始版本 |
|---|
| CDS 视图 | DEFINE VIEW | 是 | 7.4 SP8 |
| CDS 视图实体 | DEFINE VIEW ENTITY | 否 | 7.55 |
建议 : 新开发请使用 CDS 视图实体。
@AbapCatalog.sqlViewName: 'ZCDS_EXAMPLE_V'
@AbapCatalog.compiler.CompareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: '示例 CDS 视图'
define view ZCDS_EXAMPLE
as select from db_table as t
{
key t.field1,
t.field2,
t.field3 as AliasName
}
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: '示例视图实体'
define view entity Z_CDS_EXAMPLE
as select from db_table as t
{
key t.field1,
t.field2,
t.field3 as AliasName
}
关键区别 : 视图实体省略了 @AbapCatalog.sqlViewName - 不生成 SQL 视图。
CDS 开发的核心注解 :
@AbapCatalog.sqlViewName - SQL 视图名称(最多 16 个字符)@AbapCatalog.compiler.CompareFilter - 优化 WHERE 子句@AccessControl.authorizationCheck - 设置为 #NOT_REQUIRED、#CHECK、#MANDATORY 或 #NOT_ALLOWED@EndUserText.label - 面向用户的描述@Metadata.allowExtensions - 允许视图扩展完整参考 : 有关 50 多个带示例的注解,请参阅 references/annotations-reference.md。
对于 CURR 和 QUAN 数据类型是必需的,以避免错误 SD_CDS_ENTITY105:
-- 货币字段
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
amount,
-- 数量字段
@Semantics.unitOfMeasure: true
meins,
@Semantics.quantity.unitOfMeasure: 'meins'
quantity
@UI.lineItem: [{ position: 10 }]
@UI.identification: [{ position: 10 }]
@UI.selectionField: [{ position: 10 }]
field1,
@UI.hidden: true
internal_field
@Consumption.valueHelpDefinition: [{
entity: { name: 'I_Currency', element: 'Currency' }
}]
waers
完整的注解参考,请参阅 references/annotations-reference.md。
简单 CASE(单变量比较):
case status
when 'A' then '激活'
when 'I' then '未激活'
else '未知'
end as StatusText
搜索 CASE(多条件):
case
when amount > 1000 then '高'
when amount > 100 then '中'
else '低'
end as AmountCategory
标准运算符 : =, <>, <, >, <=, >= 特殊运算符 : BETWEEN x AND y, LIKE, IS NULL, IS NOT NULL
完整参考 : 所有运算符和表达式,请参阅 references/expressions-reference.md。
quantity * price as TotalAmount,
amount / 100 as Percentage,
-amount as NegatedAmount
可用的系统变量(相当于 SY 字段):
$session.user (SY-UNAME) - 当前用户$session.client (SY-MANDT) - 客户端$session.system_language (SY-LANGU) - 语言$session.system_date (SY-DATUM) - 当前日期完整参考 : 所有系统变量,请参阅 references/expressions-reference.md。
$session.user as CurrentUser,
$session.system_date as Today
CDS 提供了全面的内置函数,用于字符串、数字和日期操作。
完整参考 : 所有 50 多个带示例的函数,请参阅 references/functions-reference.md。
-- 字符串操作
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. 连接
### 连接类型
```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
关联定义实体之间的关系(按需连接):
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
}
语法映射 :
[0..1] 或 [1] → association to one (LEFT OUTER MANY TO ONE)[1..1] → association to one (精确匹配)[0..*] 或 [*] → association to many (LEFT OUTER MANY TO MANY)[1..*] → association to many (一个或多个)完整参考 : 详细的基数指南,请参阅 references/associations-reference.md。
association to one _Customer on ... -- [0..1]
association to many _Items on ... -- [0..*]
-- 暴露供消费者使用
_Customer,
-- 临时字段访问(触发连接)
_Customer.name as CustomerName
-- 使用基数指示符过滤
_Items[1: Status = 'A'].ItemNo
完整的关联参考,请参阅 references/associations-reference.md。
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
使用冒号表示法 :p_date_from 或 $parameters.p_date_from
从 ABAP 调用 :
SELECT * FROM z_param_example(
p_date_from = '20240101',
p_date_to = '20241231',
p_langu = @sy-langu
) INTO TABLE @DATA(lt_result).
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
@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');
}
可用值 :
#NOT_REQUIRED - 无需授权检查#CHECK - 如果不存在 DCL 则警告#MANDATORY - 如果不存在 DCL 则报错#NOT_ALLOWED - 如果存在 DCL 则忽略完整参考 : 详细的 DCL 模式,请参阅 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。
SELECT * FROM zcds_example
WHERE field1 = @lv_value
INTO TABLE @DATA(lt_result).
cl_salv_gui_table_ida=>create_for_cds_view(
CONV #( 'ZCDS_EXAMPLE' )
)->fullscreen( )->display( ).
问题 : CURR/QUAN 字段没有参考
解决方案 : 添加语义注解
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
netwr
或者从相关表导入货币:
inner join t001 as c on ...
{
c.waers,
@Semantics.amount.currencyCode: 'waers'
v.amount
}
问题 : 基数与实际数据不匹配
解决方案 : 定义与数据模型匹配的基数
association [0..1] to ... -- 用于可选关系
association [1..*] to ... -- 用于必需的一对多关系
完整的故障排除指南,请参阅 references/troubleshooting.md。
CL_DD_DDL_ANNOTATION_SERVICE - 编程方式访问注解:
get_annos() - 获取所有注解get_label_4_element() - 获取 @EndUserText.label详细指南,请参阅 references/ 中的参考文件:
annotations-reference.md - 完整的注解目录functions-reference.md - 所有内置函数及示例associations-reference.md - 关联和基数指南access-control-reference.md - DCL 和授权模式expressions-reference.md - 表达式和运算符troubleshooting.md - 常见错误和解决方案模板,请参阅 templates/:
basic-view.md - 标准 CDS 视图模板parameterized-view.md - 带输入参数的视图模板dcl-template.md - 访问控制定义模板通过检查以下内容更新此技能 :
最后验证 : 2025-11-23
每周安装数
85
仓库
GitHub 星标数
162
首次出现
2026年2月5日
安全审计
安装于
amp84
gemini-cli84
opencode84
codex84
github-copilot84
kimi-cli84
Quick Reference : https://help.sap.com/doc/abapdocu_cp_index_htm/CLOUD/en-US/abencds.html | SAP Cheat Sheets: https://github.com/SAP-samples/abap-cheat-sheets/blob/main/15_CDS_View_Entities.md
| Type | Syntax | Database View | Since |
|---|---|---|---|
| CDS View | DEFINE VIEW | Yes | 7.4 SP8 |
| CDS View Entity | DEFINE VIEW ENTITY | No | 7.55 |
Recommendation : Use CDS View Entities for new development.
@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
}
@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.
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 extensionsComplete Reference : See references/annotations-reference.md for 50+ annotations with examples.
Required for CURR and QUAN data types to avoid error SD_CDS_ENTITY105:
-- Currency fields
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
amount,
-- Quantity fields
@Semantics.unitOfMeasure: true
meins,
@Semantics.quantity.unitOfMeasure: 'meins'
quantity
@UI.lineItem: [{ position: 10 }]
@UI.identification: [{ position: 10 }]
@UI.selectionField: [{ position: 10 }]
field1,
@UI.hidden: true
internal_field
@Consumption.valueHelpDefinition: [{
entity: { name: 'I_Currency', element: 'Currency' }
}]
waers
For complete annotation reference, see references/annotations-reference.md.
Simple CASE (single variable comparison):
case status
when 'A' then 'Active'
when 'I' then 'Inactive'
else 'Unknown'
end as StatusText
Searched CASE (multiple conditions):
case
when amount > 1000 then 'High'
when amount > 100 then 'Medium'
else 'Low'
end as AmountCategory
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.
quantity * price as TotalAmount,
amount / 100 as Percentage,
-amount as NegatedAmount
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 dateComplete Reference : See references/expressions-reference.md for all system variables.
$session.user as CurrentUser,
$session.system_date as Today
CDS provides comprehensive built-in functions for string, numeric, and date operations.
Complete Reference : See references/functions-reference.md for all 50+ functions with examples.
-- 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()`
---
## 5. Joins
### 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
Associations define relationships between entities (join-on-demand):
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
}
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.
association to one _Customer on ... -- [0..1]
association to many _Items on ... -- [0..*]
-- Expose for consumer use
_Customer,
-- Ad-hoc field access (triggers join)
_Customer.name as CustomerName
-- Filter with cardinality indicator
_Items[1: Status = 'A'].ItemNo
For complete association reference, see references/associations-reference.md.
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
Use colon notation :p_date_from or $parameters.p_date_from
Calling from ABAP :
SELECT * FROM z_param_example(
p_date_from = '20240101',
p_date_to = '20241231',
p_langu = @sy-langu
) INTO TABLE @DATA(lt_result).
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
@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');
}
Available values :
#NOT_REQUIRED - No authorization check#CHECK - Warning if no DCL exists#MANDATORY - Error if no DCL exists#NOT_ALLOWED - DCL ignored if existsComplete Reference : See references/access-control-reference.md for detailed DCL patterns.
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.
SELECT * FROM zcds_example
WHERE field1 = @lv_value
INTO TABLE @DATA(lt_result).
cl_salv_gui_table_ida=>create_for_cds_view(
CONV #( 'ZCDS_EXAMPLE' )
)->fullscreen( )->display( ).
Problem : CURR/QUAN fields without reference
Solution : Add semantics annotations
@Semantics.currencyCode: true
waers,
@Semantics.amount.currencyCode: 'waers'
netwr
Or import currency from related table:
inner join t001 as c on ...
{
c.waers,
@Semantics.amount.currencyCode: 'waers'
v.amount
}
Problem : Cardinality doesn't match actual data
Solution : Define cardinality matching data model
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.
CL_DD_DDL_ANNOTATION_SERVICE - Programmatic annotation access:
get_annos() - Get all annotationsget_label_4_element() - Get @EndUserText.labelFor detailed guidance, see the reference files in references/:
annotations-reference.md - Complete annotation catalogfunctions-reference.md - All built-in functions with examplesassociations-reference.md - Associations and cardinality guideaccess-control-reference.md - DCL and authorization patternsexpressions-reference.md - Expressions and operatorstroubleshooting.md - Common errors and solutionsFor templates, see templates/:
basic-view.md - Standard CDS view templateparameterized-view.md - View with input parametersdcl-template.md - Access control definitionUpdate this skill by checking :
Last Verified : 2025-11-23
Weekly Installs
85
Repository
GitHub Stars
162
First Seen
Feb 5, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
amp84
gemini-cli84
opencode84
codex84
github-copilot84
kimi-cli84
lark-cli 共享规则:飞书资源操作指南与权限配置详解
39,000 周安装