SQL or PL/SQL : dynamically insert table name in a SQL Statement

Hi,
We have a strange requirement - we need to dynamically use the table names in a SQL Query. E.g:
select * from :table_name
The table_name will be chosen from a list. I have tried this in SQL as well as PL SQL - but, I have been unsuccessul so far.
Can you guys please help me solve this puzzle ?
I hope I have explained my quesion clearly - if not, please do let me know if some more details are necessary.
Regards,
Ramky

The following is the anonymous block that im using in a report in HTMLDB. My problem is Line Number 9. The bind variable contains the chosen table name at
the run time.
Variable "qry_stmt" contains the query to be returned, so that result set for that query will be displayed in the report.
If I hard code the table name(rather that passing it through bind variable) in the
qry_stmt string, Im getting the result sets for that query. But if I pass through
bind variable at run time, its still generating the string correctly( im printing
using a print statement at line number 14). But its returing the following report
error
report error:
ORA-01403: no data found
Please advice/help me in this.....
declare
qry_stmt varchar2(1000);
p_table varchar2(30) := 'EMP';
P_ENAME varchar2(1000);
begin
IF :p2_TABLE_NAMES IS NOT NULL THEN
qry_stmt := 'select * from '||TRIM(:P2_TABLE_NAMES); -- Line Num 9
execute immediate qry_stmt; --into P_ENAME;
ELSE
qry_stmt := 'SELECT 1 FROM dual ';
END IF;
htp.p(qry_stmt);--Line Num 14
return qry_stmt;
EXCEPTION WHEN NO_DATA_FOUND THEN
NULL;
end;
Thanks and Regards,
Ramky

Similar Messages

  • Dynamic table name in native SQL

    Hi,
    How can i use dynamic table name in native SQL?
    My req is to select data from a external database table , but the table name will be only poulated during runtime.
    How can i acheive this?
    Regards,
    Arun.

    It should work OK - see demo below.
    Jonathan
    report zsdn_jc_adbc_test.
    start-of-selection.
      perform demo_lookup.
    form demo_lookup.
      data:
        l_error_msg          type string,
        ls_t001              type t001, "Company
        ls_t003              type t003. "Doc types
      perform dynamic_lookup
        using
          'T001'
        changing
          ls_t001
          l_error_msg.
      write: / l_error_msg.
      perform dynamic_lookup
        using
          'T003'
        changing
          ls_t003
          l_error_msg.
      write: / l_error_msg.
    endform.
    form dynamic_lookup
      using
        i_tabname            type tabname
      changing
        os_data              type any
        o_error_msg          type string.
    * Use ADBC to select data
      data:
        l_mandt_ref          type ref to data,
        l_result_ref         type ref to data,
        l_mandt              type symandt,
        l_tabname            type tabname,
        l_sql_statement      type string,
        lo_cx_root           type ref to cx_root,
        lo_cx_sql            type ref to cx_sql_exception,
        lo_connection        type ref to cl_sql_connection,
        lo_statement         type ref to cl_sql_statement,
        lo_result_set        type ref to cl_sql_result_set.
      clear: os_data, o_error_msg.
      get reference of l_mandt into l_mandt_ref.
      get reference of os_data into l_result_ref.
      l_mandt   = '222'.   "i.e. select from client 222
      l_tabname = i_tabname.
      try.
          lo_connection = cl_sql_connection=>get_connection( ).
          lo_statement  = lo_connection->create_statement( ).
    * Set criteria for select:
          lo_statement->set_param( l_mandt_ref ).
          concatenate
            'select * from' l_tabname
            'where mandt = ?'
            into l_sql_statement separated by space.
    * Execute
          call method lo_statement->execute_query
            exporting
              statement   = l_sql_statement
              hold_cursor = space
            receiving
              result_set  = lo_result_set.
    * Get the data from the resultset.
          lo_result_set->set_param_struct( l_result_ref ).
          while lo_result_set->next( ) > 0.
            write: / os_data.
          endwhile.
    * Tidy up:
          lo_result_set->close( ).
          lo_connection->close( ).
        catch cx_sql_exception into lo_cx_sql.
          o_error_msg = lo_cx_sql->get_text( ).
        catch cx_root into lo_cx_root.
          o_error_msg = lo_cx_root->get_text( ).
      endtry.
    endform.

  • How can i pass a variable instead of a table name in the Select statement.

    Dear all
    how can i pass a variable instead of a table name in a select statement ?
    Example :-
    Begin
    P_get_procedure_tname (aap_name,otable_name);--It will take an application name and will return a table name
    Select col1 into ocol1
    from  ---- here i want to pass the variable OTABLE_NAME
    End;How can i pass this ?

    Hi,
    You can use dynamic sql.
    EXECUTE IMMEDIATE 'SELECT COL1 INTO ' || OCOL1 || ' FROM " || OTABLE_NAME;
    {code}
    cheers
    VT                                                                                                                                                                                                                                                                                                   

  • Dynamic table name in native sql query

    Can i pass a dynamic table name in this query ---
                EXEC SQL PERFORMING APPEND_MTO.
                  SELECT          
                               LTOG_QUANTITY_TYPE,
                               FCONO,
                              WBSELEMENT,
                             PROJECT
                  INTO   :IMTO
                  FROM  RWORKS.MTO_ISO_V2
                  WHERE LTOD_DATE > TO_DATE(:MAXD,'YYYYMMDDHH24MISS')
                ENDEXEC.
    How can i pass this table name RWORKS.MTO_ISO_V2  dynamically in the query
    Edited by: Madhukar Shetty on Nov 26, 2009 2:40 PM

    Can i pass a dynamic table name in this query ---
                EXEC SQL PERFORMING APPEND_MTO.
                  SELECT          
                               LTOG_QUANTITY_TYPE,
                               FCONO,
                              WBSELEMENT,
                             PROJECT
                  INTO   :IMTO
                  FROM  RWORKS.MTO_ISO_V2
                  WHERE LTOD_DATE > TO_DATE(:MAXD,'YYYYMMDDHH24MISS')
                ENDEXEC.
    How can i pass this table name RWORKS.MTO_ISO_V2  dynamically in the query
    Edited by: Madhukar Shetty on Nov 26, 2009 2:40 PM

  • Parse SQL: How to extract column names, table names from a SQL query

    Hi all,
    I have a requirement wherein a SQL query will be given in a text file.
    The text file has to be read (probably using text_io package), the SQL query needs to be parsed and the column names, table names and where clauses have to be extracted and inserted into separate tables.
    Is there a way to do it using PL/SQL ?
    Is there a PL/SQL script available to parse and extract column names, table names etc ?
    Pls help.
    Regards,
    Sam

    I think I jumped to conclusion too early saying it is completely possible and straight forward. But after reading through your post for one more time I realised you are not interested only in the column_names, also the table_names and the predicates .
    >
    SQL query needs to be parsed and the column names
    >
    The above is possible and straight forward using the dbms_sql package.
    I am pasting the same information as I did in the other forum.
    Check this link and search for Example 8 and .
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm#sthref6136
    Also check the working example from asktom
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1035431863958
    >
    table names and where clauses have to be extracted
    >
    Now this is the tricky bit. You can extract the list of tables by getting the sql_id from v$sql and joining it with v$sql_plan. But sometimes you may not get all the results because the optimizer may choose to refine your query (check this link)
    http://optimizermagic.blogspot.com/2008/06/why-are-some-of-tables-in-my-query.html
    and you can get the predicate information from the same table v$sql_plan but I will leave that area for you to do some R&D.
    Regards
    Raj
    Edited by: R.Subramanian on Dec 10, 2008 3:14 AM

  • Providing table name dynamicaaly in SQL

    Hi,
    how can provide table name dynamically in an SQL query. no help of PL/SQL is possible in the scenario.
    I am trying many possiblities but without any success. any1 knowling please let me know.
    Regards,
    Prash

    well, depending on the requirments you can use XML to some extent:
    SQL> var name varchar2(20);
    SQL> exec :name:='scott.emp';
    PL/SQL procedure successfully completed.
    SQL> select 'Table "'||:name||'" has ' ||
      2         extractvalue(dbms_xmlgen.getXMLType('select count(*) cnt from '||:name),
      3                      '//CNT') || ' rows'
      4    from dual;
    'TABLE"'||:NAME||'"HAS'||EXTRACTVALUE(DBMS_XMLGEN.GETXMLTYPE('SELECTCOUNT(*)CNTF
    Table "scott.emp" has 14 rows
    SQL> exec :name:='all_tables';
    PL/SQL procedure successfully completed.
    SQL> select 'Table "'||:name||'" has ' ||
      2         extractvalue(dbms_xmlgen.getXMLType('select count(*) cnt from '||:name),
      3                      '//CNT') || ' rows'
      4    from dual;
    'TABLE"'||:NAME||'"HAS'||EXTRACTVALUE(DBMS_XMLGEN.GETXMLTYPE('SELECTCOUNT(*)CNTF
    Table "all_tables" has 1622 rows

  • SQL query to return list of table names.

    Hi all,
    I'm looking for a query that will return a list of the table names that exist in my Microsoft Access database.
    Any ideas?

    http://forum.java.sun.com/thread.jsp?forum=31&thread=348287
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DatabaseMetaData.html
    I would suggest you strat to use the search at the upper right.
    You can leave it blank and the advanced search will appear.
    You can then select the specific areas you want to search.

  • Using variable as table name in pl/sql query - Is possible?

    I am relatively new to PL/SQL and I am trying to create a function that accepts a table name and a rowid as arguments and returns a comma-delimited record string of the values of the table/rowid being passed. The problem is , I cannot code a select stmt as follows
    SELECT * FROM v_table_name
    WHERE rowid = v_row_id
    in PL/SQL. There must be a easy way to approach this.
    Thanks for any and all advice.
    GC

    I don't understand the use of the concat symbol along with the commas and field namesYou just need (if you really need it) to create variable which contains you column separated by comma:
    Simple example (in the second case separate variables are used to create
    the list of columns):
    SQL> declare
      2   rc sys_refcursor;
      3   cols varchar2(200) := 'ename, empno, sal';
      4   tab varchar2(30) := 'emp';
      5  begin
      6   open rc for 'select ' || cols || ' from ' || tab;
      7   close rc;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2   rc sys_refcursor;
      3 
      4   ename_col varchar2(10) := 'ename';
      5 
      6   empno_col varchar2(10) := 'empno';
      7 
      8   sal_col varchar2(10) := 'sal';
      9 
    10   tab varchar2(30) := 'emp';
    11 
    12  begin
    13 
    14   open rc for 'select ' || ename_col || ',' || empno_col || ',' || sal_col ||
    15   ' from ' || tab;
    16 
    17   close rc;
    18  end;
    19  /
    PL/SQL procedure successfully completed.Rgds.

  • Dynamic DB table name in insert statement

    In the following command i was able to build <dyn_table> dynamically but how do we do that for <dyn_wa>. table name should be populated dynamically here.
    for ex: pa0001, pa0002, .... and I have these names in an IT table
    INSERT  <dyn_wa> FROM TABLE <dyn_table>
                              ACCEPTING DUPLICATE KEYS.
    Pls help...Thanks

    Take it as charater type.
    This code works for me.
    TABLES : ztest123.
    DATA : tab_name(10) TYPE c.
    tab_name = 'ZTEST123'.
    DATA : wa LIKE ztest123.
    wa-name = 'Mahesh'.
    INSERT (tab_name) FROM wa.
    Thanks
    Mahesh

  • Use a variable as a table name with NATIVE SQL

    Hi all,
    I am trying to execute a SELECT statement in order to fetch data from an external Oracle DB table to SAP with the following instructions:
    EXEC SQL.
      SELECT cityfrom, cityto
             INTO STRUCTURE :wa
             FROM spfli
             WHERE mandt  = :sy-mandt AND
                   carrid = :p_carrid AND connid = :p_connid
    ENDEXEC.
    However, I need to indicate the external table name from a variable instead of the solution above. That is, declaring a variable and store the name of the table (e.q. spfli) in it. The resulting ABAP code would be something like:
    EXEC SQL.
      SELECT cityfrom, cityto
             INTO STRUCTURE :wa
             FROM <VARIABLE>
             WHERE mandt  = :sy-mandt AND
                   carrid = :p_carrid AND connid = :p_connid
    ENDEXEC.
    Does anybody know if is possible to do that?
    If not, is there any other solution?
    Thank you in advance

    Yes, as Suhas said, you could use the ADBC API and his class CL_SQL_CONNECTION to achieve this...
    Here is a small example:
    PARAMETERS: p_carrid TYPE spfli-carrid,
                               p_connid TYPE spfli-connid.
    DATA:
      l_con_ref      TYPE REF TO cl_sql_connection,
      l_stmt         TYPE string,
      l_stmt_ref     TYPE REF TO cl_sql_statement,
      l_dref         TYPE REF TO data,
      l_res_ref      TYPE REF TO cl_sql_result_set,
      l_col1         TYPE spfli-carrid,
      l_col2         TYPE spfli-connid,
      l_wa           TYPE spfli.
    CONSTANTS:
      c_tabname  TYPE string VALUE 'SPFLI'.
    * Create the connecction object
    CREATE OBJECT l_con_ref.
    * Create the SQL statement object
    CONCATENATE 'select * from' c_tabname 'where carrid = ? and connid = ?'
           INTO l_stmt SEPARATED BY space.                           "#EC NOTEXT
    l_stmt_ref = l_con_ref->create_statement( ).
    * Bind input variables
    GET REFERENCE OF l_col1 INTO l_dref.
    l_stmt_ref->set_param( l_dref ).
    GET REFERENCE OF l_col2 INTO l_dref.
    l_stmt_ref->set_param( l_dref ).
    * Set the input value and execute the query
    l_col1 = p_carrid.
    l_col2 = p_connid.
    l_res_ref = l_stmt_ref->execute_query( l_stmt ).
    * Set output structure
    GET REFERENCE OF l_wa INTO l_dref.
    l_res_ref->set_param_struct( l_dref ).
    * Show result
    WHILE l_res_ref->next( ) > 0.
      WRITE: / 'Result:', l_wa-carrid, l_wa-connid.
    ENDWHILE.
    * Close the result set object
    l_res_ref->close( ).
    Otherwise you can also use the FM DB_EXECUTE_SQL...
    Kr,
    m.

  • Dynamic physical table name vs. Cache

    Hello, Experts!
    I'm facing quite an interesting problem. I have two physical tables with the same structure but with a different data. Requirement is to show same reports with one or another table. Idea is to have dynamically changed physical table name with session variable usage. Session variable can be change in UI so it was working until cache was turned on. When cache is turned on logical statements sent to OBI backend are the same even for different values of session variable that stores physical table name. Once cache is populated every users will get values from cache. This is possible source of discrepancy because some users might run reports with tableA values and some with tableB values.
    Are there any options to set OBI to use data related to proper physical table name (i.e. accordingly to session variable value)? Model clone is not an option because it will be way to hard and complex to maintain both, beside same reports need to work sometimes with one table name and sometimes with other...
    PS. Cache is set to be common for all users.
    Lucas

    thank you, I've found another way to make it running. In fact there are two ways of doing it: filter LTS and have all data filtered from single table with session variable or use fragmentation content also with session variable.
    Now tricky part is to set variable from UI, currently I'm using issue raw sql: call NQSSetSessionValue( 'String SV_SIGNOFF=aaa;' ) but I have to figure out how to change session non system variable value without need of administrator user rights.
    There is GoURL method, but it's not working...
    2. Add In ORACLE_HOME/bifoundation/web/display/authenticationschemas.xml
    <RequestVariable source="url" type="informational" nameInSource="lang"
    biVariableName="NQ_SESSION.LOCALE" />
    inside the top <AuthenticationSchemaGroup> </AuthenticationSchemaGroup> tag

  • Dynamically assigning table name in select statement

    how can i assign the table name dynamically in Select statement?
    i tried following code
    create or replace procedure proc1
    as
    x varchar2(100);
    y varchar2(10);
    begin
    x='UNIT_MASTER';
    execute immediate 'select unit_code into y from x where
    rownum=1';
    dbms_output.put_line(y);
    end;
    the procedure is created but when i execute the procedure the
    error is shown in the execute immediate statement

    Do the following :
    Create or replace procedure pro1 as
    x varchar2(100);
    y varchar2(10);
    begin
    x := 'UNIT_MASTER';
    EXECUTE IMMEDIATE 'select unit_code from '||x||' where rownum
    = 1' INTO y;
    dbms_output.put_line(y);

  • How to dynamic set table names

    In our application, the table name can be set at runtime by the customer. So is there a way in Toplink JPA to set table name at runtime (thru annotation or orm.xml) or programatically? Thanks.

    Our application will host several domains at once. Each domain will get its own set of database tables for each module it uses. We keep them seperate by using a unique prefix. An example would be domainA.com's blog post table would be called domainA_blogPost, while domainB.com's will be domainB_blogPost. Both tables are the same, except for the name. The name needs to be specified at runtime since the central service controller tells the rest of the application which domain it is servicing and thus which set of tables to use. We will be adding domains dynamically all the time and we can't afford to create new entity sets and recompile the back end for every domain we add. I have been looking at the API and wonder if this is as simple as implementing a solution in our application, or am I going to have to tweek the implementation of toplink?

  • Dynamically pass Table name, Column Name and rownum to function

    Hi Guys
    I wanted to pass the table name, column name and rownum to function and get the relevant value for it. Please guide me to achieve this task
    Thanking You
    Regards
    Lakmal

    Thanks,
    Here is my test function
    CREATE or replace FUNCTION GET_COLUMN_VALUE (tab_name VARCHAR2,column_name VARCHAR2) RETURN varchar2 AS
    strsql varchar2 (500);
    ColVal varchar2;
    BEGIN
    strsql:='select '||column_name||' from '||tab_name|| ' Where rownum = 1' ;
    EXECUTE IMMEDIATE strsql into ColVal;
    RETURN ColVal ;
    END;
    Message was edited by:
    Lakmal Marasinghe

  • How to use a table name in the select statement using a variable?

    Hi Everybody,
                       I got a internal table which has a field or a variable that gets me some tables names. Now I need to retrieve the data from all these tables in that field dynamically at runtime. So could you suggest me a way out to use the select query which uses this variable as a table ?
    Regards,
    Mallik.

    Hi all,
    Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
    for ex : select * from (tab_name) where....?
    Can we do inner join on such select statements? If so how?
    Thanks & Regards,
    Mallik.

Maybe you are looking for