Job\execute immediate

Hi all
I now the problem is in usage of quates is problem in the code given below. Pls help me to rewrite it.
DECLARE
A BINARY_INTEGER;
BEGIN
DBMS_JOB.SUBMIT (
job=>A,
what=>'BEGIN EXECUTE IMMEDIATE 'CREATE TABLE EM_ERROR_DET AS
SELECT * FROM DM_ERROR_DET WHERE TRUNC(JOBSTARTTIMESTAMP)
>= ADD_MONTHS(TRUNC(SYSDATE,'YYYY') ,- 12)'; END;'
,NEXT_DATE=>SYSDATE);
DBMS_OUTPUT.PUT_LINE(A);
END;
ERROR at line 6:
Encountered the symbol "CREATE" when expecting one of the following:
Thanks in advance
jaggyam
Message was edited by:
jaggyam

DECLARE
   a   BINARY_INTEGER;
BEGIN
   DBMS_JOB.submit
      (job            => a,
       what           => 'BEGIN
                            EXECUTE IMMEDIATE ''CREATE TABLE EM_ERROR_DET AS
                                SELECT * FROM DM_ERROR_DET
                                  WHERE TRUNC(JOBSTARTTIMESTAMP) >= ADD_MONTHS(TRUNC(SYSDATE,''YYYY'') ,- 12)'';
                          END;',
       next_date      => SYSDATE
   DBMS_OUTPUT.put_line (a);
END;

Similar Messages

  • Execute immediate -- udpate statement

    Hello,
    I am fairly new to scripting sql..pl/sql.. any help will be really appreciated!!
    I have a table where i am trying to update one of the column with table name i am passing dynamically.
    However i get the invalid identifier error. ORA-00904. The column AD.MIR_PARENT i am updating is of compatible data type.
    Any help please.. where i am doing a mistake..
    fyi -- the reason i am updating the column with table name is because i need to know which table i make a hit.
    DECLARE
    p_table varchar2(200);
    P_SCHEMA varchar2(200);
    p_acct NUMBER;
    v_acct NUMBER;
    P_column varchar2(200);
    cursoR c is
    select schema_name, table_name, column_name from addnl_sources where TABLE_NAME = 'ACCT';
        BEGIN
            FOR R IN C LOOP
                                    p_TABLE := R.TABLE_NAME;
                                    P_SCHEMA := R.SCHEMA_NAME;
                                    P_column := R.column_name;
                       execute immediate 'UPDATE ACCT_DELETE AD
                SET AD.MIR_PARENT = '||p_table || '
                WHERE EXISTS (select "'||p_table || '" from "' || P_SCHEMA||'"."'||p_table || '" where "' || P_column ||'" = ad.acct_id )
                AND AD.EXCLUDE IS NULL
                AND AD.ACCT_ID = 472039
                AND AD.MIR_PARENT IS NULL' ;
                            END LOOP;
        end;Edited by: 982806 on Jan 18, 2013 10:47 AM
    Edited by: 982806 on Jan 18, 2013 11:04 AM

    Welcome to the forum!
    Whenever you post provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION)
    >
    I am fairly new to scripting sql..pl/sql.. any help will be really appreciated!!
    I have a table where i am trying to update one of the column with table name i am passing dynamically.
    However i get the invalid identifier error. ORA-00904. The column AD.MIR_PARENT i am updating is of compatible data type.
    Any help please.. where i am doing a mistake..
    >
    Just about everything you are doing is a mistake.
    1. You using PL/SQL instead of SQL to do this job? That is usually a red flag that something is wrong about what you are trying to do or how you are trying to do it.
    2. You are 'fairly new to scripting' and have chosen to use dynamic sql? That is one of the harder techniques to learn and to use properly and is another red flag. Experienced professionals often don't use dynamic sql properly and often use it when they shouldn't.
    3. You are using a loop to execute against multiple tables? It is extremely difficult to perform proper error handling and recovery when you do this. What if some of the tables get updated and others don't? How will you know which ones still need to be updated? How will you roll back the data if you need to.
    4. You have opened a GIGANTIC opportunity for sql injection where the wrong tables could accidentally be updated. That could corrupt the data and reek havoc on the system. Anyone could, accidentally or intentionally, put the wrong schema, table or column in your lookup table and cause enormous damage.
    5. You are using double quotes in PL/SQL? Where did you learn that?
                WHERE EXISTS (select "'||p_table || '" from "' || P_SCHEMA||'"."'||p_table || '" where "' || P_column ||'" = ad.acct_id ) Finally, it is standard practice when you do have a use case for dynamic sql to construct the query in a variable and then print the query or write it to a log file so it can be tested independently.
    If you do that you will likely see your error.
    query VARCHAR2(4000);
    query := 'UPDATE . . .';
    execute immediate query;SUMMARY: don't try to automate something until you can first do it manually. Write a query that works properly first. Then, and only then, convert it to dynamic sql.

  • How to use using clause in execute immediate statement??

    Hi ALL,
    Can u help me ....
    This is the code which I have written...
    declare
    type rec_typ is table of forall_test%rowtype;
    v_rectype rec_typ:=rec_typ();
    begin
    --poputating records
    for i in 1..10000 loop
    v_rectype.extend;
    v_rectype(v_rectype.last).id:=i;
    v_rectype(v_rectype.last).code:=to_char(i);
    v_rectype(v_rectype.last).description:='Description :'||to_char(i);
    end loop;
    execute immediate 'truncate table forall_test';
    forall i in v_rectype.first..v_rectype.last
    execute immediate 'insert into forall_test values :1' using v_rectype(i);
    commit;
    end;
    But I am getting this ERROR....
    execute immediate 'insert into forall_test values :1' using v_rectype(i);
    ERROR at line 14:
    ORA-06550: line 14, column 61:
    PLS-00457: expressions have to be of SQL types
    ORA-06550: line 14, column 1:
    PL/SQL: Statement ignored
    Thanks & Regards,
    T.Halder

    Thatmeans using statement cannot be a non sql type.True: You need an sql type for this:
    e.g. with
    create or replace type emp_typ
    as
       object (empno number (4),
               ename varchar2 (10 byte),
               job varchar2 (9 byte),
               mgr number (4),
               hiredate date,
               sal number (7, 2),
               comm number (7, 2),
               deptno number (2))
    create or replace type emp_tab as table of emp_typ
    /you can do
    --- an empty test table
    SQL> create table emp2
    as
       select *
       from emp
       where 1 = 2
    Table created.
    SQL> declare
       emp2_tab       emp_tab;
    begin
      /* fill the collection */
       select emp_typ (empno,
                       ename,
                       job,
                       mgr,
                       hiredate,
                       sal,
                       comm,
                       deptno)
       bulk collect into emp2_tab
       from emp
       where empno like '77%';
      --  forall loop
       forall c in 1 .. emp2_tab.count
          execute immediate 'begin
                               insert into emp2 select * from table(cast(emp_tab(:1) as emp_tab)) t;
                               update emp2 set sal = null where empno = (:1).empno and empno = 7788;
                             end;' using emp2_tab (c);
    end;
    PL/SQL procedure successfully completed.
    SQL> select empno, ename, sal from emp2
         EMPNO ENAME             SAL
          7782 CLARK            2450
          7788 SCOTT               
    2 rows selected.

  • How to run a EXECUTE IMMEDIATE statement in a Interactive Report

    Hello all!!
    I need to make a dinamic construction of a query to execute in a Interactive Report, but the Region Source only allows simple SELECT statements. There is any way to run a EXECUTE IMMEDIATE statement in a Interactive Report Region Source?
    Regards Pedro.

    Thank you Andy for your reply.
    I have been testing for a while the use of a collection in the interactive report but i am unable to load data in the interactive report.
    I created the collection successfully in the SQL Commands with the code:
    declare
    v_sql varchar2(32000);
    begin
    v_sql:='select ename, job from emp';
    APEX_COLLECTION.CREATE_COLLECTION_FROM_QUERY('coleccao_emp',v_sql,'NO' );
    end;
    I tested successfully the creation of the collection with the query:
    SELECT c001, c002
    FROM APEX_collections
    WHERE collection_name = 'COLECCAO_EMP'
    My problem is: the data of the collection are returned in the SQL Commands but when i run the query statament in an interactive report, report or even a Pl/Sql region in my application the data aren't displayed, only the message (No data found).
    Can someone explain why, besides the collection is populated the interactive can not print the results.
    Regards Pedro.

  • Variable contents inside "EXECUTE IMMEDIATE" not working properly.

    Hello,
    I have the following package:
    CREATE OR REPLACE PACKAGE "BACKUP"."PKG_BACKUP"
    IS
    PROCEDURE BACKUP_TABLE (TABLE_NAME IN VARCHAR);
    END PKG_BACKUP;
    CREATE OR REPLACE PACKAGE BODY "BACKUP"."PKG_BACKUP"
    IS
    PROCEDURE BACKUP_TABLE (TABLE_NAME IN VARCHAR) IS
    MYDATE VARCHAR(10);
    BEGIN
    MYDATE := to_char(sysdate,'YYYYMMDD');
    DBMS_OUTPUT.PUT_LINE(' Backing up '||TABLE_NAME||' table...');
    EXECUTE IMMEDIATE 'CREATE TABLE "BACKUP"."'||TABLE_NAME||'_'||MYDATE||'" AS SELECT * FROM "MYSCHEMA"."'||TABLE_NAME||'" COMPRESSED';
    END backup_table;
    END "PKG_BACKUP";
    /However, every time I execute it I get the following error:
    SQL> exec BACKUP.PKG_BACKUP.BACKUP_TABLE('POOL');
    ** Backing up POOL table...*
    BEGIN BACKUP.PKG_BACKUP.BACKUP_TABLE('POOL'); END;
    ERROR at line 1:
    ORA-00942: table or view does not exist
    *ORA-06512: at "BACKUP.PKG_BACKUP
    ", line 9*
    *ORA-06512: at line 1*
    Table does exist and user executing the statement has the proper privileges (i've even executed the contents of "execute immediate" by hand and it works fine)
    What am I missing?
    Thanks in advance.

    SQL> CREATE OR REPLACE PACKAGE pkg_backup AUTHID CURRENT_USER
      2  IS
      3     PROCEDURE backup_table (table_name IN VARCHAR);
      4  END pkg_backup;
      5  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY PKG_BACKUP
      2  IS
      3     PROCEDURE backup_table (table_name IN VARCHAR)
      4     IS
      5        mydate   VARCHAR (10);
      6     BEGIN
      7        mydate := TO_CHAR (SYSDATE, 'YYYYMMDD');
      8        DBMS_OUTPUT.put_line (' Backing up ' || table_name || ' table...');
      9 
    10        EXECUTE IMMEDIATE 'CREATE TABLE BACKUP'||table_name||'_'||mydate||' AS SELECT * FROM '|| table_name || ' COMPRESSED';
    11     END backup_table;
    12  END PKG_BACKUP;
    13  /
    Package body created.
    SQL> EXEC PKG_BACKUP.backup_table('EMP');
    Backing up EMP table...
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM BACKUPEMP_20090130;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7788 SCOTT      ANALYST         7566 09-DEC-82       3000                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS      CLERK           7788 12-JAN-83       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
    14 rows selected.Edited by: user10594152 on Jan 30, 2009 5:18 PM
    Edited by: user10594152 on Jan 30, 2009 5:19 PM

  • 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

  • Execute Immediate. Insert from materialized view.

    Hi,
    I'm using Execute Immediate in a function to insert rows into a table. (Oracle 10G) The function in tern is used in a materialized view. So, effectively the view does an insert.
    When I just had a regular insert statment the view would not compile. When I changed the insert statment into the execute immediate it started working.
    Here are my questions:
    1. Do I need a commit or execute immediate does it automatically? When I create my view that calls the function it looks like the rows do get inserted as expected. But I couldn't find documentation that explains whether execute immediate does the commit.
    2. Is there a drawback to using execute immediate in a function that is used in a materialized view? Is there other way to insert rows from a materialized view? Can I call a stored procedure instead of a function in a materialized view?
    Your help is greatly appreciated.
    Thanks
    NK

    there are things that I'm not able to question yet :)It's a lot easier to write decent programs if we understand the why of the requirement as well as the what. I think you will create a better impression in your new job if you demonstrate some liveliness of thought and personality - by asking questions - rather than merely following orders.
    The question I proposed is not necessarily a hostile one (I can think of at least one good reason for doing what you've been asked to do). Broadening your knowledge of your new system is a good thing in its own right. But you never know, asking the right question may prevent you doing unnecessary work.
    Cheers, APC

  • EXECUTE IMMEDIATE ERROR ..

    Kidnly somebody suggest me how to wirte below query in execute immediate in pl/sql block as it throwing below error
    CREATE OR REPLACE PROCEDURE LBA_NORTH
    AS
    BEGIN
    execute immediate ( 'CREATE TABLE LBA_ALERT(DATE_CRT,DIST_MSISDN,FOS_MSISDN,RT_COUNT,RT_SERIES)TABLESPACE PRTP_INDX1 AS
    SELECT TO_CHAR(LMA.DATE_CRT,'DD-MON-YY'), LMP.DIST_MSISDN,LMA.FOS_MSISDN,COUNT(LMA.RT_MSISDN)RT_COUNT,
    RTRIM (xmlagg (xmlelement (e, LMA.RT_MSISDN || ',')).extract ('//text()'), ',')AS RT_SERIES
    FROM LBA_Mapping LMP,LBA_Master LMA
    WHERE LMP.DIST_MSISDN=LMA.DIST_MSISDN
    GROUP BY LMP.DIST_MSISDN,LMA.FOS_MSISDN,TO_CHAR(LMA.DATE_CRT,'DD-MON-YY')');
    END;
    LINE/COL ERROR
    5/30 PLS-00103: Encountered the symbol "DD" when expecting one of the
    following:
    ) , * & | = - + < / > at in is mod remainder not rem => ..
    <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
    LIKE4_ LIKEC_ between || multiset member SUBMULTISET_
    The symbol "," was substituted for "DD" to continue.
    5/39 PLS-00103: Encountered the symbol "),
    LMP.DIST_MSISDN,LMA.FOS_MSISDN,COUNT(LMA.RT_MSISDN)RT_COUNT,
    " when expecting one of the following:
    . ( ) , * @ % & | = - + < / > at in is mod remainder not rem
    LINE/COL ERROR
    => .. <an exponent (**)> <> or != or ~= >= <= <> and or like
    LIKE2_ LIKE4_ LIKEC_ between || member SUBMULTISET_
    The symbol "(" was substituted for "),
    LMP.DIST_MSISDN,LMA.FOS_MSISDN,COUNT(LMA.RT_MSISDN)RT_COUNT,
    " to continue.
    6/65 PLS-00103: Encountered the symbol "/" when expecting one of the
    following:
    ( - + case mod new null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current max min prior sql stddev sum variance execute
    LINE/COL ERROR
    forall merge time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    <an alternatively-quoted string literal with character set
    specification>
    <an alternatively-quoted SQL string>
    6/72 PLS-00103: Encountered the symbol "), " when expecting one of the
    following:
    . ( ) , * % & | = - + < / > at in is mod remainder not rem =>
    .. <an exponent (**)> <> or != or ~= >= <= <> and or like
    LINE/COL ERROR
    LIKE2_ LIKE4_ LIKEC_ between || member SUBMULTISET_
    Edited by: user3558544 on Mar 28, 2013 4:52 AM

    And by the way...
    user3558544 wrote:
    Kidnly suggest immediately
    This is a forum of volunteers who have their own jobs to do. Suggesting they respond immediately or ugently is considered downright rude, not just to those volunteers but also to all the other people who would like a quick answer to their questions (but who haven't been rude).
    Read: {message:id=9360002}

  • Dbma_scheduler job executing procedure that loops through all client schemas in the database rolls back transaction incase of exception

    Hi,
    Needed your inputs on approach to implement a job using dbms_scheduler.
    We have around 2000 schemas. Each schema has a package with 2 procedures.
    The requirement is to create a single job in SYS that would loop through each schema and run the procedures at a specific time ( once a day) and send email notification on success or failure.
    Job script:
    BEGIN
        dbms_scheduler.create_job( job_name=> 'LOAD_EACH_SCHEMA_AUDIT_DATA',
                                   job_type=>'PLSQL_BLOCK',
                                   job_action=>'BEGIN  sys.p_loadaudit;     
                                    END;',
                                   start_date=>systimestamp,
                                   repeat_interval=>'FREQ=MINUTELY;INTERVAL=1',
                                   number_of_arguments=>0,
                                   enabled=> true,
                                   comments=>'Job repeat interval is every 5 mins' );
                                   END;
    Note: for testing purpose i have set repeat interval to minutely.
    Procedure job will be executing:
    Procedure sys.p_loadaudit:
    CREATE OR REPLACE
    PROCEDURE p_loadaudit
    AS
        v_count          NUMBER:= 0;
        lv_error_message VARCHAR2(4000);
        vstmt            VARCHAR2(4000);
    BEGIN
        FOR i IN
        ( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
        LOOP
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
            EXECUTE immediate vstmt;
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
            EXECUTE immediate vstmt;
        END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure p_loadaudit: ' || SQLCODE || ' -ERROR- ' || SUBSTR(
        sqlerrm,1,300) || '*' || dbms_utility.format_error_backtrace;
        raise_application_error(-20002,lv_error_message);
    END p_loadaudit;
    Example of one schema: SCHEMA_01
    create or replace
    PACKAGE pkg_audit_info
    AS
    type cursortype
    IS
        ref
        CURSOR;
            PROCEDURE p_load_COA;
            PROCEDURE p_load_AM;
       END pkg_audit_info;
    create or replace
    PACKAGE body pkg_audit_info
    AS
    PROCEDURE p_load_COA
    AS
    BEGIN
    INSERT INTO TABLE1();
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure pkg_audit_info.p_load_COA: ' || SQLCODE
        || ' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
        RAISE_application_error(-20002,lv_error_message);
    END p_load_COA;
    PROCEDURE p_load_AM
    AS
    BEGIN
    INSERT INTO TABLE2();
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure pkg_audit_info.p_load_AM: ' || SQLCODE ||
        ' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
        RAISE_application_error(-20002,lv_error_message);
    END p_load_AM;
    END pkg_audit_info;
    Table1 and table1 exist in schema_01.
    All 2000 schemas have same package.procedures.
    Due to security reasons i have removed the actual code.
    I was able to execute the job successfully. However, when a schema procedure (SCHEMA_01.pkg_audit_info.p_load_COA) throws an exception, the job fails and all transaction is rolled back.
    Is there a way to loop through each schema and execute the related procedures. Even if exception happens, it should rollback only for that schema and continue the other schemas in the loop?
    Please let me know if there is a better way to achieve this. Is the way i am handling exceptions in the job/procedure correct?
    Thanks

    Hi,
    RAISE_APPLICATION_ERROR will cause the program to exit back to the caller, even if you place it in a block within the loop, so the RAISE or RAISE_APPLICATION_ERROR instruction should be placed in your "pkg_audit_info.p_load_AM" and "pkg_audit_info.p_load_coa" procedures. This way, you can use a block inside the loop and log the error.
    FOR i IN
        ( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
        LOOP
           BEGIN
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
            EXECUTE immediate vstmt;
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
            EXECUTE immediate vstmt;
    EXCEPTION
    WHEN OTHERS THEN  
        --> Log the error in a custom log table otherwise you will not know what happened for that schema: don't forget the username
    END;
    END LOOP;

  • 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 see the data from the execute immediate o/p

    Hello
    i tried the following code
    SQL> declare
      2  vSql varchar2(3000);
      3  begin
      4  vSql:='SELECT';
      5   for i in (select column_name from user_tab_columns where table_name='EMP' order by column_name
      6   loop
      7     vSql:=vSql||i.column_name||',';
      8   end loop;
      9   execute immediate rtrim(vSql)||' '||'from emp';
    10  end;
    11  /
    declare
    ERROR at line 1:
    ORA-00900: invalid SQL statement
    ORA-06512: at line 9Please guide me to solve this error
    Edited by: josh1612 on Jun 22, 2010 3:58 AM

    josh1612 wrote:
    I need to execute that printed statment select ... from emp
    You are already executing it by using:
    execute immediate rtrim(vSql,',')||' from emp';What you probably want is to display results, right? Then you can either use bulk collect into clause in execute immediate or use cursor variable. Bulk collect example:
    set serveroutput on
    declare
      vSql varchar2(3000);
      type emp_rec_tbl_type is table of emp%rowtype;
      emp_rec_tbl emp_rec_tbl_type;
    begin
      vSql:='SELECT ';
       for i in (select column_name from user_tab_columns where table_name='EMP' order by column_id)
       loop
         vSql:=vSql||i.column_name||',';
       end loop;
       dbms_output.put_line(rtrim(vSql,',')||' from emp');
       execute immediate rtrim(vSql,',')||' from emp' bulk collect into emp_rec_tbl;
       for i in 1..emp_rec_tbl.count loop
         dbms_output.put_line(rpad(emp_rec_tbl(i).ename,10) || emp_rec_tbl(i).sal);
       end loop;
    end;
    SELECT EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from emp
    SMITH     800
    ALLEN     1600
    WARD      1250
    JONES     2975
    MARTIN    1250
    BLAKE     2850
    CLARK     2450
    SCOTT     3000
    KING      5000
    TURNER    1500
    ADAMS     1100
    JAMES     950
    FORD      3000
    MILLER    1300
    PL/SQL procedure successfully completed.
    SQL> Cursor variable example:
    set serveroutput on
    declare
      vSql varchar2(3000);
      emp_rec emp%rowtype;
      cv sys_refcursor;
    begin
      vSql:='SELECT ';
       for i in (select column_name from user_tab_columns where table_name='EMP' order by column_id)
       loop
         vSql:=vSql||i.column_name||',';
       end loop;
       dbms_output.put_line(rtrim(vSql,',')||' from emp');
       open cv for rtrim(vSql,',')||' from emp';
       loop
         fetch cv into emp_rec;
         exit when cv%notfound;
         dbms_output.put_line(rpad(emp_rec.ename,10) || emp_rec.sal);
       end loop;
       close cv;
    end;
    SELECT EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from emp
    SMITH     800
    ALLEN     1600
    WARD      1250
    JONES     2975
    MARTIN    1250
    BLAKE     2850
    CLARK     2450
    SCOTT     3000
    KING      5000
    TURNER    1500
    ADAMS     1100
    JAMES     950
    FORD      3000
    MILLER    1300
    PL/SQL procedure successfully completed.
    SQL> SY.

  • How to make my Execute Immediate statement to work??

    Hi, Sir:
    I use SQL Oracle 9i,
    I have following procedure called by a trigger:
    CREATE OR REPLACE PROCEDURE emps_check IS
    s_sql VARCHAR2(500);
    BEGIN
    DBMS_OUTPUT.PUT_LINE('1. Start to Delete all rows in the emps' );
    delete from emps;
    DBMS_OUTPUT.PUT_LINE('2. Start to insert into emps from emp' );
    s_sql:='INSERT INTO Emps(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) select EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from emp;';
    DBMS_OUTPUT.PUT_LINE('3. s_sql= ' || s_sql );
    EXECUTE IMMEDIATE s_sql;
    DBMS_OUTPUT.PUT_LINE('3. Procedure call OK, Employ Name ' );
    EXCEPTION
    -- Use this to trap the ORA-00942: table or view does not exist
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Procedure call Exception: Employ Name ' );
    end emps_check;
    My trigger is:
    CREATE OR REPLACE TRIGGER emps_biu_after
    after INSERT OR UPDATE or delete on emp
    for each row
    begin
    if TO_CHAR(SYSDate,'DY')= 'SUN'
    then
    DBMS_OUTPUT.PUT_LINE('Today is holiday, ename =' );
    else
    DBMS_OUTPUT.PUT_LINE('Today is working Day, ename =');
    emps_check();
    end if;
    end;
    When I use following to update emp table:
    SQL> UPDATE emp T1
    2 SET T1.sal = 200.0
    3 WHERE T1.ename like '%SCOTT%';
    I got:
    Today is working Day, Trigger Call Procedure emps_check()
    1. Start to Delete all rows in the emps
    2. Start to insert into emps from emp
    3. s_sql= INSERT INTO Emps(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) select EMPNO,ENAME,JOB,MGR
    Procedure call Exception: Employ Name
    Trigger Call Procedure emps_check() Success
    Looks like EXECUTE IMMEDIATE s_sql; did not work.
    What is wrong??
    How to make my Execute Immediate statement to work??
    Thanks

    You may omit the ';' character...
    s_sql:='INSERT INTO
    Emps(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
    select EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    from emp';
    ... and something else
    IN PL/SQL when a procedure , function doews not take
    any parameter(s) then its call can be made as simply
    its name without a pair of parenthesis....(It seems
    that you are influenced by Java...:) )
    SimThanks Sir:
    I remove this ; but still error:
    1 UPDATE emp T1
    2 SET T1.sal = 768.1
    3* wHERE T1.ename like '%SCOTT%'
    SQL> /
    Today is working Day, Trigger Call Procedure emps_check()
    1. Start to Delete all rows in the emps
    2. Start to insert into emps from emp
    3. s_sql= INSERT INTO Emps(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) select EMPNO,ENAME,JOB,MGR,
    Procedure call Exception: Employ Name
    Trigger Call Procedure emps_check() Success
    My code as follows:
    CREATE OR REPLACE PROCEDURE emps_check IS
    s_sql VARCHAR2(500);
    BEGIN
    DBMS_OUTPUT.PUT_LINE('1. Start to Delete all rows in the emps' );
    delete from emps;
    DBMS_OUTPUT.PUT_LINE('2. Start to insert into emps from emp' );
    s_sql:='INSERT INTO Emps(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) select EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from emp';
    DBMS_OUTPUT.PUT_LINE('3. s_sql= ' || s_sql );
    EXECUTE IMMEDIATE s_sql;
    DBMS_OUTPUT.PUT_LINE('3. Procedure call OK, Employ Name ' );
    EXCEPTION
    -- Use this to trap the ORA-00942: table or view does not exist
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Procedure call Exception: Employ Name ' );
    end emps_check;
    what is other wrong??
    Yes, I am java guys,
    Thanks

  • Equivalent  for execute immediate command in maxdb

    hi all,
    like in oracle for executing the sql_query, we have execute immediate command.
    for e.g.. in oracle
    L_SQL ='SELECT * FROM EMP';
    EXECUTE IMMEDIATE L_SQL;
    what will be the command for execute immediate in MaxDB??
    like in MaxDB
    L_SQL = 'SELECT * FROM EMP';
    Now How can i execute the above l_sql variable in MaxDB.
    thanks, Bhupinder

    Hi Bhupinder,
    the following code snippet should do the job
    [code]
    CREATE DBPROC EXAMPLE
    AS
    VAR statement1 char(100);
    SET statement1 = 'SELECT * from DBA.DUAL';
    TRY
        EXECUTE statement1;
    CATCH IF $rc <> 100
         THEN STOP ($rc, 'unexpected error');
    [/code]
    Best regards,
    Marco

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

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

Maybe you are looking for