Help on Execute Immediate Dynamic Sql

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

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

Similar Messages

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

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

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

  • Execute Immediate with SQL in Stored Procedure

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

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

  • Help to make this dynamic sql work

    Hi,
    I have many DDLs to execute and these DDLs change over time, so I try to load these DDLs into a table (y) and write a proc to loop through them. But I run into some problems and need your help.
    Here are the details:
    create table y ( x varchar2(4000));
    CREATE TABLE error_log (
    error_log_ID NUMBER(20),
    statement VARCHAR2(2000),
    error_msg VARCHAR2(400),
    Action VARCHAR2(16)
    CREATE SEQUENCE SEQ_error_log
    START WITH 1
    INCREMENT BY 1
    NOMINVALUE
    NOMAXVALUE
    NOCYCLE
    CACHE 20
    NOORDER
    CREATE OR REPLACE PROCEDURE CUST_UPDATE1 (
    schema_name IN VARCHAR2 ,
    table_tablespcae_name IN VARCHAR2,
    index_tablespcae_name IN VARCHAR2
    ) AS
    v_code NUMBER;
    v_errm VARCHAR2(400);
    sql_stmt1 VARCHAR2(3000) ;
    CURSOR c1 IS SELECT x FROM y;
    BEGIN
    FOR i IN c1 LOOP
    sql_stmt1 := i.x;
    DBMS_OUTPUT.PUT_LINE ( 'x = '|| sql_stmt1 );
    / **************************** worked if use this hard coded ********************************
    sql_stmt1 := 'CREATE TABLE '||schema_name||'.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE '|| table_tablespcae_name;
    BEGIN
    EXECUTE IMMEDIATE sql_stmt1;
    EXCEPTION
    WHEN OTHERS THEN
    v_code := SQLCODE;
    v_errm := SUBSTR(SQLERRM, 1 , 400);
    INSERT INTO error_log VALUES ( SEQ_error_log.nextval, sql_stmt1, v_errm, DECODE(v_code, -1430, 'IGNORE', 'CHECK') );
    END;
    END LOOP;
    END;
    Test:
    exec cust_update1('SCOTT', 'USERS', 'c'); -- didn't use last parameter
    Senario 1. insert into y values (
    'CREATE TABLE schema_name.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE table_tablespcae_name ' );
    ===> error_log show: ORA-01918: user 'SCHEMA_NAME' does not exist
    Senario 2. insert into y values (
    '''CREATE TABLE ''||schema_name||''.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE ''|| table_tablespcae_name' );
    ==> error_log show: ORA-00900: invalid SQL statement
    3. I hard coded the exact dynamic from step 2 and assigned to sql_stmt1, ( as commeted out in my code) it WORKED.
    Thanks
    George

    hi,
    do the scenario1 but you have to substitute the schema_name and table_space name with your actual string before calling the dynamic sql.
    ei.
    sql_stmt1 := replace(sql_stmt1,'schema_name',schema_name);
    sql_stmt1 := replace(sql_stmt1,'table_tablespcae_name',table_tablespcae_name);
    BEGIN
    EXECUTE IMMEDIATE sql_stmt1;
    EXCEPTION
    WHEN OTHERS THEN
    v_code := SQLCODE;
    v_errm := SUBSTR(SQLERRM, 1 , 400);
    INSERT INTO error_log VALUES ( SEQ_error_log.nextval, sql_stmt1, v_errm, DECODE(v_code, -1430, 'IGNORE', 'CHECK') );
    END;
    Cheers,
    J

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

  • What is the best way to execute immediate particular sql stored in a table

    I have a string variable containing row_ids eg "12,24,35,23"
    and a table
    row_id, sql
    1 , "insert into some_table values(23,'Happy');"
    6 , "insert into some_other_table values(24,'Sad');"
    12 , "insert into some_table values(23,'Crazzzy');"
    15 , "insert into some_other_table values(23,'Old');"
    23 , "insert into another_table values(23,'Left');"
    24 , "insert into stuff_table values(23,'Gold');"
    30 , "insert into old_table values(23,'Even');"
    35 , "insert into archive_table values(23,"True");"
    And I need to write a plsql function that takes the list of row_ids as an argument and executes the sql statements stored in the table that matches.
    I am trying a combination of cursor and execute immediate statements to do it at the moment but suspect I am being very inefficient. So any suggestions or examples of similar code anyone knows about would be hugely appreciated.
    Cheers
    Reuben

    Not sure why anyone would be doing such a thing as storing their SQL in a table and wanting to dynamically execute it (generally this is bad practice), but if you must...
    SQL> select * from testdata;
        SQL_ID SQL_TEXT
             1 insert into some_table values(23,'Happy');
             6 insert into some_other_table values(24,'Sad');
            12 insert into some_table values(23,'Crazzzy');
            15 insert into some_other_table values(23,'Old');
            23 insert into another_table values(23,'Left');
            24 insert into stuff_table values(23,'Gold');
            30 insert into old_table values(23,'Even');
            35 insert into archive_table values(23,'True');
    8 rows selected.
    SQL> set serverout on
    SQL> ed
    Wrote file afiedt.buf
      1  DECLARE
      2    v_ids VARCHAR2(4000) := '12,24,35,23';
      3    CURSOR cur_fetch IS
      4      SELECT sql_text
      5      FROM   testdata
      6      WHERE  sql_id IN (SELECT TO_NUMBER(REGEXP_SUBSTR (v_ids, '[^,]+', 1, rownum))
      7                        FROM   DUAL
      8                        CONNECT BY ROWNUM <= length(regexp_replace(v_ids,'[^,]*'))+1);
      9  BEGIN
    10    FOR s IN cur_fetch
    11    LOOP
    12      DBMS_OUTPUT.PUT_LINE(s.sql_text); -- For demo purposes show the sql text
    13      -- EXECUTE IMMEDIATE s.sql_text; -- In reality, uncomment this to execute the sql text
    14    END LOOP;
    15* END;
    16  /
    insert into some_table values(23,'Crazzzy');
    insert into another_table values(23,'Left');
    insert into stuff_table values(23,'Gold');
    insert into archive_table values(23,'True');
    PL/SQL procedure successfully completed.
    SQL>

  • Help With SUBSTR in dynamic SQL statement

    Following is the dynamic SQL statement.
    EXECUTE IMMEDIATE 'UPDATE table_name pml
    SET pml.'|| con_fields.field ||' = SUBSTR(pml.'||con_fields.field||' ||'' ''||
    (SELECT pml1.'||con_fields.field||'
    FROM table_name pml1
    WHERE pml1.grp_id = '||los_concats.grp_id ||'
    AND pml1.row_id = '||los_concats.row_id||'
    AND pml1.loser_flg = ''Y''),1, '||con_fields.max_length||')
    WHERE pml.grp_id = '||los_concats.grp_id ||'
    AND pml.loser_flg IS NULL ';
    what it does is that it updates a particular field. This field is concatenated by a field of a similar record.
    My problem is with SUBSTR function. Since I am concatenating fields I do not want the field to be updated greater than max_length on that field, the reason why I use SUBSTR. the select query inside SUBSTR works alright with one of the AND condition in a WHERE clause not present. When I add that additional condition it gives me this error.
    ORA-00907: missing right parenthesis.
    Is there any way to get around this problem. Does SQL has other than SUBSTR function which can limit the character length.
    Appreciate it.

    The other alternative I thought about was to do this first
    EXECUTE IMMEDIATE 'SELECT pml.'||con_fields.field||'
    FROM table_name pml
    WHERE pml.grp_id = '||los_concats.grp_id||'
    AND pml.row_id = '||los_concats.row_id||'
    AND pml.loser_flg = ''Y''
    ' INTO v_concat_field;
    write into the variable v_concat_field and then use it into the previous script.
    But on this I get SQL Command not properly terminated, I don't get it Why?
    Donald I tried with your suggested script. It works fine with one of the conditions eliminated. I don't understand what the error trying to say?
    Thanks

  • Help with EXECUTE IMMEDIATE and DROP

    Hi all,
    we are trying to create a procedure to do the following:
    * We have in the database some tables named like C$_XXXXXXXXX
    * We want to drop some of these tables that have a common prefix (f.e C$_1203101)
    DECLARE
    v_sql VARCHAR2(300);
    BEGIN
    SELECT 'DROP TABLE ODISTAG.'|| TABLE_NAME ||';' INTO v_sql FROM USER_TABLES WHERE TABLE_NAME LIKE 'C$_1203101%';
    EXECUTE IMMEDIATE v_sql;
    END;
    But we get this error:
    Error report:
    ORA-00911: invalid character
    ORA-06512: at line 5
    00911. 00000 - "invalid character"
    *Cause:    identifiers may not start with any ASCII character other than
    letters and numbers. $#_ are also allowed after the first
    character. Identifiers enclosed by doublequotes may contain
    any character other than a doublequote. Alternative quotes
    (q'#...#') cannot use spaces, tabs, or carriage returns as
    delimiters. For all other contexts, consult the SQL Language
    Reference Manual.
    *Action:
    Any help on that please?
    Thanks!

    This will not work if you fetch more than one row..instead you can do this..
    DECLARE
         v_sql VARCHAR2(30000);
    BEGIN
         for c2 in (
                        SELECT 'DROP TABLE ODISTAG.'|| TABLE_NAME drp
                        FROM USER_TABLES WHERE TABLE_NAME LIKE 'C$_1203101%'
         loop
              v_Sql := c2.drp;
              EXECUTE IMMEDIATE v_sql;
         end loop;
    END;

  • Need help with EXECUTE IMMEDIATE

    I have created a CHAR string in my form that contains a UPDATE statement. This statement is passed into my procedure and in the procedure, the EXECUTE IMMEDIATE is supposed to run the UPDATE statement. THIS IS NOT THE CASE for some reason. NEWVALUE is record is also passed into the procedure.
    this is the UPDATE_STATEMENT statement prepared by my forms application:
    'UPDATE xtable SET ACTION_CODE_DESC =''a b c'',INACTIVE =''N'' WHERE ACTION_CODE = newValue.ACTION_CODE'
    The CHAR values are surrounded by a pair of single quotes. The UPDATE statement starts and ends with single quotes.
    In my procedure I have this statement:
    PROCEDURE JKUPD_ACTION_CODE
    ( newValue in etmst_action_code%rowtype
    ,UPDATE_STATEMENT in CHAR
    ,perr_count out number
    AS
    BEGIN
    EXECUTE IMMEDIATE UPDATE_STATEMENT ;
    IF SQL%NOTFOUND
    THEN .......
    I keep getting ORA-00900: invalid SQL statement and dont understand why this is happening.
    Any ideas anyone?
    Thanks :)

    I haven't seen a version indication for this thread, but there should be 2 (different!) functions that come with Oracle that might do what you want.
    If all you want to do is dynamically execute text representing a SQL command check the on-line documentation (if there is any) for dbms_sql.execute and/or dbms_utility.exec_ddl. Make sure the string passed in are syntactically correct :)

  • Need some help in EXECUTE IMMEDIATE Query

    Hi All,
    First of all i have a question. Is EXECUTE IMMEDIATE allowed for multi-row queries. (I am using Oracle 10g R2).
    Some of my colleagues are using pipeline operator. Please refer below
    BEGIN
    EXECUTE IMMEDIATE 'CREATE TABLE TEMP NOLOGGING AS'||
    '(' ||
    'SELECT P.PSEQ,' ||
    'I.PLEY,' ||
    'I.ORG,' ||
    'I.RKEY,' ||
    'COUNT(P.PSEQ) COUNT'||
    'FROM' ||
    'PROD P,' ||
    'INV I,' ||
    'PLAC PL,' ||
    'ORG O' ||
    'WHERE' ||
    'I.RKEY=P.PSEQ' ||
    'AND'||
    'P.COMP=''RT''' ||
    'AND'||
    'I.INVST = ''IN''' ||
    'AND'||
    'P.SSN=''C''' ||
    'AND'||
    'PL.PLEY=I.PLEY' ||
    'AND'||
    'I.ORG=O.OSEQ' ||
    'GROUP BY' ||
    'I.PLKEY,' ||
    'I.ORG,' ||
    'I.PLEY,' ||
    'P.PSEQ' ||
    END;
    Is it at neccessary to concatenate. Earlied i have used execute immediate with multi row queries successfully without any ||.
    Please help me to understand??
    Thanks in advance.
    Message was edited by:
    SID

    btw it's the concatenation operator, and '|' is known as the pipe character. Pipelines are something different.

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

  • Execute immediate a sql block of istructions

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

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

  • EXECUTE IMMEDIATE dynamic statement and return procedure value

    Hello guys,
    How can i return values from procedure using EXECUTE IMMEDIATE statment?
    I made easy example:
    CREATE OR REPLACE PACKAGE pac_test
    IS
    PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER,
    v_out OUT NUMBER);
    PROCEDURE pro_calc(p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER);
    END;
    CREATE OR REPLACE PACKAGE BODY pac_test
    IS
    PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER,
    v_out OUT NUMBER)
    IS
    BEGIN
    v_out:=(p_age_1+p_age_2+p_age_3)/3;
    END pro_calc_average;
    PROCEDURE pro_calc(p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER)
    IS
    x number;
    v_sql varchar2(4000);
    BEGIN
    v_sql:='pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x)';
    dbms_output.put_line(v_sql);
    EXECUTE IMMEDIATE v_sql;
    dbms_output.put_line(' ====> '||x);
    END pro_calc;
    END;
    -- Run procedures [Faild]
    EXEC pac_test.pro_calc(2,9,19);
    When i run:
    DECLARE
    x number;
    BEGIN
    pac_test.pro_calc_average(2,9,9,x);
    dbms_output.put_line(' ====> '||x);
    END;
    It's works, but this is not what i am looking for.
    Thank you guys,
    Sam.

    Hi Sam,
    Like this?
    CREATE OR REPLACE PACKAGE pac_test
    IS
    pac_var number;  /* added new*/
    PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER,
    v_out OUT NUMBER);
    PROCEDURE pro_calc(p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER);
    END;
    CREATE OR REPLACE PACKAGE BODY pac_test
    IS
    PROCEDURE pro_calc_average( p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER,
    v_out OUT NUMBER)
    IS
    BEGIN
    v_out:=(p_age_1+p_age_2+p_age_3)/3;
    END pro_calc_average;
    PROCEDURE pro_calc(p_age_1 IN NUMBER,
    p_age_2 IN NUMBER,
    p_age_3 IN NUMBER)
    IS
    pack_local_var number;
    v_sql varchar2(4000);
    BEGIN
    --v_sql:='pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x)';
    v_sql:=' declare x number; begin pac_test.pro_calc_average('||p_age_1||','||p_age_2||','||p_age_3||',x);
    dbms_output.put_line(x);
    pac_test.pac_var:=x; /* added new*/
    end;';
    dbms_output.put_line(v_sql);
    EXECUTE IMMEDIATE v_sql;
    pack_local_var:=pac_var; /* added new*/
    dbms_output.put_line(pack_local_var); /* added new*/
    END pro_calc;
    END;Declared a package variable.
    But be aware this variable is accessible to everyone and they can read or change its value if they have the right privileges.
    REgards,
    Bhushan

  • Help needed in debugging dynamic SQL.

    When I pass the p_deptno =30 and run the below code the refcursor returns the rows.But when I pass the dpetno =null then it goes to the condition if p_job is not null and throws an error.Can any one please help me in debugging this code.
    declare
    p_deptno number:=null;
    p_job varchar2(30):='SALESMAN';
    v_sql varchar2(4000);
    l_ename varchar2(30);
      TYPE my_cursor IS REF CURSOR;
      RC my_cursor;
    begin
      v_sql := 'select ename
                from emp
               where 1=1';
      if p_deptno is not null then
        v_sql := v_sql||' AND deptno='||p_deptno;
      else
        if p_job is not null then
          v_sql := v_sql||' AND job='||p_job;
        end if;
      end if;
      OPEN RC FOR v_sql;
      LOOP
        FETCH RC INTO l_ename;
        EXIT WHEN RC%NOTFOUND;
        dbms_output.put_line(l_ename);
      END LOOP;
      CLOSE RC;
    END;Thanks.
    Edited by: user3565577 on Mar 6, 2010 8:44 PM

    Hi
    I've mocked up a simple test and it seems to use the indexes when I try with one or the other values being supplied, I've made an assumption on the indexes you have (i.e. single column indexes on job and deptno),
    --indexes on emp table:
    p2056@dbapw01> @indexes
    Enter value for table_name: emp
    Enter value for owner: p2056
    INDEX_OWNER                    INDEX_NAME                INDEX_TYPE                  PAR COLUMN_NAME                    STATUS
    P2056                          EMPI1                     NORMAL                      NO  DEPTNO                         VALID
    P2056                          EMPI2                     NORMAL                      NO  JOB                            VALID
    2 rows selected.
    --when accessing with a job value
    p2056@dbapw01> explain plan for select *
      2  from emp
      3  where (
      4   (null is null and job = 'SALESMAN')
      5   OR
      6   ('SALESMAN' is null and deptno = null)
      7   OR
      8   ('SALESMAN' is null and null is null)
      9         );
    Explained.
    p2056@dbapw01> @xplan
    PLAN_TABLE_OUTPUT
    Plan hash value: 1888885832
    | Id  | Operation                   | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |       |     2 |   154 |     1   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| EMP   |     2 |   154 |     1   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | EMPI2 |     2 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("JOB"='SALESMAN')
    --when accessing with a deptno value
    p2056@dbapw01> explain plan for select *
      2  from emp
      3  where (
      4   (2 is null and job = null)
      5   OR
      6   (null is null and deptno = 2)
      7   OR
      8   (null is null and 2 is null)
      9         );
    Explained.
    p2056@dbapw01> @xplan
    PLAN_TABLE_OUTPUT
    Plan hash value: 1336173234
    | Id  | Operation                   | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |       |     1 |    77 |     1   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| EMP   |     1 |    77 |     1   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | EMPI1 |     1 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("DEPTNO"=2)

  • Execute Dynamic SQL statement using procedure builder

    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks

    Hi,
    You can very well use DBMS_SQL Package supplied by Oracle for doing this.
    Search for DBMS_SQL in OTN. You will get all info regarding this.
    Regards.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by itslul:
    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks<HR></BLOCKQUOTE>
    null

Maybe you are looking for

  • Imac to tv - sound drops out

    hi, i'm not very good with technology.. but i've connected my imac to my LG tv with a HDMI cable and it was running great. but i just bought a new tv, and now the sound keeps cutting out. the settings are all the same as before though. i'm not sure w

  • Error message while asset transfer

    Hi     We are getting an error message when transfering an asset from one Company code to another Company code using transaction ABT1N. We are getting the following error message - Error during acquisition transfer: Depr. area does not exist Message

  • Not seen in windows (or anywhere else!)

    I have a problem.. I was given an Ipod - I am assuming it is a mini, but I'm not 100% certain - All I know is it has a touch wheel, is marked with 4Gb on the back, and it has a monochrome screen. There were NO cables, manuals, or CD's with it. I went

  • HP Officejet pro 8600 plus Scans show up as blank pages on Macs okay on PCs

    Scans made on HP Officejet Pro 8600 Plus show up okay on PCs buas blank pages on Macs. Any ideas? I can copy them into Publisher and then save it from Publisher as a pdf and Macs get it okay. Prefer not to have to do this

  • How to play FLAC and Other Lossless Formats on iTunes for Windows Vista x64

    Is it possible? If so, how?