Why or When should we use Execute Immediate in PLSQL??

Hi Frnds,
Long Ago i have received a interview question that ...
How can U create a table in the PLSQL object(Function or procedure)?
But the thing y should we use execute immediate?
In which scenario we should we should use????????????
Why or When should we use Execute Immediate in PLSQL????

OR
http://stackoverflow.com/questions/18375990/oracle-what-does-execute-immediate-means
For DML you'd use it when running statements that you don't have available at compile time, e.g. if the column list is based on a selection from the user.
In your case it's being used because DDL cannot be run as static SQL from within PL/SQL. Only certain query, DML and TCL commands are valid. Anything else has to be treated as dynamic.
I'd say it's rare to need to use DDL from a PL/SQL block. TRUNCATE might be reasonable; if you find anything creating or dropping objects on the fly then that might be more of a concern as it can suggest a suboptimal data model.
EXECUTE IMMEDIATE itself does not automatically commit; but if you execute DDL then that will behave the same as if you ran it outside PL/SQL, so it will commit in your case, yes.
Incidentally, I'm not sure why your code is using an intermediate variable to hold the statement; that's useful if you want to display what it's going to run maybe, but you don't seem to be doing that. What you have could be done as:
EXECUTE IMMEDIATE 'TRUNCATE TABLE BD_BIDS_EXT_DET';
Thank you

Similar Messages

  • Using Execute Immediate in PLSQL block Vs Stand alone procedure

    I am facing very unusual ( atleast unusual to me ) with usage of "Execute Immediate" statement.
    I have a table dynamic_sql with one column plsql_block as VARCHAR2(4000);
    I have stored some PLSQL blocks ('DECLARE ..... BEGIN.... END.... ) in this column .
    Now I want to execute these PLSQL blocks one after other depending on certain conditions .
    In order to archive this I wrote a PLSQL block as below
    DECLARE
    Cursor c1 is
    select plsql_block from dynamic_sql
    begin
    for irec in c1
    loop
    <<< Condition >>>
    begin
    execute_immediate(irec.plsql_block);
    exception
    when others then
    raise_application_error(-20001,'error ' ||irec.plsql_block||' '||sqlerrm);
    end loop ;
    end ;
    With above PLSQL block , "execute immediate" is executing PLSQL block successfully without any error
    But When I converted above PLSQL block into standalone procedure as shown below , I am getting error .
    CREATE OR REPLACE procedure test AS
    Cursor c1 is
    select plsql_block from dynamic_sql
    begin
    for irec in c1
    loop
    <<< Condition >>>
    begin
    execute_immediate(irec.plsql_block);
    exception
    when others then
    raise_application_error(-20001,'error ' ||irec.plsql_block||' '||sqlerrm);
    end loop ;
    end ;
    BEGIN
    test;
    end ;
    It is showing the value of irec.plsql_block but not showing sqlerrm...
    I found this is very unusual as I am able to execute "execute immediate" statement with PLSQL block but not with similar procedure .
    can anybody explain me why this is happening?
    Thanks in Advance
    Amit

    Hello,
    It doesn't make any sense to add SQLERRM for user defined exception, unless you want to raise application error for already defined error (e.g NOT_DATA_FOUND, ..)
    Check following piece of code and its output,
    CREATE OR REPLACE PROCEDURE myinsert1
    AS
       v_count   NUMBER;
       v_sql     VARCHAR2 (300);
    BEGIN
       v_sql :=
          'INSERT INTO ENTITY_EMPLOYEE VALUES(0,''TIM'',''LASTNAME'',10000)';
       BEGIN
          EXECUTE IMMEDIATE v_sql;
          COMMIT;
       EXCEPTION
          WHEN OTHERS
          THEN
             DBMS_OUTPUT.PUT_LINE (SUBSTR (SQLERRM, 1, 300));
             RAISE_APPLICATION_ERROR (-20002, 'My Error ' || SQLERRM, TRUE);
             RAISE;
       END;
    END;
    Output._
    ORA-20002: My Error ORA-00001: unique constraint (ENTITY_EMPLOYEE_PK) violated
    ORA-06512: at "MYINSERT1", line 21
    ORA-00001: unique constraint (ENTITY_EMPLOYEE_PK) violated
    ORA-06512: at line 2
    Regrds

  • Have problem when using EXECUTE IMMEDIATE.

    Hi, i'm new here... i having problem when trying to use execute immediate statement... :(
    procedure code as below:
    create procedure copy_row(
    p_table varchar2,
    p_key varchar2,
    p_keyval varchar2,
    p_user varchar2,
    p_frmto varchar2 default 'FROM')
    IS
    V_SQL VARCHAR2(500);
    BEGIN
    if upper(p_frmto)='FROM' then
    V_SQL:='INSERT INTO '||P_TABLE||
    ' SELECT * FROM '||P_USER||'.'||P_TABLE||' WHERE '||P_KEY||' = '''||P_KEYVAL||'''';
    elsif upper(p_frmto)='TO' then
    V_SQL:='INSERT INTO '||P_USER||'.'||P_TABLE||
    ' SELECT * FROM '||P_TABLE||' WHERE '||P_KEY||' = '''||P_KEYVAL||'''';
    end if;
    EXECUTE IMMEDIATE V_SQL;
    exception
    when others then
    raise_application_error(-20000,'PROCEDURE: COPY_ROW - UNABLE TO COPY ROWS! SQL='||V_SQL,TRUE);
    end;
    is there any limitation on using EXECUTE IMMEDIATE command? i need to use procedure because i'm using old form builder.... but the database server was 9i which able to use this command, so... i decide to use procedure....
    i've done some testing on this.... assume the structure of schema1.table1 and schema2.table1 are same....
    SQL> CREATE PROCEDURE TESTING IS
    2 BEGIN
    3 exeCute IMMEDIATE 'INSERT INTO schema1.table1 SELECT * FROM schema2.table1 WHERE column1 = ''abc''';
    4 END;
    5 /
    Procedure created.
    SQL> BEGIN
    2 TESTING;
    3 END;
    4 /
    BEGIN
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at "SCHEMA1.TESTING", line 3
    ORA-06512: at line 2
    any idea?? or have better solution other than this?
    database server:9i
    sqlplus:SQL*Plus: Release 8.0.6.0.0

    Do you have an access to tables you are going to insert into / select from ?
    Dynamic SQL checks the access permissions at runtime, not at the compilation stage:
    SQL> create user master identified by master default tablespace users temporary
      2  tablespace temp;
    User created.
    SQL> alter user master quota unlimited on users;
    User altered.
    SQL> grant create session to master;
    Grant succeeded.
    SQL> grant create table to master;
    Grant succeeded.
    SQL> grant create procedure to master;
    Grant succeeded.
    SQL> conn master/master
    Connected.
    SQL> create procedure wrong_prc
      2  is
      3  begin
      4   execute immediate 'insert into master.t select * from scott.t';
      5  end;
      6  /
    Procedure created.
    SQL> create table t (id number);
    Table created.
    SQL> exec wrong_prc;
    BEGIN wrong_prc; END;
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at "MASTER.WRONG_PRC", line 4
    ORA-06512: at line 1
    SQL> conn scott/tiger
    Connected.
    SQL> grant select on t to master;
    Grant succeeded.
    SQL> conn master/master
    Connected.
    SQL> exec wrong_prc;
    PL/SQL procedure successfully completed.
    SQL> select * from t;
            ID
             1And don't use literals in dynamic SQL - you should use binding variables instead.
    Rgds.

  • Delete From More than 1 table without using execute immediate

    Hi,
    Am new to PL/SQL, I had been asked to delete few of the table for my ETL jobs in Oracle 10G R2. I have to delete(truncate) few tables and the table names are in another table with a flag to delete it or not. So, when ever I run the job it should check for the flag and for those flag which is 'Y' then for all those tables should be deleted without using the Execute Immediate, because I dont have privilages to use "Execute Immediate" statement.
    Can anyone help me in how to do this.
    Regards
    Senthil

    Then tell you DBA's, or better yet their boss, that they need some additional training in how Oracle actually works.
    Yes, dynamic sql can be a bad thing when it is used to generate hundreds of identical queries that differ ony in the literals used in predicates, but for something like a set of delte table statements or truncate table statements, dynamic sql is no different in terms of the effect on the shared pool that hard coding the sql statements.
    This is a bad use of dynamic sql, because it generates a lot of nearly identical statements due to the lack of bind variables. It is the type of thing your DBA's should, correctly, bring out the lead pipe for.
    DECLARE
       l_sql VARCHAR2(4000);
    BEGIN
       FOR r in (SELECT account_no FROM accounts_to_delete) LOOP
          l_sql := 'DELETE FROM accounts WHERE account_no = '||r.account_no;
          EXECUTE IMMEDIATE l_sql;
       END LOOP;
    END;This will result in one sql statement in the shared pool for every row in accounts_to_delete. Although there is much else wrong with this example, from the bind variable perspective it should be re-written to use bind variables like:
    DECLARE
       l_sql  VARCHAR2(4000);
       l_acct NUMBER;
    BEGIN
       FOR r in (SELECT account_no FROM accounts_to_delete) LOOP
          l_sql := 'DELETE FROM accounts WHERE account_no = :b1';
          EXECUTE IMMEDIATE l_sql USING l_acct;
       END LOOP;
    END;However, since you cannot bind object names into sql statements, the difference in terms of the number of statements that end up in the shared pool between this:
    DECLARE
       l_sql VARCHAR2(4000);
    BEGIN
       FOR r in (SELECT table_name, delete_tab, trunc_tab
                 FROM tables_to_delete) LOOP
          IF r.delete_tab = 'Y' THEN
             l_sql := 'DELETE FROM '||r.table_name;
          ELSIF r.trunc_tab = 'Y' THEN
             l_sql := 'TRUNCATE TABLE '||r.table_name;
          ELSE
             l_sql := NULL;
          END IF;
          EXECUTE IMMEDIATE l_sql;
       END LOOP;
    END;and something like this:
    BEGIN
       DELETE FROM tab1;
       DELETE FROM tab2;
       EXECUTE IMMEDIATE 'TRUNCTE TABLE tab3';
    END;or this as a sql script
    DELETE FROM tab1;
    DELETE FROM tab2;
    TRUNCTE TABLE tab3;is absolutley nothing.
    Note that if you are truncating some of the tables, and wnat/need to use a stored procedure, you are going to have to use dynamic sql for the truncates anyway since trncate is ddl, and you cannot do ddl in pl/sql wiothout using dynamic sql.
    John

  • How to use Execute Immediate to execute a procedure and return a cursor?

    The procedure name is unknown until run time so I have to use Execute immediate to execute the procedure, the procedure return a cursor, but I can't figure out the right syntax to pass the cursor out.
    To simplify the issue here, I create two procedures as examples.Assume I have a procedure called XDTest:
         p_cur OUT SYS_REFCURSOR
    IS
    BEGIN
    OPEN p_cur FOR
    Select * from dummy_table;
    END XDTest;
    In another procedure, I want to use Execute Immediate to execute XDTest and obtain the result that return from the cursor into a local cursor so I can process the records:
         p_cur OUT SYS_REFCURSOR
    IS
    l_cur SYS_REFCURSOR;
    BEGIN
    execute immediate 'BEGIN XDTest (:1); END;' using OUT l_cur;
    END XDTest2;
    However, this is not working, I get ORA-03113: end-of-file on communication channel error.
    What syntax should I use here?
    Cheers

    well...
    I update the XDTest2 procedure as below but when execute it get exceptions.I think the v_sqlstmt syntax is wrong, but I don't know what meant to be correct, please give some suggestions .
    Cheers
    -------------------- XDTest procedure --------------------------------------------------
         p_cur OUT SYS_REFCURSOR
    --AUTHID CURRENT_USER
    IS
    BEGIN
    OPEN p_cur FOR
    Select Table_Name from USER_Tables;
    END XDTest;
    -------------------- XDTest2 procedure --------------------------------------------------
         p_cur OUT SYS_REFCURSOR
    IS
    TYPE T1 IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER ;
    v_sqlstmt varchar2(1000):=null;
    v_cursor number;
    x_num number;
    LN$Lig number := 0 ;
    LN$MaxCol number := 0 ;
    t T1 ;
    v VARCHAR2(4000) ;
    userTb User_Tables%ROWTYPE;
    l_cur number;
    BEGIN
    LN$Lig := 0 ;
    LN$MaxCol := 1 ;
    --OPEN p_cur FOR
    --execute immediate 'BEGIN XDTest (:1); END;' using OUT l_cur;
    v_cursor:=dbms_sql.open_cursor;
    v_sqlstmt:='begin :p_cur:="XDTest"(); END; ';
    dbms_sql.parse(v_cursor,v_sqlstmt,DBMS_SQL.NATIVE);
    dbms_sql.bind_variable(v_cursor,':p_cur',l_cur);
    dbms_output.put_line('1');
    -- Define the columns --
    dbms_sql.DEFINE_COLUMN(v_cursor, 1, userTb.Table_Name, 30);
    x_num:=dbms_sql.execute(v_cursor);
    dbms_output.put_line('2');
    -- Fetch the rows from the source query --
    LOOP
    IF dbms_sql.FETCH_ROWS(v_cursor)>0 THEN
    -- get column values of the row --
    dbms_sql.COLUMN_VALUE(v_cursor, 1,userTb.Table_Name);
    dbms_output.put_line(userTb.Table_Name);
    ELSE
    -- No more rows --
    EXIT;
    END IF;
    END LOOP;
    dbms_sql.close_cursor(v_cursor);
    END XDTest2;
    ---------------------- Error when execute ------------------------------------------------
    1
    BEGIN DevD0DB.XDTest2(:l_cur); END;
    ERROR at line 1:
    ORA-01007: variable not in select list
    ORA-06512: at "SYS.DBMS_SYS_SQL", line 1010
    ORA-06512: at "SYS.DBMS_SQL", line 212
    ORA-06512: at "DEVD0DB.XDTEST2", line 35
    ORA-06512: at line 1
    ----------------------------------------------------------------------------------------------------

  • What are the mapfiles for and when should I use them?

    Hi,
    what are the map files for and why/when should I use them?
    /usr/lib/ld/map.noexstk
    usr/lib/ld/map.noexbss
    /usr/lib/ld/map.noexdata
    /usr/lib/ld/map.pagealign

    Hi, I'm sure you've read the comments, but for the benefit of those who haven't: /usr/lib/ld/map.noexstk # Linker mapfile to create a non-executable stack definition within an # executable. /usr/lib/ld/map.noexbss # Link-editor mapfile to create a non-executable bss segment definition # within an executable. /usr/lib/ld/map.noexdata # Link-editor mapfile to create a non-executable data segment definition # within an executable. These stop the various segments from being executable. Which could reduce the risk surface for exploiting security holes in an application. /usr/lib/ld/map.pagealign # Linker mapfile to create page-aligned data within an executable. Aligning the start of the data segment can reduce the number of TLB entries needed to map the data. So the smallest TLB page size is 8KB, then we have 64KB, then 4MB etc. If the data starts on a 4MB boundary then it can be mapped with 4MB pages, if not then it has to be mapped with 8KB pages until a 64KB boundary, then 64KB pages until we get to a 4MB boundary. You sometimes get a bit of performance from this, but you may also get performance stability from it. If the mapping is random sometimes it works well, sometimes it works less well. Regards, Darryl.

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

  • Selecting data from a table using Execute Immediate in 9i

    Hi,
    I was wondering how I would be able to do a SELECT on a table using EXECUTE IMMEDIATE. When I tried it (with the proc below), I got the following below. Can anyone tell me what I am doing wrong?
    Using Scott/Tiger I tried this:
    SQL> ed
    Wrote file afiedt.buf
    1 CREATE OR REPLACE PROCEDURE P2
    2 IS
    3 v_SQL VARCHAR2(100);
    4 BEGIN
    5 v_SQL := 'Select * from Emp';
    6 EXECUTE IMMEDIATE v_SQL;
    7* END;
    SQL> /
    Procedure created.
    SQL> exec p2
    PL/SQL procedure successfully completed.
    SQL> set serveroutput on
    SQL> exec p2
    PL/SQL procedure successfully completed.
    SQL>
    Thanks in advance.
    Sincerely,
    Nikhil Kulkarni

    1 CREATE OR REPLACE PROCEDURE P2
    2 IS
    3 v_SQL VARCHAR2(100);
    erec emp%rowtype;
    4 BEGIN
    5 v_SQL := 'Select * from Emp';
    6 EXECUTE IMMEDIATE v_SQL into erec;
    7* END;
    SQL> /

  • Oracle 11G Copying a table using execute immediate

    I want to copy the contents of one table into another using execute immediate.
    This keeps failing with the following error
    ORA-00903: invalid table name
    ORA-06512: at "TABLE_COPY", line 6
    ORA-06512: at line 8
    create or replace
    procedure TABLE_COPY(
    TABLE1 varchar2,
    TABLE2 varchar2)
    is
    begin
    execute immediate 'insert into '||TABLE2||' (select * from '||TABLE1||')';
    end;
    Edited by: user9213000 on 24-Jan-2013 07:38

    user9213000 wrote:
    I want to copy the contents of one table into another using execute immediate.
    This keeps failing with the following error
    ORA-00903: invalid table name
    ORA-06512: at "TABLE_COPY", line 6
    ORA-06512: at line 8
    create or replace
    procedure TABLE_COPY(
    TABLE1 varchar2,
    TABLE2 varchar2)
    is
    begin
    execute immediate 'insert into '||TABLE2||' (select * from '||TABLE1||')';
    end;
    Edited by: user9213000 on 24-Jan-2013 07:38The standard advice when (ab)using EXECUTE IMMEDIATE is to compose the SQL statement in a single VARCHAR2 variable
    Then print the variable before passing it to EXECUTE IMMEDIATE.
    COPY the statement & PASTE into sqlplus to validate its correctness.

  • Using EXECUTE IMMEDIATE with an NVARCHAR2 parameter

    Hi everyone,
    In the system I'm working on, my stored procedure receives an NVARCHAR2 parameter which contains a complete SQL statement. e.g.
    'UPDATE SomeTable SET SomeTable.Value = 0'
    I want to be able to execute this dynamically, using EXECUTE IMMEDIATE, but I've encountered a problem where this is apparently not supported (because the string is Unicode).
    It is crucial that the string stays as Unicode, because of the data that may possible be baked into the SQL statement, and so casting it off to a VARCHAR2, or changing the parameter type, is not acceptable.
    Is there a work-around for this issue? Even if it has a performance hit, it will be better than nothing :)
    I've tried something like this;
    declare
    myVal VARCHAR2(256);
    begin
    myVal := 'UPDATE SomeTable SET SomeTable.Value = 2';
    execute immediate 'BEGIN :x; END;' using myVal;
    end;
    But I get an error;
    "bind variable 'X' not allowed in this context"
    Has anyone any ideas?
    Thanks for your help,
    Chris

    uhmm, I'm not sure if this is a valid testcase. the string could still be converted into ascii or we8iso8859p1 or whatever 1byte-character set you want.
    What I think you should test is a two-byte character as part of SQL, PL/SQL resp. as in SQL all words are defined you can not enlarge it with a 2byte word. But in PL/SQL you could define your own variable. If this variable name itself contains a 2byte character, I guess it will fail.
    (I have used l_vär and l_vér as variable names in my example)
    Message was edited by:
    Leo Mannhart
    According to the PL/SQL Reference Guide PL/SQL consists of:
    PL/SQL programs are written as lines of text using a specific set of characters:
    Upper- and lower-case letters A .. Z and a .. z
    Numerals 0 .. 9
    Symbols ( ) + - * / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ]
    Tabs, spaces, and carriage returns
    This seems no longer up-to-date as I could define a variable l_vär for instance as long as I use a 1byte char set (like iso8859p1). The same variable name as a n-byte char set like UTF-8 will give an error as my example shows.

  • Why and when can I use the "NotBoundException" in my RMI?

    why and when can I use the "NotBoundException" in my RMI?

    The answer to this is contained in the documentation which you should have read before posting to this forum.

  • CREATE TEMPORARY TABLE USING EXECUTE IMMEDIATE

    Hi All,
    i have a question,
    how can i create a temporary table using EXECUTE IMMEDIATE ??
    Like:
    CREATE GLOBAL TEMPORARY table new_table as (Select * from old_table);
    Thanks,
    Edited by: xDeviates on Jun 11, 2012 3:13 PM

    It looks like you are approaching the problem incorrectly. As I suggested in Dynamic Select, it sounds like you, at most, want a function that returns a SYS_REFCURSOR (it's still not obvious to me why you would even want/ need to resort to dynamic SQL in the first place)
    CREATE OR REPLACE FUNCTION get_dynamic_cursor( p_table_name IN VARCHAR2 )
      RETURN sys_refcursor
    IS
      l_rc sys_refcursor;
    BEGIN
      OPEN l_rc FOR 'SELECT * FROM ' || dbms_assert.sql_object_name( p_table_name );
      RETURN l_rc;
    END;which you can then call from your application
    SQL> variable rc refcursor;
    SQL> exec :rc := get_dynamic_cursor( 'EMP' );
    PL/SQL procedure successfully completed.
    SQL> print rc
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        801
            20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1601        300
            30
          7521 WARD       SALESMAN        7698 22-FEB-81       1251        500
            30
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7566 JONES      MANAGER         7839 02-APR-81       2976
            20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1251       1400
            30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2851
            30
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7782 CLARK      MANAGER         7839 09-JUN-81       2451
            10
          7788 SCOTT      ANALYST         7566 19-APR-87       3001
            20
          7839 KING       PRESIDENT            17-NOV-81       5001
            10
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7844 TURNER     SALESMAN        7698 08-SEP-81       1501          0
            30
          7876 ADAMS      CLERK           7788 23-MAY-87       1101
            20
          7900 JAMES      CLERK           7698 03-DEC-81        951
            30
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7902 FORD       ANALYST         7566 03-DEC-81       3001
            20
          7934 MILLER     CLERK           7782 23-JAN-82       1301
            10
    14 rows selected.Justin

  • How to use execute immediate for character string value 300

    how to use execute immediate for character string value > 300 , the parameter for this would be passed.
    Case 1: When length = 300
    declare
    str1 varchar2(20) := 'select * from dual';
    str2 varchar2(20) := ' union ';
    result varchar2(300);
    begin
    result := str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || ' ';
    dbms_output.put_line('length : '|| length(result));
    execute immediate result;
    end;
    /SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
    length : 300
    PL/SQL procedure successfully completed.
    Case 2: When length > 300 ( 301)
    SQL> set serveroutput on size 2000;
    declare
    str1 varchar2(20) := 'select * from dual';
    str2 varchar2(20) := ' union ';
    result varchar2(300);
    begin
    result := str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || str2 ||
    str1 || ' ';
    dbms_output.put_line('length : '|| length(result));
    execute immediate result;
    end;
    /SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
    declare
    ERROR at line 1:
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    ORA-06512: at line 6

    result varchar2(300);Answer shouldn't be here ? In the greater variable ?
    Nicolas.

  • Using EXECUTE IMMEDIATE with XML

    Database version : 10.2.0.3.0 - 64bi
    Hi All,
    I have a xml which is stored in a table, xmltype column.
    i have target insert tables whose column names and xml nodes are same.
    using all_tab_columns table i will generate columns to be passed to xmltable.
    all these data i will store in variables and finally pass to xmltable as below
    just want to know using execute immediate is good to use in XML?
    SQL_STMT := 'insert into '||table_name|| ' ( '||V_COLUMN_NAME||')';
    SQL_STMT := SQL_STMT ||' SELECT ' ||V_XTAB_COLUMN_NAME ||
    ' FROM TO_XML,
    XMLTABLE(' ||v_xpath||
    'PASSING XML_VALUE
    columns ' || V_COLUMNS_DATA_TYPE
    ||') XTAB
    WHERE Seq_NO = ' || P_SEQUENCE_NO ;
    EXECUTE IMMEDIATE SQL_STMT ;
    Thanks and Regards,
    Rubu

    1) is it OK? As I stated above, it can be made to work. It would not be my first choice, but then none of us here know the full details as well as you do so maybe there is a compelling reason to use dynamic SQL.
    Here is the documentation for [url http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/executeimmediate_statement.htm#LNPLS01317]EXECUTE IMMEDIATE.
    Actually now I finally realize your XML resides in table TO_XML so that means you won't be putting the actual XML into the shared pool via an incorrectly written dynamic SQL statement at least. That is what Odie and I were first concerned about with dynamic SQL usage, that the XML would be hard-coded into your SQL_STMT variable. You are simply changing the columns (in 3 locations). With that setup, you have no need for (nor can use) bind variables. The overall issue of dynamic SQL being slightly slower than static SQL still exists as the SQL statement will first have to be parsed and validated.
    A larger issue in terms of performance is how 10.2 handles XMLTypes. If the underlying XML is large, XMLTable performance degrades quickly. Options around this are to parse the XML in PL/SQL or to upgrade to some version of 11 and use SECUREFILE BINARY XML as the underlying storage structure for the TO_XML.XML_VALUE column.

  • Problem in Update statement using Execute Immediate

    Hi All,
    I am facing problem in update statement.
    I am creating dynamic sql and use "execute immediate" statement to execute a update statement.
    But it is not updating any thing there in the table.
    I have created a query like :
    update_query='Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
    Execute immediate update_query using V_Id;
    commit;
    But it is not updating the table.
    I have a question , is execute immediate only does insert and delete?
    Thanks
    Ashok

    SQL> select * from t;
                     TID P
                     101 N
    SQL> declare
      2     V_Id          number := 101;
      3     Table_Name    varchar2(30) := 'T';
      4     update_query  varchar2(1000);
      5  begin
      6     update_query := 'Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
      7     Execute immediate update_query using V_Id;
      8     commit;
      9  end;
    10  /
    PL/SQL procedure successfully completed.
    SQL> select * from t;
                     TID P
                     101 Y                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for