How to display result of execute immediate on sql prompt

I wish to create a dynamic select statement where i will give table name and where condition as input parameters at runtime. for this i created following procedure:
CREATE or replace PROCEDURE select_rows (
table_name IN VARCHAR2,
condition IN VARCHAR2 DEFAULT NULL)
AS
where_clause VARCHAR2(100) := ' WHERE ' || condition;
BEGIN
IF condition IS NULL THEN where_clause := NULL; END IF;
EXECUTE IMMEDIATE 'select * FROM ' || table_name || where_clause;
END;
my procedure is successfully created.
my problem is how to get select stmt output at screen (sql prompt)
or how to spool the output in a file.
plz. help me. I am learning oracle .
thanx in adv.
Mani

You could use refcursors. Example :
TEST@db102 > CREATE or replace PROCEDURE select_rows (
  2     table_name IN VARCHAR2,
  3     condition IN VARCHAR2 DEFAULT NULL,
  4     cur1 out sys_refcursor)
  5  AS
  6     where_clause VARCHAR2(100) := ' WHERE ' || condition;
  7  BEGIN
  8     IF condition IS NULL THEN where_clause := NULL; END IF;
  9     open cur1 for 'select * from '||table_name||where_clause;
10  END;
TEST@db102 > /
Procedure created.
TEST@db102 > var cur refcursor;
TEST@db102 > exec select_rows('emp','deptno=20',:cur);
PL/SQL procedure successfully completed.
TEST@db102 > print cur
     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7788 SCOTT      ANALYST         7566 09-DEC-82       3000                    20
      7876 ADAMS      CLERK           7788 12-JAN-83       1100                    20
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
TEST@db102 >

Similar Messages

  • Copy the result of Execute immediate result into a variable.

    Hi All,
    Is there any way to copy the result of execute immediate result into a variable.
    am doing following steps but am getting an error.
    varSQLstmt1:='select count(*) into'||vararch_ct||' from '||vararch_count;
    dbms_output.put_line(varSQLstmt1);
    execute immediate varSQLstmt1;
    But am getting sql statement as select count(*) into from SALES
    the variable(vararch_ct) is missing in select statement .
    please help me to solve this issue. Or is there any way to insert the count of records into any variable.
    Thanks
    Sree

    declare
    varSQLstmt1    varchar2(4000);
    v_count          number;
    begin
    varSQLstmt1:='select count(*) from '||vararch_count;
    dbms_output.put_line(varSQLstmt1);   
    execute immediate varSQLstmt1 into v_count;
    dbms_output.put_line('Coutn :: ' || v_count);
    end;

  • How to display result of database query in JFrame?

    How to display result of oracle database query in JFrame?
    This is part of my code:
    String username, password;
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
              OracleConnection conn = DriverManager.getConnection(String url, String username, String password);
    Statement s= conn.createStatement();
    ResultSet q= s.executeQuery("SELECT A, B, C FROM TABLE X");
    Forget what url, username & password are. Is there any problem with my code?
    What should be next if I want to display result of the query in a table in JFrame?Thx !

    How to create JTable with unknown no. of rows? How to get no. of rows of a query?
    I saw the demo of creating JTable on java.sun.com but the the table has a certain no. of rows which is not applicable to my case.
    Suppose the result of query is a table with 3 attributes so there are 3 columns in the table.
    R contains the result of the query.
    Should it be something like this if I want to create JTable of the query?
    How to make n rows of {R.getString(1),R.getString(2),R.getString(3)};?
    public SimpleTableDemo() {
    super(new GridLayout(1,0));
    String[] columnNames = {"A",
    "B",
    "C",
    while (R.next())
    // content of a row
    Object[][] data = {R.getString(1),R.getString(2),R.getString(3)};
    I can't run it because I still can't debug my code which is said before.
    Thx!

  • How to display Date Calendar in Oracle BI Answers Prompts (parameter)

    I'm still new to OBIEE.
    How to display Date Calendar in Oracle BI Answers Prompts (parameter)?
    Thanks.

    Hi,
    While creating Dash Board prompt choose the control to 'Calendar'.
    I think it is not possible to provide 'Calendar' control using Prompts tab while creating request.
    It is possible to write Java Script for a Column of data type 'char'. So, cast the date data type to char.
    Go to: Column Properties --> Data Format
    Choose override default data format to view the available options in the drop down list.
    I would be very happy if anybody acknowledge me that I am wrong.
    -Vency

  • How to display list process, when i run sql*loader in c#

    Hello,
    How to display list process, when i run sql*loader in c#. I mean when i run sql*loader from cmd windows, i get list process how many row has been inserted. But when i run SQL*Loader from C#, i can't get process SQL*Loader.
    This is my code:
    string strCmd, strSQLLoader;
    string strLoaderFile = "XLLOAD.CTL";
    string strLogFile = "XLLOAD_LOG.LOG";
    string strCSVPath = @"E:\APT\WorkingFolder\WorkingFolder\sqlloader\sqlloader\bin\Debug\8testskrip_HTTP.csv";
    string options = "OPTIONS (SKIP=1, DIRECT=TRUE, ROWS=1000000,BINDSIZE=512000)";
    string append = "APPEND INTO TABLE XL_XDR FIELDS TERMINATED BY ','";
    string table = "OPTIONALLY ENCLOSED BY '\"' TRAILING NULLCOLS (xdr_id,xdr_type,session_start_time,session_end_time,session_last_update_time,session_flag,version,connection_row_count,error_code,method,host_len,host,url_len,url,connection_start_time,connection_last_update_time,connection_flag,connection_id,total_event_count,tunnel_pair_id,responsiveness_type,client_port,payload_type,virtual_type,vid_client,vid_server,client_addr,server_addr,client_tunnel_addr,server_tunnel_addr,error_code_2,ipid,c2s_pkts,c2s_octets,s2c_pkts,s2c_octets,num_succ_trans,connect_time,total_resp,timeouts,retries,rai,tcp_syns,tcp_syn_acks,tcp_syn_resets,tcp_syn_fins,event_type,flags,time_stamp,event_id,event_code)";
    strCmd = "sqlldr xl/secreat@o11g control=" + strLoaderFile + " LOG=" + strLogFile;
    System.IO.DirectoryInfo di;
    try
    System.Diagnostics.ProcessStartInfo cmdProcessInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
    di = new DirectoryInfo(strCSVPath);
    strSQLLoader = "";
    strSQLLoader += "LOAD DATA INFILE '" + strCSVPath.ToString().Trim() + "' " + append + " " + table;
    StreamWriter writer = new StreamWriter(strLoaderFile);
    writer.WriteLine(strSQLLoader);
    writer.Flush();
    writer.Close();
    // Redirect both streams so we can write/read them.
    cmdProcessInfo.RedirectStandardInput = true;
    cmdProcessInfo.RedirectStandardOutput = true;
    cmdProcessInfo.UseShellExecute = false;
    cmdProcessInfo.LoadUserProfile = true;
    //System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
    // Start the procses.
    System.Diagnostics.Process pro = System.Diagnostics.Process.Start(cmdProcessInfo);
    // Issue the dir command.
    pro.StandardInput.WriteLine(strCmd);
    // Exit the application.
    pro.StandardInput.WriteLine("exit");
    //Process[] processlist = Process.GetProcesses();
    //foreach(Process pro in processlist){
    Console.WriteLine("Process: {0} ID: {1}", pro.ProcessName, pro.Id);
    Console.WriteLine(pro.StandardOutput.ReadLine());
    // Read all the output generated from it.
    string strOutput;
    strOutput = pro.StandardOutput.ReadToEnd();
    pro.Dispose();
    catch (Exception ex)
    return;
    finally
    Thanks.

    friend
    sqlldr is an application residing in the OS. procedure runs in the dbms engine.
    you cannot run an os command directly from a procedure or a function or a package .
    If you want to do so you need to use either a daemon process created by a PRO*C program
    or a JAVA stored procedure to do so.
    just refer to previous question forums, you can find the solution. Somebody has already given a solution using
    java to run an OS command . check it out
    prakash
    [email protected]

  • Can I issue this command in PL/SQL: EXECUTE IMMEDIATE '@filename.sql';

    can I issue this command in PL/SQL: EXECUTE IMMEDIATE '@filename.sql';

    Hi,
    Rather the opening a new process (sqlplus), a new connection (need password) etc... I would rather read and execute the file in pl/sql.
    I do not know if someone wrote it already, but here is a quick and dirty code for doing that with UTL_FILE.GET_LINE
    Here, I am only processing some DML statements and no SELECT statements. Correct it as you like !
    CREATE OR REPLACE PROCEDURE run_script ( dir_name IN VARCHAR2,file_name IN VARCHAR2)
    IS
    vSFile UTL_FILE.FILE_TYPE;
    vCmd VARCHAR2(200);
    vNewLine VARCHAR2(200);
    BEGIN
        vSFile := UTL_FILE.FOPEN(dir_name, file_name,'r');
        vCmd := NULL;
        IF UTL_FILE.IS_OPEN(vSFile) THEN
        LOOP
            BEGIN
                UTL_FILE.GET_LINE(vSFile, vNewLine);
                if (vCmd is null) THEN
                    if (upper(vNewLine) like 'INSERT%' or upper(vNewLine) like 'UPDATE%' or upper(vNewLine) like 'DELETE%') THEN
                        if (vNewLine like '%;') THEN
                            /* we have a single line command, execute it now */
                            dbms_output.put_line(substr(vNewLine,1, length(vNewLine)-1));
                            execute immediate substr(vNewLine,1, length(vNewLine)-1);
                        else
                            /* we have a command over multiple line, set vCmd */
                            vCmd := vNewLine;
                        end if;
                    else
                        /* ignore the rest like spool, prompt, accept, errors, host, @, ... */
                        null;
                    end if;
                else
                    if (vNewLine like '%;') THEN
                        /* we have a the last line of the command, execute it now */
                        vCmd := vCmd || ' ' || substr(vNewLine,1, length(vNewLine)-1);
                        dbms_output.put_line(vCmd);
                        execute immediate vCmd;
                        vCmd := null;
                    else
                        /* keep concatenating to vCmd */
                        vCmd := vCmd ||' '|| vNewLine;
                    end if;
                end if;
            EXCEPTION
                WHEN NO_DATA_FOUND THEN
                    EXIT;
                END;
        END LOOP;
        COMMIT;
        END IF;
        UTL_FILE.FCLOSE(vSFile);
    EXCEPTION
        WHEN utl_file.invalid_path THEN
            RAISE_APPLICATION_ERROR (-20052, 'Invalid File Location');
        WHEN utl_file.read_error THEN
            RAISE_APPLICATION_ERROR (-20055, 'Read Error');
        WHEN others THEN
            RAISE_APPLICATION_ERROR (-20099, 'Unknown Error');
    END run_script;
    set serverout on
    create directory scriptdir as '/home/oracle';
    grant read,write on directory to scott;
    exec run_script('SCRIPTDIR', 'test.sql')

  • How do I display result of EXTRACT in PL/SQL

    I'm new to Oracle. I've begun experimenting with the XML functions. I was able to test existsNode and extractValue and see my results OK using DBMS_OUTPUT.PUT_LINE(<some variable of type X>) but I'm failing with EXTRACT. I currently think that extract returns an XML fragment of data type XMLType. I've failed to figure out how to display this fragment so see if my extract is doing what I expect. I've tried TO_CHAR(), TO_CLOB, and EXTRACT('/Root/text()').getStringVal() with no success. Could one of you point me in the right direction? My test is below.
    DECLARE     XMLDoc XMLTYPE;
         XMLOut          XMLType;
    BEGIN
         XMLDoc := XMLTYPE('<Root>
         <Trans_Info Name="ORIGINAL_AUTH_AMOUNT" Value="100.00" Mod_Date="2005-11-18" Trans_Id="100000" Xi_Id="100"></Trans_Info>
         <Trans_Info Name="Web Auth ID" Value="Houston" Mod_Date="2005-11-18" Trans_Id="100000" Xi_Id="100"></Trans_Info>
         <Trans_Info Name="3_SHIP_TO_STATE" Value="Of Mind" Mod_Date="2005-07-28" Trans_Id="100000" Xi_Id="100"></Trans_Info>
    </Root>');
         SELECT     EXTRACT(VALUE(x),'/Root')
         INTO     XMLOut
         FROM     TABLE(XMLSEQUENCE(XMLDoc.EXTRACT('/Root'))) x;
         DBMS_OUTPUT.PUT_LINE(XMLOut);
    END;

    As Garret said getClobVal() should work as should getStringVal()..
    You shouldn't be using XMLSEQUENCE on a node that only occurs once in the document (eg the root node). XMLSEQUENCE should be used to generate virtual tables from nodes that occur mutltiple times as the following shows..
    SQL> set serveroutput on
    SQL> --
    SQL> DECLARE
      2
      3  XMLDoc XMLTYPE;
      4  XMLOut XMLType;
      5
      6    cursor getTransInfo is
      7    select value(x) TRANSINFO
      8      from table(xmlsequence(extract(XMLDoc,'/Root/Trans_Info'))) x;
      9
    10  BEGIN
    11  XMLDoc := XMLTYPE(
    12  '<Root>
    13    <Trans_Info Name="ORIGINAL_AUTH_AMOUNT" Value="100.00" Mod_Date="2005-11-18" Trans_Id="100000" Xi_Id="100"></Trans_Info>
    14    <Trans_Info Name="Web Auth ID" Value="Houston" Mod_Date="2005-11-18" Trans_Id="100000" Xi_Id="100"></Trans_Info>
    15    <Trans_Info Name="3_SHIP_TO_STATE" Value="Of Mind" Mod_Date="2005-07-28" Trans_Id="100000" Xi_Id="100"></Trans_Info>
    16  </Root>');
    17
    18    -- Can use an in-line SELECT INTO here as only one row is returned..
    19
    20    SELECT EXTRACT(XMLDoc,'/Root')
    21      into XMLOUT
    22      from dual;
    23
    24    -- Can also be written as xmlout := XMLDOC.extract('/Root');
    25
    26    -- Use getStringVal() or getClobVal() to serialize XMLType for DBMS_OUTPUT.
    27
    28    DBMS_OUTPUT.PUT_LINE('extract(''/Root'') : ');
    29    DBMS_OUTPUT.NEW_LINE();
    30    DBMS_OUTPUT.PUT_LINE(XMLOut.getStringVal());
    31    DBMS_OUTPUT.NEW_LINE();
    32
    33    -- Use the Cursor to process the set of Trans_Info nodes. Cannot use an inline SELECT INTO here as multiple rows are returned.
    34
    35    DBMS_OUTPUT.PUT_LINE('value(x) : ');
    36    DBMS_OUTPUT.NEW_LINE();
    37
    38    for r in getTransInfo loop
    39      DBMS_OUTPUT.put_line(r.TRANSINFO.getStringVal());
    40    end loop;
    41  END;
    42
    43  /
    extract('/Root') :
    <Root><Trans_Info Name="ORIGINAL_AUTH_AMOUNT" Value="100.00"
    Mod_Date="2005-11-18" Trans_Id="100000" Xi_Id="100"/><Trans_Info Name="Web Auth
    ID" Value="Houston" Mod_Date="2005-11-18" Trans_Id="100000"
    Xi_Id="100"/><Trans_Info Name="3_SHIP_TO_STATE" Value="Of Mind"
    Mod_Date="2005-07-28" Trans_Id="100000" Xi_Id="100"/></Root>
    value(x) :
    <Trans_Info Name="ORIGINAL_AUTH_AMOUNT" Value="100.00" Mod_Date="2005-11-18"
    Trans_Id="100000" Xi_Id="100"/>
    <Trans_Info Name="Web Auth ID" Value="Houston" Mod_Date="2005-11-18"
    Trans_Id="100000" Xi_Id="100"/>
    <Trans_Info Name="3_SHIP_TO_STATE" Value="Of Mind" Mod_Date="2005-07-28"
    Trans_Id="100000" Xi_Id="100"/>
    PL/SQL procedure successfully completed.
    SQL>

  • How can i have '&' in EXECUTE IMMEDIATE statement?

    I have PL/SQL procedure, where i will be inserting data to a table. Data which i am inserting is having a '&' value in it. If i use the below statement for insert then sqlplus is prompting for the value '&' like a substitution value while compile this procedure.
    EXECUTE IMMEDIATE 'INSERT INTO TABLE_TEST VALUES (:1,:2)' USING 'root/direct/&text', SYSDATE;If i replace the '&' by assigning this value to VARCHAR field then it is working properly. But when i populate an xml from this table using DBMS.XMLGEN, then the value '&' is not entity escaped in the XML which is normally replaced with '&amp;' in XML.
    Please help.

    Vel wrote:
    i can't go by both ways because i am using '&' in various files to get some values. Also in this package i am using the '&' to get another substitution variable. Is there any other workaround possible?I prefer not to mess with server-side SQL and PL/SQL code to fix, or work around, a problem on the client-side. Not a very sensible thing IMO.
    In such a case as you've described, I would set the substitution character to a character that I'm not using in server-side code. I have done this a couple of times in the past for db create and installation scripts. Oracle uses the same approach for their Apex installation scripts.
    I think Oracle uses the +#+ character for their Apex install scripts. E.g.
    set define '#'I think I used the tilde (char <i>~</i>) at a stage as substitution char as it is very seldom used in PL/SQL and SQL code.
    The bottom line is that you will need to change your code. Set define off and on where needed to ensure substitution only happens where needed. Set the substitution char to a different char and update your substitution variables. Or hack your server-side code (as suggested above) and use the char() function instead.

  • How to display results set of multiple reports into a single report table

    Our goal is to create a single report (or dashboard) that shows the "funnel" of object creations related to each campaign. The flow goes from Activity to Lead to Opportunity as well as multiple steps within each (ie. Unqualified Lead -> Qualified Lead, etc).
    We currently have 3 separate reports in three different subject areas, each reporting the different metrics and we would like to combine the output into a single Unified report.
    For example what we currently have is:
    Activities:
    Campaign Name # of Activities
    Campaign A 12
    Campaign B 26
    Leads:
    Campaign Name # of Leads # of Qualified Leads
    Campaign A 10 4
    Campaign B 20 18
    Opportunities:
    Campaign Name # of Opportunities # of Opps per Sales Stage ... # of Wins Closed Revenue
    Campaign A 3 2 1 $1,000.00
    Campaign B 10 8 3 $2,800.00
    What we want to see is:
    Combined:
    Campaign Name - Campaign Cost - # of Activities - # of Leads - # of Qualified Leads - # of Opportunities - # of Opps per Sales Stage - # of Wins - Closed Revenue
    Campaign A - $423.00 - 12 - 10 - 4 - 3 - 2 - 1 - $1,000.00
    Campaign B - $ 1,000.00 - 26 - 20 - 18 - 10 - 8 - 3 - $2,800.00
    We have tried using the "Combine with similar analysis" but the number of columns for each subject area differ. We also tried creating multiple UNION criteria (one for each column), but in the case of # of Opps per Sales Stage and Closed Revenue, those are not "Metrics" fields, so they won't combine.

    Hi, You may have to create some dummy fields to equate the no. of field in each of the report matching the data type too and get a one single report using combined analytics and then using the resultant data you can create a simple pivot like below. Haven't tried it before
    -- Venky CRMIT
    Hi Venky,
    I am facing the same problem. Can you please say Steps how to create resultant data and Combine in pivot Table .
    Please Help me .
    Thanks in Advance .
    My mail id is :
    [email protected]

  • Put the query result of "EXECUTE IMMEDIATE" command in a local table

    Hi all.
    Is it possible to put the output of the "EXECUTE IMMEDIATE" command in a local table so that the ouput can be accessed through other procedures.
    Regards,
    Andila

    Hi Andila, well you could just make your dynamic sql statement an insert statement based on your select. See example below
    create column table test_table_1
    "COL1" nvarchar(10),
    "COL2" nvarchar(10)
    CREATE PROCEDURE INSERT_P() 
    LANGUAGE SQLSCRIPT AS 
      sql_string NVARCHAR(2000) := '';
    BEGIN 
      sql_string := 'insert into test_table_1 (select ''val1'', ''val2'' from dummy) ';
      EXECUTE IMMEDIATE (:sql_string); 
    END; 
    call insert_p();
    select * from test_table_1;
    However you may want to investigate other options instead of using dynamic SQL as this is not a recommended approach. Less optimized compared to standard sql.
    Peter

  • How to take output of execute immediate 'select * from table' into a file ?

    hi all,
    below is my code .....
    declare
    var_column_name varchar2(2000);
    main_string varchar2(12000);
    var_table_name varchar2(30);
    base_string varchar2(2000);
    final_string varchar2(2000);
    cursor c1 is
    select
    object_name
    from user_objects
    where object_type in ('TABLE','VIEW') and rownum < 2 ;
    cursor c2 is
    select
    column_name
    from user_tab_columns
    where upper(table_name) = upper(var_table_name);
    begin
    --var_column_name := null;
    -- main_string :=null;
    -- table_name :=null ;
    -- base_string :=null;
    -- final_string := null;
    open c1;
    fetch c1 into var_table_name;
    close c1;
    for c2_var in c2
    loop
    main_string := c2_var.column_name||','||main_string;
    end loop;
    select rtrim(main_string,',') into final_string from dual;
    dbms_output.put_line(final_string);
    base_string := 'Select '||final_string ||' from '||var_table_name||'' ;
    dbms_output.put_line(base_string);
    spool tete.lst;
    execute immediate base_string;
    spool off;
    end;
    i want to take the output of the execute immediate in a file on unix server ....
    please suggest
    rgds
    s

    Were you looking for something like this?
    SELECT
         CASE WHEN Columns.Column_Id = 1 THEN 'SELECT ' || CHR(10) END
              || CHR(09) || Columns.Column_Name
              || CASE
                   WHEN Columns.Column_Id = Info.Total_Columns THEN
                           CHR(10) || 'FROM'
                        || CHR(10) || CHR(09) || Columns.Table_Name || ';'
                        || CHR(10)
                   ELSE ','
                 END          Statement
    FROM
         User_Tab_Columns     Columns,
          SELECT
              Table_Name,
              MAX(Column_Id) Total_Columns
          FROM
              User_Tab_Columns
          GROUP BY
              Table_Name
         )               Info
    WHERE
         Columns.Table_Name = Info.Table_Name
    ORDER BY
         Columns.Table_Name,
         Columns.Column_Id;

  • Execute immediate a sql block of istructions

    Hello,
    i need to to do something like this:
    execute immediate par;
    where par is a big file stored in a table that is simply a pl/sql script like this
    comment on table SOMETABLE.COLUMN is 'this' ;
    comment on table SOMETABLE.COLUMN2 is 'this' ;
    and so on for 45 columns. when i try it say that ; is not a valid character. It works only if i put only a row in the table.
    How i can put more istructions in a string to be "execute immediate"
    Thanks
    Edited by: user12195888 on 10-nov-2009 7.59

    In the example already provided be aware that if you have commands that aren't supported in PL/SQL like COMMENT this approach may not work. Here is an example that breaks the string up on the semi-colon terminator:
    SQL> DROP TABLE A;
    Table dropped.
    SQL> DROP TABLE B;
    Table dropped.
    SQL> DROP TABLE C;
    Table dropped.
    SQL> DROP TABLE INSTRUCTION_TEST;
    Table dropped.
    SQL>
    SQL> CREATE TABLE A (ID NUMBER);
    Table created.
    SQL> CREATE TABLE B (ID NUMBER);
    Table created.
    SQL> CREATE TABLE C (ID NUMBER);
    Table created.
    SQL> CREATE TABLE INSTRUCTION_TEST
      2  (
      3          INSTRUC VARCHAR2(4000)
      4  );
    Table created.
    SQL>
    SQL> INSERT INTO INSTRUCTION_TEST
      2  VALUES
      3  (
      4          'COMMENT ON TABLE A IS ''Table A''; COMMENT ON TABLE B IS ''Table B''; COMMENT ON TABLE C IS ''Table C'';'
      5  );
    1 row created.
    SQL>
    SQL> DECLARE
      2  BEGIN
      3          FOR r IN
      4          (
      5                  WITH    instructions AS
      6                  (
      7                          SELECT  ';' || INSTRUC AS INST
      8                          FROM    INSTRUCTION_TEST
      9                  )
    10                  SELECT  SUBSTR
    11                          (
    12                                  INST
    13                          ,       INSTR(INST,';',1,LEVEL) + 1
    14                          ,       INSTR(INST,';',1,LEVEL+1) - INSTR(INST,';',1,LEVEL) - 1
    15                          )       AS INDIVIDUAL_STATEMENT
    16                  FROM    instructions
    17                  CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(INST,'[^;]','')) - 1
    18          )
    19          LOOP
    20                  --DBMS_OUTPUT.PUT_LINE(r.INDIVIDUAL_STATEMENT);
    21                  EXECUTE IMMEDIATE r.INDIVIDUAL_STATEMENT;
    22          END LOOP;
    23  END;
    24  /
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM ALL_TAB_COMMENTS WHERE TABLE_NAME IN ('A','B','C');
    OWNER                          TABLE_NAME                     TABLE_TYPE  COMMENTS
    TEST_USER                      C                              TABLE       Table C
    TEST_USER                      B                              TABLE       Table B
    TEST_USER                      A                              TABLE       Table AHTH!

  • Help on Execute Immediate Dynamic Sql

    Hi all
    when i run the following Pl/SQL,nothing is happening
    I want to pass array to following procedure
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    SQL> ed
    Wrote file afiedt.buf
      1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
      2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
      3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
      TABLE TABLE_TEST1
        "ID_NO"      NUMBER(10,0)     ,
        "ID_NAME"    VARCHAR2(10 BYTE),
        "ATTRIBUTE1" VARCHAR2(10 BYTE),
        "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    table_test
    Edited by: user1849 on Nov 30, 2011 12:40 PM
    Edited by: user1849 on Nov 30, 2011 1:18 PM

    user1849 wrote:
    Hi all
    when i run the following Pl/SQL,nothing is happeningRemember to issue the SQL*Plus command
    SET  SERVEROUTPUT  ONbefore running it; otherwise, you won't see the output from dbms_output.
    >
    I want to pass array to following procedureIs this a procedure or an anonymous PL/SQL block?
    If it's a procedure, post the entire procedure, starting with CREATE [OR REPLACE] PROCEDURE...
    Never write, let alone post, unformatted code. Indent the code to show the scope of BEGIN, LOOP, etc.
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    /Only use an EXCEPTION handler when you can improve on the default error handling. The default is to print an error message, so there's no point in you explicitly doing the same.
    Why do you need dynamic SQL? Post the output results you want to get from the sample data you posted.
    Given that you do need dynamic SQL, why can't you use bind variables, rather than including the values as literals?
    Given that you have to use literals, use Q-notation for strings that include single-quote characters.
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#sthref337
    For example:
    ...     SQL_STMT  := Q{'Select  populate_table_test ('}'
              || id_name
              || Q'{','}'
              || attribute1
              || Q'{','}'
    SQL> ed
    Wrote file afiedt.buf
    1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
    TABLE TABLE_TEST1
    "ID_NO"      NUMBER(10,0)     ,
    "ID_NAME"    VARCHAR2(10 BYTE),
    "ATTRIBUTE1" VARCHAR2(10 BYTE),
    "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful.
    Is that the best sample data for testing? Wouldn't it be better to have at least one row that was not the same as all the others?
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (l_t_seq(i),
    treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; You're trying to INSERT 4 values into 3 columns. Did you mean to say "insert into TABLE_TEST( *id_no,* id_name,attribute1,attribute2)"?
    What is l_t_seq? Post complete test scripts that people can run to re-create the problem and test their ideas.

  • Execute Immediate with SQL in Stored Procedure

    Dear Experts, Please help / guide on below statement which i want to execute in stored procedure,
    EXECUTE IMMEDIATE 'INSERT INTO TABLE
    SELECT COUNT(AGENTID) FROM TABLE_1 A,
    TABLE_2 B, TABLE_3 C
    WHERE A.COL = B.COL AND B.COL = C.COL AND
    DT BETWEEN TRUNC(SYSDATE-1) + 1/24 + 0/12/60/60 AND TRUNC(SYSDATE-1) + 25/24 - 0/12/60/60';
    Edited by: DBA on Dec 3, 2011 3:57 PM

    So what's the problem? The only thing I can see is:
    INSERT INTO TABLETABLE is reserved word, so name your table differently.
    Also, I am assuming the above statement is actually generated from some variables based on some conditions, otherwise why would you need dynamic SQL, just issue:
    INSERT INTO TABLE
    SELECT COUNT(AGENTID) FROM TABLE_1 A,
    TABLE_2 B, TABLE_3 C
    WHERE A.COL = B.COL AND B.COL = C.COL AND
    DT BETWEEN TRUNC(SYSDATE-1) + 1/24 + 0/12/60/60 AND TRUNC(SYSDATE-1) + 25/24 - 0/12/60/60;

  • Obtaining a collection as a return from an execute immediate pl/sql block

    version 10.2
    I need to obtain the collection back from the execute immediate of a pl/sql block:
    procedure block(owner varchar2) is
    stmt                   long;
    objecttab_coll         dbms_stats.objecttab;
    begin
    stmt := '
       begin
        dbms_stats.gather_schema_stats(''' || owner || '''
         ,options => ''LIST AUTO''
         ,objlist => :objecttab_coll
       end;'; 
    execute immediate stmt returning into objecttab_coll;
    -- do more stuff here
    end block;I have tried this + a few variations but with no luck. In looking through the docs I do not see an example. can this be done?
    Thanks
    Ox

    I dont find any need for an execute immediate here. This must be just enough.
    procedure block(owner varchar2)
    is
         objecttab_coll         dbms_stats.objecttab;
    begin
         dbms_stats.gather_schema_stats(ownname => owner, options => 'LIST AUTO', objlist => objecttab_coll);
         -- do more stuff here
    end block;Thanks,
    Karthick.

Maybe you are looking for

  • Problem with functioning Generic Delta

    Hi Expert ! I Have Created a Generic Delta and has Scheduled the Delta Load By Means of Process Chain In BI Side. Although it is showing Green(OK) status for the respected Request at PSA(saying No Data Exists FOR PSA) and ODS Lavel but no data is loa

  • ICHAT AV & KYE 320S USB Webcam

    I installed this low cost "genius" (25US$) webcam and it works fine with the IChatUSECam driver but I cannot "zoom out" so only a close up of my face is visible.. This is obviously better than nothing and a great economical solution, but it would be

  • Character encoding in flash

    I'm trying to view this application in Russian: http://www.h-ck.ru/map/address.php3?x=237&y=176 But it's showing up in Unicode or Western. How can I change the encoding in the flash application? I've played with all the encoding settings in both Fire

  • Abap vs Java?

    Hi All, Are there any major differences in Interactive Forms between the Abap Workbench and Java environment development wise? Regards, Itay Assraf

  • Smartform material desc. window + zebra printer. 40 chars desc not display

    Hi All, I have a problem in printing the material description of 40 characters using zebra printer for label printing. If I take field of 40 characters, the printer is wrapping the text after 30 and print in the next line. So I divided the desc into