合理地使用集,能有效避免硬编码,增加程序的可维护性和灵活性。本文以实现资产负债表的报表项为例,讲解 Set 的用法以及 ABAP 中如何获取 Set 的值。
维护集合 (Set)
在 SAP 中,通过下面的事务码维护集
- GS01: 创建集
- GS02: 修改集
- GS03: 显示集
- GS04: 删除集
SAP 支持 4 种类型的集:
- 基本集(basic set):在集中保存单一维度的值。比如以报表项为基础建立基本集,每一个报表项由会计科目的范围组成。在创建 Set 的时候,需要指定参照的数据库表和字段。
回车后输入参照的字段:
然后维护 ASST020 所包括的科目范围。每一行可以是单值,也可以是一个范围,允许多行。界面非常直观:
- 单维集 (single set):由 single set 构成的集,用于表示层次结构。比如基于 basic set 创建的 ZBS,用于表示资产负债表的所有报表项。
- 多维集(multi set): 由 basic set 和 single set构成的集合
- 指标集(key figure): 用于 report painter
集的数据表
SAP 对 set 主要存储在下面几个表中:
-
setheader: set header and directory。比如 ASST020,在 setheader 表中存储形式如下:
-
setleaf: 存储 set 的值。比如 ASST020,在 setleaf 表中存储如下:
如何获取 set 的值
SAP 提供下面几个函数用于获取 set 的值
G_SET_GET_ID_FROM_NAME
:根据 set name 获取 set id。set name 是 GS01 创建的时候使用的 name,比如 asst020。这个 id 用于后面两个函数中,根据 set id 获取对应的值。G_SET_GET_ALL_VALUES
: 根据 set id 获取 set 的所有值G_SET_FETCH
: 根据 set id 获取 set 的子项
下面演示如何通过这几个函数,获取 ZBS 集合中的所有值
report z_set_test.
data setid like sethier-setid.
data: setvalues type standard table of rgsb4 with header line.
start-of-selection.
call function 'G_SET_GET_ID_FROM_NAME'
exporting
shortname = 'ZBS'
importing
new_setid = setid.
call function 'G_SET_GET_ALL_VALUES'
exporting
setnr = setid
tables
set_values = setvalues.
loop at setvalues.
write: / setvalues-shortname,
setvalues-field,
setvalues-from,
setvalues-to.
endloop.
程序运行结果如下:
也可以使用 G_SET_FETCH
函数来获取 set 的值:
report z_set_test.
data setid like sethier-setid.
data: setvalues type standard table of rgsb4 with header line,
single_lines type standard table of rgsb1 with header line,
basic_lines type standard table of rgsbv with header line.
start-of-selection.
call function 'G_SET_GET_ID_FROM_NAME'
exporting
shortname = 'ZBS'
importing
new_setid = setid.
call function 'G_SET_FETCH'
exporting
setnr = setid
tables
set_lines_single = single_lines.
loop at single_lines.
call function 'G_SET_FETCH'
exporting
setnr = single_lines-setnr
tables
set_lines_basic = basic_lines.
loop at basic_lines.
write: / single_lines-setnr,
basic_lines-title,
basic_lines-from,
basic_lines-to.
endloop.
endloop.
程序运行界面如下:
也可以直接调用 G_SET_GET_ALL_VALUES
函数获取 set 的值,使用方法如下:
report z_set_test.
data setid like sethier-setid.
data: setvalues type standard table of rgsb4 with header line.
start-of-selection.
call function 'G_SET_GET_ALL_VALUES'
exporting
client = sy-mandt
setnr = 'ZBS'
table = 'SKB1'
class = '0000'
fieldname = 'SAKNR'
tables
set_values = setvalues.
loop at setvalues.
write: / setvalues-shortname,
setvalues-field,
setvalues-from,
setvalues-to.
endloop.