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

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.

  • 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

  • Multi Provider Table name

    Hi ,
    How can i get multi-provider table name.
    Regards
    Rajini

    Hi,
    MultiProvider doesn't store any data physically. You can view data in it with tcode LISTCUBE.
    Can you please explain more what you are trying.
    Reg
    Pra

  • 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

  • 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 table names without dynamic sql?

    I am trying to figure out a way to use table names as variables without using dynamic sql.
    So for instance, I have...
    execute immediate 'INSERT INTO '||vTABLE||' VALUES ('test')';
    and
    execute immediate 'INSERT INTO TABLE1 SELECT * FROM '||vTable;
    Is there any other way to do these without the dynamic sql in Oracle 10.2g?

    I am trying to figure out a way to use table names as variables without using dynamic sql. Well I guess it makes a change from perpetual motion machines or cold fusion.
    Are you doing this as a purely academic exercise or do you have something against dynamic SQL?
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • 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.

  • How to use a variable as a table name in PL/SQL?

    Hello all.
    I was given one day to wrote a piece of PL/SQL code to do a query. That is,
    First select two columns from one table and use them to build another table's name, then
         join the two tables. I'm not sure if variables can be used in the select list, if possible,
         how to reference them?
    -- My code is
    DECLARE
         tablename varchar2(40);
         CURSOR c1 IS
    select a.sourcesystemcode, a.adminorganizationno from cdb1.organization_mapping a
    where exists( select 1 from cdb1.organization_mapping b where
    a.cdborganizationno = b.cdborganizationno and a.adminorganizationno != b.adminorganizationno)
    order by a.cdborganizationno,a.adminorganizationno;
         v_src_sys_cod cdb1.organization_mapping.sourcesystemcode%TYPE;
         v_adm_org_no cdb1.organization_mapping.adminorganizationno%TYPE;
    BEGIN
    OPEN c1;
    LOOP
    FETCH c1 INTO v_src_sys_cod, v_adm_org_no;
    EXIT WHEN c1%NOTFOUND;
    tablename := 'ODS1.SRC_' || v_src_sys_cod || v_adm_org_no || 'ACTORG_CURR';
    select c.cdborganizationno, c.sourcesystemcode, c.adminorganizationno, c.sourceorganizationno, d.ibkcde, d.orgnam
    from cdb1.organization_mapping c inner join tablename d on c.sourceorganizationno = d.orgidt;
    END LOOP;
    CLOSE c1;
    END;
    The error message says "... the table or view does not exist... line 18, column 66..."
    It says the variable "tablename" wasn't build or build incorrectly.
    Please give the solution.

    If the TABLEs being queried are already known, and it is just a matter of which one to query, perhaps you can CREATE a VIEW that uses all the TABLEs with a UNION ALL, and include an identifier COLUMN.
    CREATE VIEW SRC_ALL_ACTORG_CURR
    AS
    SELECT 'aa' Name, ibkcde, orgnam FROM SRC_aa_ACTORG_CURR UNION ALL
    SELECT 'bb' Name, ibkcde, orgnam FROM SRC_bb_ACTORG_CURR UNION ALL
    SELECT 'cc' Name, ibkcde, orgnam FROM SRC_cc_ACTORG_CURR UNION ALL
    SELECT 'dd' Name, ibkcde, orgnam FROM SRC_dd_ACTORG_CURR UNION ALL
    SELECT 'ee' Name, ibkcde, orgnam FROM SRC_ee_ACTORG_CURR;
    Then, in you query:
    select c.cdborganizationno, c.sourcesystemcode, c.adminorganizationno, c.sourceorganizationno, d.ibkcde, d.orgnam
    from cdb1.organization_mapping c inner join SRC_ALL_ACTORG_CURR d on c.sourceorganizationno = d.orgidt and d.Name = v_src_sys_cod || v_adm_org_no;

  • Sql statement for a table name with a space in between

    Hi,
    I just noticed that one of my tables for Access is consisted of two word. It is called "CURRENT CPL". How would I put this table name into an sql statement. When I did what I normally do, it only reads the CURRENT and thinks that's the table name.
    Thanks
    Feng

    I just noticed that one of my tables for Access is
    consisted of two word. It is called "CURRENT CPL".
    How would I put this table name into an sql
    statement. When I did what I normally do, it only
    reads the CURRENT and thinks that's the table name.That is called a quoted identifier. The SQL (not java) for this would look like this....
    select "my field" from "CURRENT CPL"
    The double quote is the correct character to use. Note that quoted identifiers are case sensitive, normal SQL is not.

  • Bug With Quoted Table Names?

    I think I've encountered a bug in Oracle 9.2.0.1.0. If I create table with its name in quotes, I can't access it again unless I also use the name in quotes. But, in DBA_OBJECTS the table's name shows up without quotes.
    For example:
    CREATE TABLE "avalys" (test number);
    SELECT * FROM "avalys"; --Works
    SELECT * FROM avalys; --Doesn't
    Any idea what the problem could be? Am I just not supposed to quote table names (I need to, because one of our tables is a reserved word, and unfortunately we can't change the name of the table).

    When you put quotes around a table name, you're telling Oracle to store the table name in a case-sensitive fashion, rather than the default case-insensitive fashion. When you use a non-quoted identifier, Oracle automatically upcases the whole thing and tries to resolve the name. Thus, you can do the following (not the uppercase table name in quotes)
    SQL> create table "FOO" (n1 number);
    Table created.
    SQL> select * from foo;
    no rows selected
    because "select * from foo" implicitly upcases foo. If you declare a table with some lowercase letters, i.e.
    SQL> create table "FOo" (n1 number);
    Table created.
    you'll only be able to access it with the same partially lowercase string, i.e.
    SQL> select * from "FOo"
    no rows selected
    Justin

  • Getting table name from a query

    Hi, I'm trying to get the table name from my sql query
    My code is as follows;
    ResultSetMetaData metadata = rs.getMetaData();
    for (int i = 1; i < metadata.getColumnCount(); i++)
    System.out.println(metadata.getTableName(i));
    I just get a blank output. Yet my sql query executes and I can pull down the records, and grab the column names from the result sets.
    Any ideas on how I can get the table name for the columns. The reason being is on one of my querys I'm using join statements and i need to retrieve the table name for the column i'm displaying, as some tables have similar column names.
    Thanks in advance.

    Hi,
    What db are you using?
    I also get a blank output with ResultSetMetaData.getTableName because Oracle doesn't implement this method.
    Why do you not know the table name anyway?
    regards
    Nick

  • PreparedStatement and table name

    Hi,
    I have the following snippet, and it seems that I cannot use the function
    prepStmt.setString(1, TABLE_NAME);
    to set the table name for the SQL prepared statement. What function should I use?
    Thanks,
    Rocky
    final String[] TABLE_NAME =
    "Borrower",
    "Loan",
    "Depositor",
    "Account",
    "Customer",
    "Branch",
    final String DATA_DELETE = "DELETE * FROM ?";
    try
    PreparedStatement prepStmt = dbConn.prepareStatement(DATA_DELETE);
    for (int i =0; i < TABLE_NAME.length; i++)
    System.out.println(TABLE_NAME[i]);
    prepStmt.setString(1, TABLE_NAME[i]);
    prepStmt.execute();
    prepStmt.clearParameters();
    dbConn.commit();     //     not needed
    prepStmt.close();
    catch(SQLException e)
    System.out.println(e.getMessage());

    setString is just a specific case of setting a field value should not be used to set table name
    what u want to do should be done at the sql String level and it's not necessary prepared statements
    This would be my suggestion (didn't test it):
    final String[] TABLE_NAME =
    "Borrower",
    "Loan",
    "Depositor",
    "Account",
    "Customer",
    "Branch",
    final String DATA_DELETE = "DELETE * FROM TABLE_NAME";
    try
    Statement stmt = dbConn.createStatement();
    for (int i =0; i < TABLE_NAME.length; i++)
    System.out.println(TABLE_NAME);
    stmt.executeUpdate(
    sql.replaceFirst("TABLE_NAME",TABLE_NAME[i])
    dbConn.commit();     //     not needed
    stmt.close();
    catch(SQLException e)
    System.out.println(e.getMessage());

  • Table name for Bill of Exchange no

    Hi,
    We are using Payment Wizard for generating Bill of Exchange and sent customer for acceptence.
    We would like to create Query base report for printing Bill of Exchange sent for acceptence using payment wizard name.
    Can any one provide table name of Payment Wizard in which SAP stores the Bill of exchange no generated throgh Payment wizard.
    Regards,
    Arpit

    Hi
    Bill of Exchange are in OBOE table.
    Bill of Exchange lines are in BOE1 table
    Bill of Exchange transactions are in OBOT table.
    Kind regards.
    Agustín Marcos Cividanes

Maybe you are looking for