EXECUTE IMMEDIATE stmt

I am using oracle 10G XE.
When I have the following, it works fine..
========================================
FOR report_c IN report_cur LOOP
FOR i in 1 .. 62 loop
INSERT INTO trip_stop (sc_v, r_id, b_id,
code_id, terminal, seq_num, bs_id, flag, note_id, eta_string)
VALUES (report_c.sc_v, report_c.r_id, report_c.b_id,
report_c.code_id, report_c.terminal, i , report_c.st_id1,
report_c.flag1, report_c.note1, report_c.eta1);
COMMIT;
END LOOP;
END LOOP;
========================================
I need to use a dynamic sql to change the column name
i.e.: from id1 to id2 then to id3, etc..
I need to repeat this 62 times.. So I tried to use the following, but I got error:
ORA-00984: column not allowed
Any idea??? Any suggestion??
Thanks
========================================
FOR report_c IN report_cur LOOP
FOR i in 1 .. 62 loop
stmt:= ' INSERT INTO trip_stop ' ||
' (sc_v, r_id, b_id, ' ||
' code_id, terminal, ' ||
' seq_num, bs_id, flag, note_id, eta_string) ' ||
' VALUES (report_c.sc_v, report_c.r_id, report_c.b_id, ' ||
' report_c.code_id, report_c.terminal, ' ||
i ||','|| c_st_id||','|| c_flag||','|| c_note||','|| c_eta|| ' ||);' ;
i ||', report_c.st_id' || i || ', report_c.flag' || i||', report_c.note' || i||', report_c.eta' || i||');' ;
EXECUTE IMMEDIATE stmt;
END LOOP;
END LOOP;

I would suggest "unpivoting" that table by turning each row in the source table into 62 rows - that way you can insert into/select from and do this in one insert statement with no procedural or dynamic code at all.
Here's an example going 1-2 instead of 1-62:
sql>select * from t;
SC_V  R_ID  B_ID ST_ID1 FLAG1  ETA1 ST_ID2 FLAG2  ETA2
    0   123  1111    101     1  1001    102     0  1002
    0   124  1112    201     1  2001    202     0  2002
    0   125  1113    301     1  3001    302     0  3002
3 rows selected.
sql>select *
  2    from t, (select rownum rn from dual connect by level <= 2) d
  3   order by t.r_id, d.rn;
SC_V  R_ID  B_ID ST_ID1 FLAG1  ETA1 ST_ID2 FLAG2  ETA2    RN
    0   123  1111    101     1  1001    102     0  1002     1
    0   123  1111    101     1  1001    102     0  1002     2
    0   124  1112    201     1  2001    202     0  2002     1
    0   124  1112    201     1  2001    202     0  2002     2
    0   125  1113    301     1  3001    302     0  3002     1
    0   125  1113    301     1  3001    302     0  3002     2
6 rows selected.
sql>select t.sc_v, t.r_id, t.b_id,
  2         case rn
  3           when 1 then st_id1
  4           when 2 then st_id2
  5         end st_id,
  6         case rn
  7           when 1 then flag1
  8           when 2 then flag2
  9         end flag,
10         case rn
11           when 1 then eta1
12           when 2 then eta2
13         end eta
14    from t, (select rownum rn from dual connect by level <= 2) d
15   order by t.r_id;
SC_V  R_ID  B_ID ST_ID  FLAG   ETA
    0   123  1111   101     1  1001
    0   123  1111   102     0  1002
    0   124  1112   201     1  2001
    0   124  1112   202     0  2002
    0   125  1113   301     1  3001
    0   125  1113   302     0  3002
6 rows selected.

Similar Messages

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

  • Failure of EXECUTE IMMEDIATE when in a stored procedure

    Hello,
    this concerns behaviour observed in Oracle 10g on Windows.
    As user "system", I execute from the command line the following:
    SQL> select COUNT(1) from sys.dba_sequences;
    COUNT(1)
    645
    Again I try the same thing from the command line:
    SQL> declare
    2 CNT INTEGER:=0;
    3 STMT VARCHAR2(300);
    4 BEGIN
    5 STMT:='select COUNT(1) from SYS.DBA_SEQUENCES';
    6 EXECUTE IMMEDIATE STMT INTO CNT;
    7 dbms_output.put_line('CNT='||CNT);
    8 end;
    9 /
    CNT=645
    So far so good, clearly this table exists and I have sufficient privileges to access SYS.DBA_SEQUENCES as user system.
    However, if I put this in a stored procedure in a script TEST_SEQ.sql and then execute, I get ORA-00942:
    1. Create or replace Procedure TEST_A1
    2. IS
    3. CNT INTEGER:=0;
    4. STMT VARCHAR2(300);
    5.
    6. BEGIN
    7. STMT:='select COUNT(1) from SYS.DBA_SEQUENCES';
    8.     EXECUTE IMMEDIATE STMT INTO CNT;
    9.     dbms_output.put_line('CNT='||CNT);
    10. END;
    SQL> @ TEST_SEQ.sql
    SQL> exec TEST_A1;
    ORA-00942: Table or view does not exist
    ORA-06512: At "SYSTEM.TEST_A1", line 8
    ORA-06512: At line 1
    Why now does this table not seem to exist when accessed from a stored procedure?

    http://www.google.com/search?btnG=1&q=ora-0942+procedure
    Sybrand Bakker
    Senior Oracle DBA
    Experts: those who do read documentation.

  • BULK SELECT EXECUTE IMMEDIATE

    I want to update 3 lakhs record in EXP__REQUEST_SK table
    How to use bulk select "execute immedaite" in PLSQL
    Update EXP__Request_sk set R_CUSTOMERNAME = cust_name where BFG_CUSTOMERID=cust_id;

    Note: this code is not tested.
    create or replace procedure generic_update (
      tab_name  varchar2,             -- table to update
      field_to_update  varchar2,     -- column to update
      field_value  varchar2,             -- new column value
      id_field_name  varchar2,        -- id column name
      id_value number)                 -- id value to identify the record
    as
      --local variables section
      stmt varchar2(4000) := '';
    begin
      stmt := 'update ' || tab_name || ' set ' || field_to_update || ' = :f_value where '
                 || id_field_name || ' = :i_value';
      savepoint txn1;
      execute immediate stmt using field_value, id_value;
      execute immediate ('commit');
      dbms_output.put_line('Update is done.');
    exception
       when others then
          rollback to txn1;
          dbms_output.put_line('Update has been rolled back.');
    end;
    /Even though I provided this, static SQL is always faster than PL/SQL because there is no context switch.
    An alternative to the above is to write all static SQLs into a script and run it.
    However, if you don't know which tables and column to update before hand, and the update depends on user inputs (e.g. from a JSP), then Java can call a stored procedure to perform the update.
    Edited by: pl/sql novice on Nov 20, 2008 11:24 PM

  • Execute immediate and "in" operator

    Hello!
    I want to pass varchar2 type argument to my procedure in format '1,2,3' where 1,2 and 3 are some IDs.
    And then, in procedure I write:
    stmt := 'select avg(PRICE) from ORDERS where ORDER_ID in (:Ids)';
    execute immediate stmt into APrice using ARGUMENT;
    I undersand, that this is incorrect, because where clause in executable query is
    "where ORDER_ID in ('1,2,3')" but not "where ORDER_ID in (1,2,3)".
    Is there any easy way how to solve such a problem?
    Maybe I should use other argument type?

    user10304317 wrote:
    I undersand, that this is incorrect, because where clause in executable query isIf you want to use a string you will have to concatenate it into dynamic sql:
    stmt := 'select avg(PRICE) from ORDERS where ORDER_ID in (' || ARGUMENT || ')';
    execute immediate stmt into APrice;However, it will produce as many sql in shared pool as you will have different ARGUMENT values and each of them will do a hard parse. Or you could use collection and then you do not need dynamic sql (unless select list and/or rest of where clause is dynamic):
    SQL> create or replace
      2    type num_tbl_type
      3      as
      4        table of number;
      5  /
    Type created.
    SQL> create or replace procedure p1(
      2                                 p_num_tbl num_tbl_type
      3                                )
      4    is
      5    begin
      6        for rec in (select empno,ename from emp where empno in (select * from table(p_num_tbl))) loop
      7          dbms_output.put_line(rpad(rec.empno,10) || rec.ename);
      8        end loop;
      9  end;
    10  /
    Procedure created.
    SQL> set serveroutput on
    SQL> exec p1(num_tbl_type(7566,7839,7902))
    7566      JONES
    7839      KING
    7902      FORD
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Unable to INSERT PL/SQL  record with EXECUTE IMMEDIATE

    Hi All,
    I am selecting data from a source table and after some modification inserting into a target table. Source and target table name are available at run time. You can say only source table structure is fixed.
    I have crated a pl/sql table of type source record and inserting record by record in target table using execute immediate. But I am not able to write
    EXECUTE IMMEDIATE string USING pl_sql_table(index); and getting error as
    PLS-00457: expressions have to be of SQL types
    Please see the part of code below. Is it possible to use FORALL with dynamic sql like
    FORALL pl_sql_table.FIRST .. pl_sql_table.COUNT
    EXECUTE IMMEDIATE .... pl_sql_table(j); -- Like this.
    Please suggest why I am not able to write record here. I also want to replace 'INSERT in a loop' with a single INSERT statement out of the loop, to upload whole pl_sql table into target table in one go.
    Thanks,
    Ravi
    DECLARE
        TYPE rec_tab_CMP IS RECORD
         model_id          NUMBER(38),   
         absolute_rank          NUMBER(5)         
        v_rec_tab_CMP  rec_tab_CMP;
        TYPE t_rec_tab_CMP IS TABLE OF v_rec_tab_CMP%TYPE INDEX BY BINARY_INTEGER;
        v_records_CMP               t_rec_tab_CMP;
        rc                          SYS_REFCURSOR;
        v_old_table_name            VARCHAR2(30); -- passed from parameter 
        v_new_table_name            VARCHAR2(30); -- passed from parameter 
        dyn_str                     VARCHAR2(500);
        v_columns_str               VARCHAR2(200) := ' model_id, absolute_rank ';
    BEGIN
           EXECUTE IMMEDIATE 'CREATE TABLE '|| v_new_table_name || ' AS SELECT * FROM ' || v_old_table_name ||' WHERE 1 = 2 ' ;
         OPEN rc FOR 'SELECT '|| v_columns_str ||' FROM '|| v_old_table_name;
         FETCH rc BULK COLLECT INTO v_records_CMP;
         FOR j IN 1..v_records_CMP.COUNT
         LOOP
            v_records_CMP(j).model_id := 1; -- Do someting here, This thing can be performed in SQL stmt directly.
            dyn_str := 'INSERT INTO '|| v_new_table_name ||' ( '|| v_columns_str || ' ) VALUES (:1, :2) ';
            EXECUTE IMMEDIATE dyn_str USING v_records_CMP(j).model_id          ,
                                v_records_CMP(j).absolute_rank     ;
         -- Here in place of two columns I want to use one record like
         -- EXECUTE IMMEDIATE dyn_str USING v_records_CMP(j);
         -- But it is giving me error like
            --          EXECUTE IMMEDIATE dyn_str USING v_records_st(j);
            --   PLS-00457: expressions have to be of SQL types
         END LOOP;
         CLOSE rc;
    END;
    /

    You cannot bind PL/SQL record types to dynamic SQL.
    Possibly you could work around this by declaring the INDEX-BY table of records at package specification level, e.g.
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
    SQL> CREATE PACKAGE package_name
      2  AS
      3     TYPE tt_emp IS TABLE OF emp%ROWTYPE;
      4     t_emp tt_emp;
      5  END package_name;
      6  /
    Package created.
    SQL> CREATE TABLE new_emp
      2  AS
      3     SELECT *
      4     FROM   emp
      5     WHERE  1 = 0;
    Table created.
    SQL> DECLARE
      2     v_table_name user_tables.table_name%TYPE := 'NEW_EMP';
      3  BEGIN
      4     SELECT *
      5     BULK COLLECT INTO package_name.t_emp
      6     FROM   emp;
      7
      8     EXECUTE IMMEDIATE
      9        'BEGIN ' ||
    10        '   FORALL i IN 1 ..package_name.t_emp.COUNT ' ||
    11        '      INSERT INTO ' || v_table_name ||
    12        '      VALUES package_name.t_emp (i); ' ||
    13        'END;';
    14  END;
    15  /
    PL/SQL procedure successfully completed.
    SQL> SELECT empno, ename
      2  FROM   new_emp;
         EMPNO ENAME
          7369 SMITH
          7499 ALLEN
          7521 WARD
          7566 JONES
          7654 MARTIN
          7698 BLAKE
          7782 CLARK
          7788 SCOTT
          7839 KING
          7844 TURNER
          7876 ADAMS
          7900 JAMES
          7902 FORD
          7934 MILLER
    14 rows selected.
    SQL>

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

  • Problem while executing procedure thru Shell script (EXECUTE IMMEDIATE)

    Hi All,
    I have created a procedure where i am passing column name, tablename and business date. The procedure gets last 5 business date excluding Saturday and sunday based on business date.
    i am using EXECUTE IMMEDIATE statement in the procedure, where i am replacing the column name, table name, and business date & then executing this statement.
    stmt := 'select count(1) FROM '||tblname||' where trunc('||date_column||')= :1';
    EXECUTE IMMEDIATE l_stmt into tbl_count using to_char(in_date, 'DD-MON-YYYY') ;
    It will give me the count of all 5 days for a particular dates. When i run the procedure in SQL*Plus/TOAD, it gives me desired result. When i run this in UNIX shell script, it runs fine but at end gives following error:
    SP-xxx: Bind varaible not declared.
    Can someone tell me where might be the problem?

    Hello, if you could put a {noformat}{noformat} before and after your snippets of code please, it makes it much easier to decipher.
    You have:EXECUTE IMMEDIATE l_stmt into tbl_count using to_char(in_date, 'DD-MON-YYYY') ;
    Where it should be:EXECUTE IMMEDIATE l_stmt into tbl_count using TRUNC(in_date) ;
    Additionally, you do not need the SQL script, you could simply have:sqlplus -S $ORA_UID/$ORA_PWD@$DSQuery <<EOF >>${TMP_DIR}/report.log 2>&1
    whenever sqlerror exit failure
    whenever oserror exit failure
    set serveroutput on;
    set pages 0;
    set feed off;
    exec return_date ('20090515','STIFAPACDTR','ASOFD','n');
    print;
    quit
    EOF
    if [[ $? -ne 0 ]]
    then
    echo "sqlplus did not run successfully,verify"
    echo "For errors please check ${TMP_DIR}/report.log file\n Exiting..."
    else
    echo "$0 script executed successfully"
    fi
    exit $?
    You don't need any of this:if /usr/xpg4/bin/grep -e 'ORA-' -e '^ERROR at' -e 'unknown command' ${TMP_DIR}/report.log
    then
    print "sqlplus did not run successfully,verify"
    print "For errors please check ${TMP_DIR}/report.log file\n Exiting..."
    exit 1
    fi
    if [http:// -s ${TMP_DIR}/report.log ]
    then
    print "`echo $0 script executed successfully"
    grep -v '^$'${TMP_DIR}/report.log > ${TMP_DIR}/report.csv
    else
    print "${TMP_DIR}/report.log file not generated, verify, \n exiting"
    exit 1
    fi
    outFLAG="n"
    done
    I'm not sure that that will fix your problem here, but can you try again with those changes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Error while insert data using execute immediate in dynamic table in oracle

    Error while insert data using execute immediate in dynamic table created in oracle 11g .
    first the dynamic nested table (op_sample) was created using the executed immediate...
    object is
    CREATE OR REPLACE TYPE ASI.sub_mark AS OBJECT (
    mark1 number,
    mark2 number
    t_sub_mark is a class of type sub_mark
    CREATE OR REPLACE TYPE ASI.t_sub_mark is table of sub_mark;
    create table sam1(id number,name varchar2(30));
    nested table is created below:
    begin
    EXECUTE IMMEDIATE ' create table '||op_sample||'
    (id number,name varchar2(30),subject_obj t_sub_mark) nested table subject_obj store as nest_tab return as value';
    end;
    now data from sam1 table and object (subject_obj) are inserted into the dynamic table
    declare
    subject_obj t_sub_mark;
    begin
    subject_obj:= t_sub_mark();
    EXECUTE IMMEDIATE 'insert into op_sample (select id,name,subject_obj from sam1) ';
    end;
    and got the below error:
    ORA-00904: "SUBJECT_OBJ": invalid identifier
    ORA-06512: at line 7
    then when we tried to insert the data into the dynam_table with the subject_marks object as null,we received the following error..
    execute immediate 'insert into '||dynam_table ||'
    (SELECT

    887684 wrote:
    ORA-00904: "SUBJECT_OBJ": invalid identifier
    ORA-06512: at line 7The problem is that your variable subject_obj is not in scope inside the dynamic SQL you are building. The SQL engine does not know your PL/SQL variable, so it tries to find a column named SUBJECT_OBJ in your SAM1 table.
    If you need to use dynamic SQL for this, then you must bind the variable. Something like this:
    EXECUTE IMMEDIATE 'insert into op_sample (select id,name,:bind_subject_obj from sam1) ' USING subject_obj;Alternatively you might figure out to use static SQL rather than dynamic SQL (if possible for your project.) In static SQL the PL/SQL engine binds the variables for you automatically.

  • Strange Case on Security Rights and Dynamic SQL (Execute Immediate)

    Hi friends, (forgive me if I write with wrong grammar and sentence, I not used English for daily)
    I got a weird trouble yesterday.
    I created a package (we can called it X, OK!?) which containing Execute Immediate Statement, that function to delete a table (we can called it Y).
    Several days ago, it's worked, but yesterday it wasn't. Last things happened before was recreate those table, and regrant to a role which including user account that execute package X.
    Error Msg shown is ORA-00942 : Table or view does not exist. After rechecked and rechecked, I found nothing that could trigger that error, I used DBMS_OUTPUT.PUT_LINE to debug and show what statement resulted and executed, I cut and paste, and it's worked. I created anonymous PL/SQL Block, and wrote it and executed it, and worked.
    Finally, today, We Grant explicitly those table to user account Y, not via Role, ... and it's work. Interesting thing I think :P
    And, I revoke, execute package and run. I think, there's something about Oracle he..he.. :D .
    Can somebody help me and explain me the reason of that strange symptomp? and right solution? I must know it, because several days again, it's launched / install.
    TIA

    Here is the procedure that get troubled into :)
    PROCEDURE DeleteOld_Job(
    p_Job_Code IN VARCHAR2,
    p_User_Id IN VARCHAR2,
    p_Parameter_Entry IN VARCHAR2,
    p_Status OUT NUMBER )
    IS
    StrSql VARCHAR2(1000);
    CURSOR CTable_Used_By_Report IS
    SELECT TABLE_NAME
    ,TABLE_OWNER
    FROM TABLE_USED_BY_JOB
    WHERE
    Job_Code = p_Job_Code
    BEGIN
    p_Status := 1;
    DBMS_OUTPUT.PUT_LINE('p_Job_Code '&#0124; &#0124;p_Job_Code );
    DBMS_OUTPUT.PUT_LINE('p_Parameter_Entry '&#0124; &#0124;p_Parameter_Entry );
    FOR Item IN CTable_Used_By_Report
    LOOP
    StrSql := 'DELETE '&#0124; &#0124;Item.TABLE_OWNER&#0124; &#0124;'.'&#0124; &#0124;Item.TABLE_NAME&#0124; &#0124;' T WHERE EXISTS ( SELECT 1 FROM USERBATCH.HISTORY_JOB H WHERE H.USER_ID = ' ;
    StrSql := StrSql&#0124; &#0124;''''&#0124; &#0124;p_User_Id&#0124; &#0124;''''&#0124; &#0124;' AND H.Job_Code = '&#0124; &#0124;''''&#0124; &#0124;p_Job_Code&#0124; &#0124;''''&#0124; &#0124;' AND H.PARAMETER_ENTRY = '&#0124; &#0124;'''' &#0124; &#0124;p_Parameter_Entry&#0124; &#0124;''''&#0124; &#0124;' AND T.SESSION_ID = H.TRANSACTION_ID)';
    DBMS_OUTPUT.PUT_LINE(StrSql);
    DBMS_OUTPUT.PUT_LINE(Item.TABLE_OWNER&#0124; &#0124;'.'&#0124; &#0124;Item.TABLE_NAME);
    EXECUTE IMMEDIATE StrSql;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('DELETE USERBATCH.HISTORY_JOB WHERE USER_ID ='''&#0124; &#0124; p_User_Id &#0124; &#0124;'''
    AND Job_Code ='''&#0124; &#0124; p_Job_Code &#0124; &#0124;''' AND PARAMETER_ENTRY = '''&#0124; &#0124; p_Parameter_Entry &#0124; &#0124;'''');
    EXECUTE IMMEDIATE 'DELETE USERBATCH.HISTORY_JOB WHERE USER_ID ='''&#0124; &#0124; p_User_Id &#0124; &#0124;'''
    AND Job_Code ='''&#0124; &#0124; p_Job_Code &#0124; &#0124;''' AND PARAMETER_ENTRY = '''&#0124; &#0124; p_Parameter_Entry &#0124; &#0124;'''';
    COMMIT;
    EXCEPTION
    WHEN OTHERS THEN
    ROLLBACK;
    p_Status := 0;
    DBMS_OUTPUT.PUT_LINE( SUBSTR(SQLERRM,1,255) );
    END DeleteOld_Job;
    TIA
    null

  • Execute immediate and dynamic sql

    Dear all;
    Just curious....Why do developers still use dynamic sql..and execute immediate, because I always thought dynamic sql were bads and the use of execute immediate as well...
    or am I missing something...

    There are no 'bad' things and 'good' things.
    There are 'correctly used' and 'incorrectly used' features.
    It depends what you want to do.
    One simple example: Oracle 11.2 - you write a package that fetches data from range interval partitioned table (a new partition is created automatically every day when new key values are inserted). If you use static SQL then whenever Oracle creates a new partition then your package gets invalidated and has to be compiled. If your package is heavily used (by many sessions running in parallel) then you may get this:
    ORA-04068: existing state of packages has been discarded
    ORA-04061: existing state of package body "PACKAGE.XXXXX" has been invalidated
    ORA-06508: PL/SQL: could not find program unit being called: "PACKAGE.XXXXX" Nice, isn't it?
    You can avoid this kind of problems by simply using dynamic SQL. You break dependency with the table and your package is not invalidated when new partition is created.

  • [Solved] Reference apex_application.g_fXX in "execute immediate" statement

    Hi!
    I created a dynamically generated tabular form - the number of columns is not known in advanced. Each cell of the form is a text item generated with apex_item.text().
    I want to write an after-submit process that saves the values from the form into a database table. In this process I already know how many columns there are in the report so I want to do the following:
    --for each row...
    for i in 1..apex_application.g_f01.count loop
      -- and for each column in that row (number of columns is in v_col_count)
      for j in 1..v_col_count loop
        -- get the value of text item
        v_query := 'select apex_application.g_f0' || j || '(' || i || ')' || ' from dual';
        execute immediate v_query into v_value;
        -- now do some DML with v_value
      end loop;
    end loop;The problem is that I get an error: ORA-06553: PLS-221: 'G_Fxx' is not a procedure or is undefined where xx is the number from the generated query.
    My question is - am I doing something wrong or is is just not possible to reference apex_application.g_fxx in "execute immediate"? Will I have to manually check for all 50 possibilites of apex_application.g_fxx? Is there another way?
    TIA,
    Jure

    Well now I know what was wrong and what you were trying to tell me - apex_application.g_fxx is not visible in "plain" SQL. And now I also have a solution to this problem. The point is to wrap the select statement with begin - end block so that the statement is rendered as pl/sql:
    --for each row...
    for i in 1..apex_application.g_f01.count loop
      -- and for each column in that row (number of columns is in v_col_count)
      for j in 1..v_col_count loop
        -- get the value of text item
        v_query := 'begin select apex_application.g_f0' || j || '(:i)' || ' into :x from dual; end;';
        execute immediate v_query using i, out v_value;
        -- now do some DML with v_value
      end loop;
    end loop;This works great :).
    Jure

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

  • Error in execute immediate statement

    i am writing a stored procedure i am getting error
    v_Sql NVARCHAR2(1500);
    BEGIN
    v_Sql := 'Select * from vw_FillPatient Where 1 = 1 ';
    IF v_pVisitTypeID <> 0 THEN
    v_Sql := v_Sql || ' AND VisitTypeID = ' || CAST(v_pVisitTypeID AS VARCHAR2) || '';
    ELSE
    IF v_pVisitTypeID = 0 THEN
    v_Sql := v_Sql || ' AND VisitTypeID In (1,2,6)';
    END IF;
    END IF;
    v_Sql := v_Sql || ' AND VisitDate between ''' || TO_CHAR(v_pFromDate,'''DD_MON_YYYY''')
    || ''' and ''' || TO_CHAR(v_pToDate,'''DD-MON-YYYY''') || '''';
    v_Sql := v_Sql || ' ORDER BY VisitID ';
    EXECUTE IMMEDIATE v_Sql;-- error in this line as shown by SQL Developer
    end;
    error
    Error(64,22): PLS-00382: expression is of wrong type

    v_Sql NVARCHAR2(1500);
    BEGIN
      V_SQL := 'Select * from vw_FillPatient Where 1 = 1 ';
      IF V_PVISITTYPEID=0 THEN
        v_Sql := v_Sql || ' AND VisitTypeID = ''' || CAST(v_pVisitTypeID AS VARCHAR2) || '''';
      ELSE
        IF v_pVisitTypeID = 0 THEN
          v_Sql          := v_Sql || ' AND VisitTypeID In (1,2,6)';
        END IF;
      END IF;
      V_SQL :=
      V_SQL || ' AND VisitDate between  to_date(''' ||V_PFROMDATE||''',''DD-MON-YYYY'') and '
            ||  'to_date('''||v_pToDate||''',''DD-MON-YYYY'')';
      v_Sql := v_Sql || ' ORDER BY VisitID ';
      EXECUTE IMMEDIATE v_Sql;-- error in this line as shown by SQL Developer
    END;try it , please
    I think your V_PFROMDATE, and V_PTODATE is varchar
    elsif V_PFROMDATE and V_PTODATE id date then
    V_SQL || ' AND VisitDate between  to_date(''' ||to_char(V_PFROMDATE,'DD-MON-YYYY')||''',''DD-MON-YYYY'') and '
            ||  ' to_date('''||to_char(v_pToDate,'DD-MON-YYYY')||''',''DD-MON-YYYY'')';Edited by: Mahir M. Quluzade on Mar 1, 2011 11:15 AM
    Edited by: Mahir M. Quluzade on Mar 1, 2011 11:22 AM

  • Java Stored Procedure in EXECUTE IMMEDIATE

    Hi,
    I need advice for the following.
    I'm on Oracle 11g R2. I'm testing application in Oracle 11gR1 and R2 and Oracle Express.
    Purpose is to generate XML reports.
    I have PLSQL Stored Procedure which does that, but since there is bug in Oracle11gR2 related to XMLTRANSFORM I have and Java Stored Procedure which is workaround. They are both compiled, valid etc.
    Java class is :
    import java.io.PrintWriter;
    import java.io.Writer;
    import oracle.xml.parser.v2.DOMParser;
    import oracle.xml.parser.v2.XMLDocument;
    import oracle.xml.parser.v2.XSLProcessor;
    import oracle.xml.parser.v2.XSLStylesheet;
    * This class is used as Java stored procedure
    * There is a bug on Oracle11gR2, related to the limitation on the number of style sheet instructions
    * This stored procedure is workaround when PLSQL code can not be used.
    * File must not have package, otherwise is wrongly compiled in DB
    public class JavaXslt {
         public static void XMLTtransform(oracle.sql.CLOB xmlInput,oracle.sql.CLOB xslInput,oracle.sql.CLOB output) throws Exception{
              DOMParser parser;
              XMLDocument xml;
              XMLDocument xsldoc;
              try{
                   parser = new DOMParser();
                   parser.parse(xmlInput.getCharacterStream());
                   xml = parser.getDocument();
                   parser.parse(xslInput.getCharacterStream());
                   xsldoc = parser.getDocument();
                   XSLProcessor processor = new XSLProcessor();
                   XSLStylesheet xsl = processor.newXSLStylesheet(xsldoc);
                   Writer w = output.setCharacterStream(1L);
                   PrintWriter pw = new PrintWriter(w);
                   processor.processXSL(xsl, xml, pw);
              }catch (Exception ex){
                   throw ex;
    PROCEDURE Java_XmlTransform (xml CLOB, xslt CLOB, output CLOB) AS LANGUAGE JAVA
    NAME 'JavaXslt.XMLTtransform(oracle.sql.CLOB, oracle.sql.CLOB, oracle.sql.CLOB)';
    I'm calling Java stored procedure from PLSQL Stored procedure (if it is Oracle11gR2) like that :
    Java_Proc.Java_XmlTransform(inputXML, xslt, res);
    So till here everything works ok. XSLT as applied and output XML (res) is OK.
    But when Oracle Express is used Java is out of the question, so there is no Java stored procedure. Howewer PLSQL Stored procedure is still needed.
    So I had to put call to Java Stored procedure in EXECUTE IMMEDIATE statement in order to compile to PLSQL package.
    But when I do that :
    EXECUTE IMMEDIATE 'BEGIN Java_Proc.Java_XmlTransform (:1, :2, :3); END;' USING inputXML, xslt, res;
    result value CLOB (res) has zero length...
    What am I missing? Should i set return value to Java class?
    Hope my explanations are clear though.
    Thanks

    Hi odie_63,
    Thanks for quick response.
    I didn't clearly explained.
    When using Oracle 11gR1 and Oracle Express I'm using only PLSQL Procedure.
    When using Oracle 11gR2 i have to use Java Stored procedure because there is documented bug in R2.
    That's why i have to use EXECUTE IMMEDIATE. I don't know which version is the client DB and whether there is or no Java procedures.
    I did tried
    EXECUTE IMMEDIATE 'BEGIN Java_Proc.Java_XmlTransform (:1, :2, :3); END;' USING IN inputXML, IN xslt, OUT res; and the result was ORA-06537: OUT bind variable bound to an IN position
    When using IN OUT for last parameter i.e.
    EXECUTE IMMEDIATE 'BEGIN Java_Proc.Java_XmlTransform (:1, :2, :3); END;' USING IN inputXML, IN xslt, IN OUT res;
    there is no exception, but still DBMS_LOB.getlength(res) = 0
    Thanks

Maybe you are looking for

  • Error message for export to PDF in CS3 after os upgrade

    I upgraded my Mac o/s to 10.6.8 -Snow Leopard - Now CS3 gives me an error when I try to export a file to PDF that says"PDF library failed to initialize" Adobe says that CS3 is compatible with snow leopard, but they don't troubleshoot CS3 anymore. Any

  • Oracle 9.2.0.8 Binary Data Problem

    Hi Folks, need some advice from the experts here about an error I got yesterday while installing a (Java-based) Software at a customer using Oracle 9.2.0.8. While being able to work with the database most of the time, I get an error when trying to sa

  • Has anyone had to restore ipod touch 5g

    i bought a blue ipod touch 5g 64gb on november 30th on ebay brand new sealed in box and got it on december 3rd.  i have reset it to factory settings atleast 3 times because after putting some songs on it and after a few days i go to play a particular

  • Change data capture - ignore delete?

    Hello, I'm trying to solve an issue I met on a synchronous change data capture : I created a CDC table with the DBMS_LOGMNR_CDC_PUBLISH.CREATE_CHANGE_TABLE procedure: BEGIN    DBMS_LOGMNR_CDC_PUBLISH.CREATE_CHANGE_TABLE (       OWNER             => '

  • Nokia 5310 service provider BSNL not listed in Net...

    I have 5310 xpress music and trying to connect/activate Email and my service provider is BSNL. While choosing the Network, BSNL is not listed. Request someone can assist in this matter. I have installed PC suite software in my PC. Thanks P.Selvakumar