It is possible to run SAP queries in background and to create a query output as a file in application server.
Follow below steps to implement the same.
1) As per OSS note 537735 - SAP Query: save to file in the background activate the enhancement SQUE0001 using the t.code SMOD.
2) Once the above enhancement is activated, it will add a new radio button option with text "Private file" under the output format block of the Query selection screen.
Image may be NSFW.
Clik here to view.
3) Create a Z table and maintain the sever filepath in which the files to be stored in application server.
Image may be NSFW.
Clik here to view.
4) Go to the function exit "EXIT_RSAQEXCE_001" and do your customized coding in the INCLUDE ZXQUEU01.
*Data Declaration.
DATA : c_lv_buf TYPE string,
c_lv_line TYPE string,
c_lv_filepath TYPE localfile,
c_lv_query TYPE aqs_quname.
*Field symbols
FIELD-SYMBOLS : <fs_record>TYPEANY,
<fs_comp>TYPEANY.
*Get a Query name from the program
CALLFUNCTION'RSAQ_DECODE_REPORT_NAME'
EXPORTING
reportname = program
IMPORTING
query = c_lv_query
EXCEPTIONS
no_query_report = 1
OTHERS = 2.
IF sy-subrc <>0.
MESSAGEID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
*Select the filepath from ZBSD_T0246 table based
*on the query name and variant.
SELECTSINGLE filepath
FROM zbsd_t0246
INTO c_lv_filepath
WHERE query = c_lv_query
AND qvariant = syst-slset.
IF sy-subrc = 0.
*Open application server file.
OPENDATASET c_lv_filepath FOROUTPUTINTEXTMODE ENCODING DEFAULT.
IF sy-subrc = 0.
CLEAR c_lv_line.
*Create header of the file
LOOPAT listdesc.
CONCATENATE c_lv_line listdesc-fcol ';'INTO c_lv_line.
ENDLOOP.
TRANSFER c_lv_line TO c_lv_filepath.
CLEAR c_lv_line.
*Transfer the data to the file
LOOPAT datatab ASSIGNING<fs_record>.
DO.
ASSIGN COMPONENT sy-index OFSTRUCTURE<fs_record>TO<fs_comp>.
IF sy-subrc <>0.
EXIT.
ENDIF.
c_lv_buf = <fs_comp>.
IF sy-index = 1.
c_lv_line = c_lv_buf.
ELSE.
CONCATENATE c_lv_line c_lv_buf INTO c_lv_line SEPARATEDBY';'.
ENDIF.
CLEAR c_lv_buf.
ENDDO.
TRANSFER c_lv_line TO c_lv_filepath.
CLEAR c_lv_line.
ENDLOOP.
*Close the file once the datas are transfered.
CLOSEDATASET c_lv_filepath.
IF sy-subrc = 0.
*File created in path &1
MESSAGE s483(zbsd_0001)WITH c_lv_filepath.
ENDIF.
ENDIF.
ELSE.
*File path not maintained in table ZBSD_T0246
MESSAGE e484(zbsd_0001).
ENDIF.
5) Run the query in the background and the files will be created in the application server path maintained in Z-table.