背景
内表的排序是ABAP最常见的操作,但是遇到动态内表时,无法静态指定内表组件,因此需要动态实现
解决方案
- 简单变量+小括号()
- 排序表abap_sortorder_tab
- 系统标准类cl_abap_itab_utilities(版本7.52支持)
第一种方式仅适合排序组件较少的情况
示例代码
types:
begin of line,
col1 type i,
col2 type i,
col3 type string,
col4 type string,
end of line,
itab type standard table of line with empty key.
"获取随机数对象
data(rnd) = cl_abap_random_int=>create( seed = + sy-uzeit
min = 1
max = 10 ).
"初始化内表
data(itab) = value itab( for i = 1 until i > 10
(
col1 = rnd->get_next( )
col2 = rnd->get_next( )
col3 = substring( val = sy-abcde off = rnd->get_next( ) - 1 len = 1 )
col4 = substring( val = sy-abcde off = rnd->get_next( ) - 1 len = 1 ) )
).
data(out) = cl_demo_output=>new( ).
out->next_section( `原始内表` ).
out->write( itab ).
out->next_section( `按COL1 COL2正序` ).
"OO排序(本质上是调用内核底层方法)
data(v_index) =
cl_abap_itab_utilities=>virtual_sort(
im_virtual_source = value #(
( source = ref #( itab )
components = value #( ( name = 'COL1' )
( name = 'COL2' ) ) ) ) ).
out->write( '排序结果对应的行索引' ).
out->write( v_index ).
data sorted_tab type itab.
sorted_tab = value #( for idx in v_index ( itab[ idx ] ) ).
"静态排序
data(test_tab) = itab.
sort test_tab stable by col1 col2.
assert sorted_tab = test_tab.
"简单动态排序
data(lt_common) = itab.
data(lv_component1) ='COL1'.
data(lv_component2) = 'COL2'.
sort lt_common by (lv_component1) ascending (lv_component2).
assert sorted_tab = lt_common."这里是相等的
"排序表动态排序
data:lt_sorted_table type abap_sortorder_tab.
lt_sorted_table = value #(
( name = 'COL1' astext = abap_false descending = abap_false )
( name = 'COL2')
).
data(lt_sort_by_table) = itab.
sort lt_sort_by_table by (lt_sorted_table).
assert sorted_tab = lt_sort_by_table.
out->write( '排序结果' ).
out->write( sorted_tab ).
out->display( ).
备注
上述只是简单介绍,更丰富的内容可以参考F1关键字文档
另外本人才疏学浅,如有错误或不完善的地方,请在评论中指出
也可以加QQ 2212332116交流