Application Development and Automation 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: 
Read only

Dynamic Select Query

Former Member
0 Likes
4,854

Hi,

My requirement specifies to fetch certain fields from a certain table at runtime.

The catch is, the fields to be fetched, the table from which fields to be fetched and the where conditions would be known only at runtime and in variables.

So i need something like this :

  v_field1 = 'NAME1'.
v_tablename = 'KNA1'.
v_keyfield = 'KUNNR'.

select single  (v_field1)
   from (v_tablename)
   into v_name1
   where ( v_keyfield = p_kunnr ).

only problem i am facing is in the dynamic where clause , as its not accepting a variable in it. And throws a dump for dynamic declaration.

I have read a lot of discussions on dynamic internal table, but they don't really help.Even using field symbols to create dynamic ranges and assign in where clause doesn't seem to be a solution as i don't know the field names before hand.

Any Suggestions?


5 REPLIES 5
Read only

Former Member
0 Likes
1,398

Hi,

Just try this. Maybe it will help.

DATA: v_field1 TYPE string,
       v_tablename TYPE string,
       v_keyfield TYPE string,
       v_name1 TYPE kna1-name1,
       g_kunnr TYPE kna1-kunnr.

PARAMETERS: p_kunnr LIKE g_kunnr.

v_field1 = 'NAME1'.
v_tablename = 'KNA1'.
v_keyfield = 'KUNNR EQ p_kunnr'. " serve as value of WHERE in your selection

SELECT SINGLE  (v_field1)
    FROM (v_tablename)
    INTO v_name1
    WHERE (v_keyfield).

IF sy-subrc EQ 0.
   WRITE: v_name1.
ENDIF.

Regards,

Jake

Read only

former_member585060
Active Contributor
Read only

Former Member
0 Likes
1,398

HI all,

Thanks, Got the answer in sap help itself...

v_field1 = 'NAME1'.
v_tablename = 'KNA1'.
v_keyfield = 'KUNNR'.

cond_Syntax = v_keyfield && '= p_kunnr'.

select single  (v_field1)
   from (v_tablename)
   into v_name1
   where (cond_syntax).

Read only

0 Likes
1,398

I guess it is same with my suggestion earlier.

Read only

kesavadas_thekkillath
Active Contributor
0 Likes
1,398

If you much confused in building a dyn where clause, the call

RH_DYNAMIC_WHERE_BUILD to build the condition.The table parameter where_clause return it yo you.

after that just call the select query for ex:

SELECT plvar otype objid from hrp1000 into it where ( dyn_cond ). Here dyn_cond is returned from the fm.

Donot forget to catch the exception cx_sy_dynamic_osql_semantics for the dynamic query used.

ex:

TRY .

   SELECT plvar otype objid from hrp1000 into it where ( dyn_cond )

  CATCH cx_sy_dynamic_osql_semantics INTO lref_err.

    lv_msg = lref_err->get_text( ).

ENDTRY.