Dynamic table in a pl/sql script

Hi everybody
how can I design a sql query in a pl/sql script when the table I want to access is built dynamically ?
for instance
select to_char(sysdate,'MON')
into v_month
select * from table_'v_month' --> this is not working
Thanks for your replies
Alain

You will need to use dynamic sql to create a sql statement in PL/SQL.
If you have 8.1.x, you can use EXECUTE IMMEDIATE. You would need to have something like this in you proc.
SELECT TO_CHAR(sysdate,'MON')
INTO v_month;
tname:= 'table_'||v_month;
sqlstr := 'SELECT * FROM '||tname;
EXECUTE IMMEDIATE sqlstr;If you have 8.0.x or less, you will need to use the DBMS_SQL package. This is a little more complicated because you need to do a few more steps, but the principle is similar.
You can see how to use dynamic sql in the PL/SQL manuals, and in the Application Developer guide.

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 to reference dynamic parameters in the PL/SQL script

    The meaning of dynamic parameter is the position and name of parameters will be changed based on the data structure of a referenced text file reading by the concerned PL/SQL script. Anybody can post a sample code will be very appreciated.

    The SQL and PL/SQL discussion forum is a good source for this kind of information.
    The URL is:
    PL/SQL

  • 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

  • SQL script: dynamic table creation

    Hello,
    I should write a sql script to do the following (simplified):
    - Create a table if it doesn't exist yet
    - Select something from the newly created table and do further conditional actions
    I've tried something like that:
    DECLARE
    lv_count INTEGER;
    BEGIN
    DBMS_OUTPUT.enable();
    SELECT COUNT(*) INTO lv_count FROM user_tables WHERE table_name = 'DATABASEINFO';
    IF(lv_count = 0)
    THEN
         DBMS_OUTPUT.PUT_LINE('Create DatabaseInfo');
    EXECUTE IMMEDIATE
         'CREATE TABLE DATABASEINFO(
              ZDatabaseInfoId RAW(16) NOT NULL,
              ZInfo VARCHAR2(30) NOT NULL,
              ZValue VARCHAR2(100) NOT NULL,
    CONSTRAINT DatabaseInfo_U_NC_PK PRIMARY KEY
    ZDatabaseInfoId
    END IF;
    SELECT COUNT(*) INTO lv_count FROM DatabaseInfo WHERE ZInfo = 'anything';
    The select statement fails with error message "Table or view cannot be found". As far as I know, this is because the table is created dynamically and validation of the sql script fails because the table doesn't exist on compile time.
    How to solve that?
    Best Regards
    Andreas

    866121 wrote:
    Hello,
    I should write a sql script to do the following (simplified):
    - Create a table if it doesn't exist yet
    - Select something from the newly created table and do further conditional actions
    I've tried something like that:
    DECLARE
    lv_count INTEGER;
    BEGIN
    DBMS_OUTPUT.enable();
    SELECT COUNT(*) INTO lv_count FROM user_tables WHERE table_name = 'DATABASEINFO';
    IF(lv_count = 0)
    THEN
         DBMS_OUTPUT.PUT_LINE('Create DatabaseInfo');
    EXECUTE IMMEDIATE
         'CREATE TABLE DATABASEINFO(
              ZDatabaseInfoId RAW(16) NOT NULL,
              ZInfo VARCHAR2(30) NOT NULL,
              ZValue VARCHAR2(100) NOT NULL,
    CONSTRAINT DatabaseInfo_U_NC_PK PRIMARY KEY
    ZDatabaseInfoId
    END IF;
    SELECT COUNT(*) INTO lv_count FROM DatabaseInfo WHERE ZInfo = 'anything';
    The select statement fails with error message "Table or view cannot be found". As far as I know, this is because the table is created dynamically and validation of the sql script fails because the table doesn't exist on compile time.
    How to solve that?
    why, oh why, are you dynamically making table?
    DDL should be done only once via static SQL.
    dig a deeper hole & EXECUTE IMMEDIATE the SELECT.

  • SQL script for exporting table

    Could anyone please help me with SQL (plain SQL, not PL/SQL) for writing the data from a table into a .csv file?
    I need to run it on SQL developer. Can't use spool because it works only on SQL*PLus
    Edited by: user10403078 on Oct 15, 2008 2:24 AM

    But I want the SQL script to create a CSV file, because it should write the data from the tables into a CSV file, and proceed to delete it from the tables, every time the SQL script is run. I can't manually click and save.

  • Run multiple sql scripts using osql

    We have 2 databases which should be installed on each and every sql server.
    STEPS DONE
    1. scripted out these two DB'S as    ex:    db1.sql     db2.sql
    2.Scripted lookup tables in these DB's into two scripts        ex:    lookup1.sql   lookup2.sql
    3.scripted permissions of service accounts in two databases as     ex: perm1.sql    perm2.sql
    In order to run all these scripts in sequence I am planning to use an batch file which executes all these scripts in sequence and also we know the database creation script db.sql looks for the same path for DATA and LOG file locations as it is in the script. Is
    that possible to use parameters to allow dba to set location paths while running batch file?
    The sequence should be as
    db1.sql
    lookup1.sql
    perm1.sql
    db2.sql
    lookup2.sq
    perm2.sql

    Setup a ControlParms table. Let the DBA configure the values in the table.
    Change the .sql scripts to read the ControlParms table for path or other configuration value.
    Dynamic SQL: http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Dynamic Update Queries - SQL Script

    Hi All,
    I have a table Account_info where columns are ACCT_NO and flag with other information (columns). We are receving a file which contains ACCT_NO and FLAG. Now i need to compare ACCT_NO for Table and file and based on it need to update FLAG column in table.
    To automate this process, i can develop a shell script, which load data from file to temp table and then update statement to update Account_info table. For batch process, i can write a for loop, which commit data after every 10,000 update.
    but client does not want this way. We have to send file to Production team, where they will load data manually into temp table.
    Once done, i have to write a update statement which will take 10000 records to update on every run and then commit it, so there will not be space/memory issue.
    For example, if table has 50,000 records, i have to create 5 update statement. and then i have to send all 5 queries as sql script and send it to Production support.
    It is difficult for me to do it daily.
    Is there any other way, where SQL script is dynamic and based on number of rows/10000 , it create UPDATE statement and run it daily.
    Regards,
    ACE

    ace_friends22 wrote:
    Hi All,
    I have a table Account_info where columns are ACCT_NO and flag with other information (columns). We are receving a file which contains ACCT_NO and FLAG. Now i need to compare ACCT_NO for Table and file and based on it need to update FLAG column in table.
    To automate this process, i can develop a shell script, which load data from file to temp table and then update statement to update Account_info table. For batch process, i can write a for loop, which commit data after every 10,000 update.Why not simply use an external table pointing at the file and use a single update statement? If you write a loop with intermittent commits, this is one of the worst known ways of processing data.
    but client does not want this way.And the client knows how to technically implement a solution then? Why aren't they doing it themselves then?
    We have to send file to Production team, where they will load data manually into temp table.Unnecessary. Use an External table
    Once done, i have to write a update statement which will take 10000 records to update on every run and then commit it, so there will not be space/memory issue.Oracle is an enterprise level database engine capable of processing millions of rows without space/memory issues. If you've encountered shuch an issue you should be trying to identify the cause of it rather than suppress the symptoms.
    For example, if table has 50,000 records, i have to create 5 update statement. and then i have to send all 5 queries as sql script and send it to Production support.Bad Idea ^tm^

  • How to set dynamic table name in sql query?

    I want set dynamic table name by parameter in sql query,just like:
    select * from :tbname
    but run report is error,BI P report table name is invalidation.
    What can i do? Thanks!

    Hi,
    that's only possible inside a data template with a lexical parameter.
    Regards
    Rainer

  • Generating SQL Script for Existing Tables and DBs

    Hello,
    is it possible to generate automatically a SQL-Script from an existing table or oracle database ?
    I want to export an existing table from an Oracle DB (g11) if its possible with the data.
    Perhaps somebody could me explain how to to do this.
    I am using the "SQL Developer 2.1" and the "enterprise manager konsole".
    I'm a rookie in using this tools.
    Thank you for any informations.
    N. Wylutzki

    If you want to export data, you should use the export utility. This is documented:
    http://tinyurl.com/23b7on

  • Dynamic table pulled from SQL database, Need to Search

    My table results are not static, they are pulled into a
    dynamic table from a SQL database. Each table displays 10 records
    with an option at the bottom to display additional records
    (next/previous), for my query. I also have an option set up to
    allow users to click for a detail view of a record in the table. If
    the table data was static, I would be able to set up a search
    option and a results page for it, but I'm dealing with dynamic data
    on an .ASP page. I'd like to set up a search box to limit the
    records displayed in the table. I haven't found any code samples
    that are designed for dynamic data.
    Here is a copy of the code from my table.

    Hi,
    I think the code on this URL will get you the solution
    http://www.asp.happycodings.com/Array/code3.html
    Cheers,
    ~Maneet

  • How to get SQL script for generating table, constraint, indexes?

    I'd like to get from somewhere Oracle tool for generating simple SQL script for generating table, indexes, constraint (like Toad) and it has to be Oracle tool but not Designer.
    Can someone give me some edvice?
    Thanks!
    m.

    I'd like to get from somewhere Oracle tool for
    generating simple SQL script for generating table,
    indexes, constraint (like Toad) and it has to be
    Oracle tool but not Designer.
    SQL Developer is similar to Toad and is an Oracle tool.
    http://www.oracle.com/technology/products/database/sql_developer/index.html

  • How to generate sql script based on table structure

    I want to generate a sql script based on a table structure.
    For example:
    if the table is:
    cid id c_value
    1 1 zz
    2 1 yy
    3 2 zz
    4 2 xx
    5 3 ss
    6 3 tt
    The expected output is:
    WITH
    CHILD_tab as (
    SELECT 1 cid, 1 id,'zz' c_value from dual union all
    SELECT 2 cid, 1 id,'yy' c_value from dual union all
    SELECT 3 cid, 2 id,'zz' c_value from dual union all
    SELECT 4 cid, 2 id,'xx' c_value from dual union all
    SELECT 5 cid, 3 id,'ss' c_value from dual union all
    SELECT 6 cid, 3 id,'tt' c_value from dual )
    Release 11.1.0.7.0

    I'm doing a lot of XML these days (too much perhaps) so here's a solution involving XQuery.
    We pass a query string and it outputs a CLOB containing the WITH clause :
    SELECT DBMS_XMLGEN.Convert(
    XMLQuery(
    q'[concat(
    "WITH t AS (
    string-join(
    for $i in /ROWSET/ROW
    return concat( " SELECT ",
                    string-join($i/*/concat("'",ora:replace(text(),"'","''"),"' ",local-name()),", "),
                    " FROM dual" ),
    " UNION ALL
    passing dbms_xmlgen.getXMLType('SELECT * FROM scott.emp')
    returning content
    ).getClobVal(), 1) AS WITH_CLAUSE
    FROM dual;
    WITH_CLAUSE
    WITH t AS (
    SELECT '7369' EMPNO, 'SMITH' ENAME, 'CLERK' JOB, '7902' MGR, '17/12/80' HIREDATE, '800' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7499' EMPNO, 'ALLEN' ENAME, 'SALESMAN' JOB, '7698' MGR, '20/02/81' HIREDATE, '1600' SAL, '300' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7521' EMPNO, 'WARD' ENAME, 'SALESMAN' JOB, '7698' MGR, '22/02/81' HIREDATE, '1250' SAL, '500' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7566' EMPNO, 'JONES' ENAME, 'MANAGER' JOB, '7839' MGR, '02/04/81' HIREDATE, '2975' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7654' EMPNO, 'MARTIN' ENAME, 'SALESMAN' JOB, '7698' MGR, '28/09/81' HIREDATE, '1250' SAL, '1400' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7698' EMPNO, 'BLAKE' ENAME, 'MANAGER' JOB, '7839' MGR, '01/05/81' HIREDATE, '2850' SAL, '30' DEPTNO FROM dual UNION ALL
    SELECT '7782' EMPNO, 'CLARK' ENAME, 'MANAGER' JOB, '7839' MGR, '09/06/81' HIREDATE, '2450' SAL, '10' DEPTNO FROM dual UNION ALL
    SELECT '7788' EMPNO, 'SCOTT' ENAME, 'ANALYST' JOB, '7566' MGR, '19/04/87' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7839' EMPNO, 'KING' ENAME, 'PRESIDENT' JOB, '17/11/81' HIREDATE, '5000' SAL, '10' DEPTNO FROM dual UNION ALL
    SELECT '7844' EMPNO, 'TURNER' ENAME, 'SALESMAN' JOB, '7698' MGR, '08/09/81' HIREDATE, '1500' SAL, '0' COMM, '30' DEPTNO FROM dual UNION ALL
    SELECT '7876' EMPNO, 'ADAMS' ENAME, 'CLERK' JOB, '7788' MGR, '23/05/87' HIREDATE, '1100' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7900' EMPNO, 'JAMES' ENAME, 'CLERK' JOB, '7698' MGR, '03/12/81' HIREDATE, '950' SAL, '30' DEPTNO FROM dual UNION ALL
    SELECT '7902' EMPNO, 'FORD' ENAME, 'ANALYST' JOB, '7566' MGR, '03/12/81' HIREDATE, '3000' SAL, '20' DEPTNO FROM dual UNION ALL
    SELECT '7934' EMPNO, 'MILLER' ENAME, 'CLERK' JOB, '7782' MGR, '23/01/82' HIREDATE, '1300' SAL, '10' DEPTNO FROM dual
    )It may be useful for small data sets only because we quickly hit ORA-01706.

  • Question about creating new tables using SQL script in WebLogic Server

    Hi,
    I am new to WebLogic and I am following a book Java EE Development with Eclipse published by PACKT Publishing to learn
    Java EE.  I have installed Oracle Enterprise Pack for Eclipse on the PC and I am able to log into the WebLogic Server Administration Console
    and set up a Data Source.  However the next step is to create tables for the database.  The book says that the tables can be created using
    SQL script run from the SQL command line.
    I cannot see any way of inputting SQL script into the WebLogic Server Admistration Console.  Aslo there is no SQL Command line in DOS.
    Thanks  for your help.
    Brian.

    Sounds like you are to run the scripts provided by a tutorial to create the tables, right?  In that case, you may need to install an Oracle client to connect to your database.  The client is automatically installed with the database, so if you have access to the server that hosts the database, you should be able to run SQLplus from there.
    As far as I know, there is no way to run a script from the Admin Console.  I could be wrong, however.

  • Dynamically fetaching data into PL/SQL tables help

    Hi,
    I am develioping a PL/SQL procedure in which I am creatig 24 PL/SQL tables of the same type.
    But while inserting data in them I need to use the table names dynamically i.e., the Execute immediate used to put the data into the tables would remain same just I need that for each and every run of for loop for that Execute immediate statement, it should use different table name.
    Please see sample code below:
    col_name varchar2(20);
    Type RA_TABLE is table of CALL_DETAIL_EXCEPTION.IC_CIRCT_GR_CD%TYPE
    index by binary_integer;
    MY_RA1 RA_TABLE;
    MY_RA2 RA_TABLE;
    MY_RA3 RA_TABLE;
    MY_RA4 RA_TABLE;
    BEGIN
    for idx in 1..cnt_interval Loop
    Col_name := 'MY_RA'||idx;
    query1:='select Trunk_info bulk collect INTO MY_RA'|| idx ||' from dbl.vw_cgi v where not exists (select 1 from dbl.varun f
    where f.ic_circt_gr_cd= v.TRUNK_INFO and f.call_gmt_dnect_dt_time between
    to_date('''||stime||''',''yyyymmddhh24miss'') and to_date('''||etime||''',''yyyymmddhh24miss''))';
    Now when I execute this code, it gives me an error for query1 saying that it is unimplemented feature in Oracle.
    It is not able to pick up that dynamic table name.
    Please help!

    user9315951 wrote:
    I am develioping a PL/SQL procedure in which I am creatig 24 PL/SQL tables of the same type.All wrong. This is NOT how one treats data in PL/SQL.
    There is NO such concept as PL/SQL "+tables+". You are in fact defining associative arrays and not using these as associative arrays, but as normal arrays. Your code can consume vast amounts of server memory as private process memory. Your code CAN crash the Oracle database server (yes, I have seen this multiple times - even in production).
    Your code is flawed. Your approach is flawed.
    I suggest that you take several steps back, gain some understanding of fundamental Oracle concepts, about what does scale and perform in PL/SQL and SQL, and then apply these concepts and principles.

Maybe you are looking for

  • Set Commodity Code in Purchase order

    hello, I have implemented a BADi for purchase order for updating the commodity code/weight and Volume from material configuration. It works fine with updating for weight and volume. But when trying to update the Commodity code I got a "time out" beca

  • How to create a custom Firefox installation?

    I would like to install a custom version of Firefox on several computers. I would like to customize Firefox in the following ways: - Set the default language to English. - Set the default search engine to Google, and set the language of Firefox's def

  • Is it possible to duplicate a row in a table and the values entered by u

    PDF LiveCycle Designer  : Is it possible to duplicate a row in a table and the values entered by the user?

  • Passing Tables back from Java Stored Procedures

    Thomas Kyte has written (in reference to trying to pass an array back from a stored function call): You can do one of two things (and both require the use of objects). You cannot use PLSQL table types as JDBC cannot bind to this type -- we must use O

  • How to convert PS CS6 to exteneded version?

    my PS cs6 extended (3D) accidentally got converted into cs6...can sombody pls help me to get back my CS6 extended version....