ABAP: SQL 多值查询

基础查数据

问题举例:例如查物料类型为ZFRT、ZROH和ZRSA的物料编码。

1、直接查询,三种不同类型的物料类型是或的关系。

  SELECT DISTINCT ma~matnr  ma~mtart
   FROM mara AS ma
  INNER JOIN mbewh AS mb
    ON ma~matnr = mb~matnr
  INTO CORRESPONDING FIELDS OF TABLE gt_tab
  WHERE ma~mtart EQ 'ZFRT' OR
        ma~mtart EQ 'ZROH' OR
        ma~mtart EQ 'ZRSA'.

2、如果对1进行优化,三种物料类型放在列表项中,使用关键字IN,这样查询等价于1.

  SELECT DISTINCT ma~matnr  ma~mtart
   FROM mara AS ma
  INNER JOIN mbewh AS mb
    ON ma~matnr = mb~matnr
  INTO CORRESPONDING FIELDS OF TABLE gt_tab
  WHERE ma~mtart IN ( 'ZFRT' , 'ZROH', 'ZRSA' ).

3、定义区间函数,RANGE 内表

https://www.cnblogs.com/buduzhiren/p/13131483.html

SAP ABAP编程 Ranges用法_m15188153014的博客-CSDN博客

定义区间结构:

 TYPES: BEGIN OF ty_sign,
           sign   TYPE sign,
           option TYPE option,
           low    TYPE mtart,
           high   TYPE mtart,
         END OF ty_sign.           "定义区间结构


(1)直接赋值,不建议这种直接堆叠赋值方式,代码量比较多。


  DATA: lt_mtart TYPE TABLE OF ty_sign WITH HEADER LINE.  "定义区间表
  
  lt_mtart-sign = 'I'.    "赋值
  lt_mtart-option = 'EQ'.
  lt_mtart-low = 'ZFRT'.
  APPEND lt_mtart TO lt_mtart.
  lt_mtart-sign = 'I'.
  lt_mtart-option = 'EQ'.
  lt_mtart-low = 'ZROH'.
  APPEND lt_mtart TO lt_mtart.
  lt_mtart-sign = 'I'.
  lt_mtart-option = 'EQ'.
  lt_mtart-low = 'ZRSA'.
  APPEND lt_mtart TO lt_mtart.
  CLEAR lt_mtart.

(2) 优化:使用VALUE#() 进行赋值,建议这种方式,代码量会大大减少。

  DATA: lt_mtart TYPE TABLE OF ty_sign .

 lt_mtart = VALUE #( sign = 'I' option = 'EQ'  ( low = 'ZFRT' high = '' )
                                               ( low = 'ZROH' high = '' )
                                               ( low = 'ZRSA' high = '' )
                    ).

(3)或者用APPEND VALUE#() TO ITAB. 与(2)二者等同。

DATA: lt_mtart TYPE TABLE OF ty_sign . 

APPEND  VALUE #( sign = 'I' option = 'EQ'  low = 'ZFRT' high = '' ) TO lt_mtart.
APPEND  VALUE #( sign = 'I' option = 'EQ'  low = 'ZROH' high = '' ) TO lt_mtart.
APPEND  VALUE #( sign = 'I' option = 'EQ'  low = 'ZRSA' high = '' ) TO lt_mtart.

ABAP: SQL 多值查询_第1张图片

对RANGE内表 赋值完成后的,以上三种方式的查询语句均相同。

  SELECT DISTINCT ma~matnr  ma~mtart
  FROM mara AS ma
  INNER JOIN mbewh AS mb
    ON ma~matnr = mb~matnr
  INTO CORRESPONDING FIELDS OF TABLE gt_tab
  WHERE ma~mtart IN lt_mtart.

总结: 1、如果是多个字符,使用第二种,IN +列表项,查询最为简洁;

2、如果有多个区间,可以使用VALUE#()方式进行赋值。

你可能感兴趣的:(ABAP,mysql,数据库)