Nested subquery in FOR ALL ENTRIES

Viewed 5876

Consultant sent me this code example, here is something he expects to get

SELECT m1~vbeln_im m1~vbelp_im m1~mblnr smbln      
    INTO CORRESPONDING FIELDS OF TABLE lt_mseg
    FROM mseg AS m1
    INNER JOIN mseg AS m2 ON m1~mblnr = m2~smbln
                         AND m1~mjahr = m2~sjahr
                         AND m1~zeile = m2~smblp
    FOR ALL ENTRIES IN lt_vbfa
    WHERE 
      AND m2~bwart = '102'
      AND 0 = ( select SUM( ( CASE
        when SHKZG = 'S' THEN 1
        when SHKZG = 'H' THEN -1
        else 0
        END ) *MENGE ) MENGE
        into lt_mseg-summ
        from mseg
        where
        VBELN_IM = m1~vbeln_im
        and VBELP_IM = m1~vbelp_im
        ).

The problem is I don't see how that should work in current syntax. I think about deriving internal select and using it as condition to main one, but is there a proper way to write this nested construction?

As i get it, if nested statement = 0, then main query executes. The problem here is the case inside nested statement. Is it even possible in ABAP? And in my opinion this check could be used outside from main SQL query.

Any suggestions are welcome.

2 Answers

This is probably what you need, it works at least since ABAP 750.

SELECT vbeln UP TO 100 ROWS
 FROM vbfa
 INTO TABLE @DATA(lt_vbfa).

DATA(rt_vbeln) = VALUE range_vbeln_va_tab( FOR GROUPS val OF <line> IN lt_vbfa GROUP BY ( low = <line>-vbeln ) WITHOUT MEMBERS ( sign = 'I' option = 'EQ' low = val-low ) ).

SELECT m1~vbeln_im, m1~vbelp_im, m1~mblnr, m2~smbln
  INTO TABLE @DATA(lt_mseg)
  FROM mseg AS m1
  JOIN mseg AS m2
    ON m1~mblnr = m2~smbln
   AND m1~mjahr = m2~sjahr
   AND m1~zeile = m2~smblp
 WHERE m2~bwart = '102'
   AND m1~vbeln_im IN ( SELECT vbelv FROM vbfa WHERE vbelv IN @rt_vbeln  )
 GROUP BY m1~vbeln_im, m1~vbelp_im, m1~mblnr, m2~smbln
HAVING SUM( CASE  m1~shkzg WHEN 'H' THEN 1  WHEN 'S' THEN -1 ELSE 0 END * m1~menge ) = 0.

Yes, aggregating and FOR ALL ENTRIES is impossible in one SELECT, but you can trick the system with range and subquery. Also you don't need three joins for summarizing reversed docs, your SUM subquery is redundant here.

If you need to select documents not only by delivery number but also by position this will be more complicated for sure.

Related