hanacdshana-sql-scriptamdp

AMDP Unable to use UNION ALL with local tables - sql syntax error: incorrect syntax near "UNION


I have a requirement to create a table for 2 columns: first date of the month and the last day of the respective month. The last day calculation works correctly but I am not able to merge the results to a table. When I use UNION ALL it gives an error: sql syntax error: incorrect syntax near "UNION

  CLASS zcl_sou_amdp_datetesting DEFINITION
  PUBLIC
  FINAL
  CREATE PUBLIC .
  PUBLIC SECTION.
  INTERFACES: IF_AMDP_MARKER_HDB.
  TYPES:BEGIN OF ty_date_range,
          first_date TYPE string,
          last_day TYPE string,
        END OF TY_DATE_RANGE.
  TYPES tt_date_range_type TYPE STANDARD TABLE OF TY_DATE_RANGE WITH EMPTY KEY.

  CLASS-METHODS get_last_days_in_range
      IMPORTING VALUE(p_start_date) TYPE DATS
                VALUE(p_end_date) TYPE DATS
      EXPORTING VALUE(result) TYPE tt_date_range_type.


   METHOD get_last_days_in_range
    BY DATABASE PROCEDURE FOR HDB
    LANGUAGE SQLSCRIPT
    OPTIONS READ-ONLY.

    DECLARE current_month DATE;
    DECLARE last_day_of_month DATE;


    result = SELECT '' AS first_date, '' AS last_day FROM dummy WHERE 1 = 0; -- Initialize empty result table

    -- Initialize current_month to the first day of the starting month
    current_month = TO_DATE(TO_VARCHAR(:p_start_date, 'YYYYMM') || '01', 'YYYYMMDD');

    WHILE current_month <= :p_end_date DO
        -- Calculate the last day of the current month
        last_day_of_month = LAST_DAY(current_month);

   
        -- Add the month and last Sunday to the result table
    
--The ERROR OCCURS HERE!!!!
     result = result UNION ALL
                 SELECT TO_VARCHAR(:current_month, 'YYYY-MM') AS month,
                        TO_VARCHAR(:last_day_of_month, 'YYYY-MM-DD') AS last_day
                 FROM dummy;

        -- Move to the next month
        current_month = ADD_MONTHS(current_month, 1);
    END WHILE;

  ENDMETHOD.

Solution

  • This is not proper SQL syntax for UNION ALL

    try this:

      result = SELECT first_date, last_day 
                   FROM :result
               UNION ALL  
               SELECT TO_VARCHAR(:current_month, 'YYYY-MM') AS month,
                      TO_VARCHAR(:last_day_of_month, 'YYYY-MM-DD') AS last_day
                   FROM dummy;