SELECT statement can also be used in a dynamic way. The list of fields, the actual
WHERE clause and the table name can all be defined at runtime. This is not very common and maybe even difficult to read (for your fellow developers) but it is a powerful option that you do need to know about. If not to implement yourself, this article can clarify how dynamic selects work.
The following example shows a simple setup where the list of fields, the where clause and the table name are all set as parameter values - before the
SELECT statement is called:
data: lv_fields type string, lv_clause type string, lv_tablename type string, lt_results TYPE TABLE OF matnr. lv_tablename = 'MARA'. lv_fields = 'MATNR'. lv_clause = 'MTART = ''FERT'' AND MBRSH = ''A'''. SELECT (lv_fields) FROM (lv_tablename) INTO TABLE lt_results UP TO 20 rows WHERE (lv_clause).
A few notes: this whole setup only makes sense if the actual results table is also flexible. SAP has e great example in their help system which shows how such table can be defined and prepared as a
FIELD-SYMBOLS variabele. Also: the example shows string fields for the field list and the where clause. These can also be internal tables, which can make composing the where clause a bit easier. A coding example:
data: lv_snnn_table(4) type c, lv_select_clause type string. field-symbols: <fs_table_snnn> type standard table. * Prepare the logic according to the selection you need case what_i_need. when 'ZORBA' lv_snnn_table = 'S920'. lv_select_clause = 'VRSIO = ''000'' ' && 'MATNR IN GR_MATNR'. when 'ZEBRO'. lv_snnn_table = 'S920'. *... more variations endcase. select * into corresponding fields of table <fs_table_snnn> from (lv_snnn_table) where (lv_select_clause).
When accessing the information selected here, you should cater for the fact that fields are not known beforehand, so addressing a field like
<fs_table_snnn>-VRSIO will not compile. Have a look at the next bit of coding:
field-symbols: <fs_wa_snnn> type any, <VERSION> type any, <MATERIAL> type matnr. * Compose a select clause - for the LOOP lv_select_clause = 'MATNR = '' && lv_my_material && '' and PROCESSED = abap_false'. LOOP AT <fs_table_snnn> ASSIGNING <fs_wa_snnn> WHERE (lv_select_clause). ASSIGN COMPONENT 'VRSIO' OF STRUCTURE <fs_wa_snnn> TO <VERSION>. ASSIGN COMPONENT 'MATNR' OF STRUCTURE <fs_wa_snnn> TO <MATERIAL>. IF <MATERIAL> IS ASSIGNED. * Do your thing here ENDIF. ENDLOOP.
In the example a few field-symbols access methods are shown. Loop at assigning and assign component are the keys to accessing you data.