Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Dynamic Select Query with dynamically determined fields and table

Former Member
0 Kudos

Hello Experts,

I have got a requirement in which I have to fetch the table name from table TAB1 and fields from table TAB2.

I am not sure which all fields will be present in TAB2 and hence I cannot do a Select * on TAB1. I have to select only those fields which are mentioned in TAB2.

Can anyone suggest which logic with some code so that this requirement can be fulfilled.

Thanks

Jaydeep

1 ACCEPTED SOLUTION

Former Member
0 Kudos

hi jaydeep,

do you mean to say that TAB1 has table names and TAB2 has corresponding fields?

Your requirement is to make a select query based on the parameter of table name from TAB1 isnt't?

4 REPLIES 4

Former Member
0 Kudos

Hello,

Have a look at this:

DATA: itab TYPE STANDARD TABLE OF spfli,
            wa LIKE LINE OF itab.


DATA: line(72) TYPE c,

list LIKE TABLE OF line(72).

parameters: p_table(30) type c default 'T001'.

line = ' CITYFROM CITYTO '.

APPEND line TO list.

SELECT DISTINCT (list)
INTO CORRESPONDING FIELDS OF TABLE (p_table)
FROM spfli.

IF sy-subrc EQ 0.

LOOP AT itab INTO wa.
WRITE: / wa-cityfrom, wa-cityto.
ENDLOOP.

ENDIF.

(most parts copied from How can we give dynamic table name in select statement?)

br,

Nikolaus

Former Member
0 Kudos

hi jaydeep,

do you mean to say that TAB1 has table names and TAB2 has corresponding fields?

Your requirement is to make a select query based on the parameter of table name from TAB1 isnt't?

0 Kudos

Yes Abdul. First line of your statement is right.

I will have to pick up only those fields from table which will be mentioned in TAB2.

0 Kudos

I got the way out guys with help of Nikolaus Harrich.

  DATA: line(72) TYPE c,

        list LIKE TABLE OF line(72).

*ITAB2

  LOOP AT gt_fields INTO gs_fields.

    MOVE gs_fields-field_name TO line.

    APPEND line TO list.

  ENDLOOP.

*ITAB1

  READ TABLE gt_table INTO gs_table INDEX 1.

  IF sy-subrc = 0.

    IF gs_table-where2 IS NOT INITIAL.

      MOVE gs_table-where2 TO line.

    ENDIF.

    IF gs_table-where3 IS NOT INITIAL.

      CONCATENATE line 'AND' INTO line SEPARATED BY space.

      CONCATENATE line gs_table-where3 INTO line SEPARATED BY space.

    ENDIF.

  ENDIF.

*  SELECT data FROM table.

  SELECT (list)

        INTO CORRESPONDING FIELDS OF TABLE <dyn_table>

        FROM (p_table)

        WHERE (line).

Thanks Nikolaus !