Error in PL/SQL - execute immediate

Hi ,
I am getting this error when executing the procedure.Could you help me what wrong in it?
SQL >create or replace procedure delete_emp_copy (tname in varchar2) is
sql_stmt varchar2(200);
begin
sql_stmt :='delete from :1';
execute immediate sql_stmt using tname;
end;
Procedure created
.SQL> execute delete_emp_copy('EMPLOYEES_COPY');
BEGIN delete_emp_copy('EMPLOYEES_COPY'); END;
ERROR at line 1:
ORA-00903: invalid table name
ORA-06512: at "HR.DELETE_EMP_COPY", line 5
ORA-06512: at line 1
EMPLOYEES_COPY exists in my schema? what could be wrong?

You can't bind in a table name. You would have to concatenate the table name. Youd can use bind variables for values in the where clause, for example, but not for object names.
create or replace procedure delete_emp_copy (tname in varchar2) is
sql_stmt varchar2(200);
begin
sql_stmt :='delete from ' || tname;
execute immediate sql_stmt;
end;I'd recommend you to validate the table name, using a select from all_tables to check if it exists, or using the DBMS_ASSERT if your Oracle version supports it.

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')

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

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

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

  • How to execute a statement in forms procedure like SQL EXECUTE IMMEDIATE

    Hi to all,
    In a form I have created this procedure:
    PROCEDURE insert_rows (
    tbName IN VARCHAR2,
    list_of_fields IN VARCHAR2,
    origin_table IN VARCHAR2,
    wCondition IN VARCHAR2 DEFAULT NULL)
    IS
    where_clause VARCHAR2 (2000) := ' WHERE ' || wCondition ;
    table_to_fill VARCHAR2 (30);
    BEGIN
    -- Exist the table ?
    SELECT OBJECT_NAME INTO table_to_fill FROM USER_OBJECTS
    WHERE OBJECT_NAME = UPPER(origin_table) AND OBJECT_TYPE = 'TABLE' ;
    IF wCondition IS NULL THEN
    where_clause := NULL;
    END IF ;
    EXECUTE IMMEDIATE 'INSERT INTO ' || table_to_fill || ' SELECT ' || list_of_fields || ' FROM ' || origin_table || where_clause ;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    -- Here the Alert
    END;
    But, when I compile this error is displayed:
    Function not supported from client side application corresponding to SQL statement EXECUTE IMMEDIATE
    How can to correct this script for my form ?
    I hope in Your help.
    Best Regards
    Gaetano

    You have two options:
    1)To create this procedure in database
    2)Yo use the forms built-in FORMS_DDL instead of execute immediate , altering the one provided
    Sim

  • Dyn sql execute immediate  A plsql block returning sql%rowcount of rows inserted

    I would like to get the number of rows inserted in a dynamic sql statement like following.
    execute immediate
    'begin insert into a(c1,c2,c3)
    (select ac1,ac2,ac3 from ac where ac1=:thekey
    UNION select tc1,tc2,tc3 from tc where tc1=:otherkey); end;' using in key1,in key2;
    I have tried per the oracle8i dyn sql chapter in doc RETURN sql%rowcount won't compile.
    also add this to statement 'returning sql%rowcount into :rowcount'
    no luck.
    any ideas.?
    thanks.

    Quick comment first - I'm not sure why you are even using dynamic SQL here. There is nothing dynamic about your statement. It is equivalent to just:
    insert into a (c1, c2, c3)
      select ac1, ac2, ac3
        from ac
       where ac1 = key1
      UNION
      select tc1, tc2, tc3
        from tc
       where tc1 = key2;Unless you are really dynamically changing a table or column name here and just didn't show it in your example, you certainly don't want the overhead of NDS for this insert in this situation.
    In any case, you just need to evaluate SQL%ROWCOUNT in the next statement.
    insert ...;
    if sql%rowcount = 0 then
      -- nothing was inserted
    end if;

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

  • ORA-01007 - variable not in select list error in pl\sql code

    Hi,
    When I tried to run this program I am getting below error:
    ORA-01007 - variable not in select list.Please help to resolve.
    Code:
    create or replace procedure "XX_BPM_DATA_P" (P_PROCESS_ID IN VARCHAR2)
    is
    TYPE l_entity_type IS TABLE OF xx_BPM_data.ENTITY%TYPE INDEX BY PLS_INTEGER;
    TYPE l_data_type IS TABLE OF XX_BPM_DATA.DATA%TYPE INDEX BY PLS_INTEGER;
    TYPE l_count_type IS TABLE OF XX_BPM_DATA.count%TYPE INDEX BY PLS_INTEGER;
    l_Entity_v l_Entity_type;
    l_data_v l_data_type;
    l_count_v l_count_type;
    l_security_group_id number;
    app_id number(20);
    l_Actual_value XX_BPM_DATA.DATA%TYPE;
    cursor BPM_CUR is select id,process_id , sequence, to_char(query) query,report_num from xx_test_bpm_dynamic
    where
        process_id = p_process_id
           and report_num=1
    order by process_id, sequence;
    BEGIN
    --delete xx_bpm_data where process_id = p_process_id;
    for bpm_rec in bpm_cur
    loop
    delete xx_bpm_data
    where process_id = bpm_rec.process_id
    and sequence = bpm_rec.sequence
    and report_num = bpm_rec.report_num;
    l_security_group_id := apex_custom_auth.get_session_id_from_cookie;
    --dbms_output.put_line(l_security_group_id);
    execute immediate bpm_rec.query BULK COLLECT INTO l_ENTITY_v,l_DATA_v,l_count_v;
    if (bpm_rec.report_num=2) then
    app_id:= 108;--NV('APP_ID');
    FORALL i IN l_ENTITY_v.FIRST..L_ENTITY_V.LAST
    INSERT INTO XX_BPM_DATA
        (EnTITY,
    value,data,count,
    Process_ID,
    Sequence,report_num)
    VALUES(l_entity_v(i),
    l_data_v(i),
    '<A HREF="f?p='||app_id||':301:'||':APP_SESSION'||'::::P301_process_id,p301_sequence,p301_id,p301_entity:'||bpm_rec.process_id||','||bpm_rec.sequence||','||bpm_rec.id||','||l_entity_v(i)||':">'||l_data_v(i)||'</A>',
        l_count_v(i),bpm_rec.process_id,
    BPM_rec.sequence,
    bpm_rec.report_num);
    else
    FORALL i IN l_ENTITY_v.FIRST..L_ENTITY_V.LAST
    INSERT INTO XX_BPM_DATA(EnTITY,data,
        count,
    Process_ID,
    Sequence,report_num)
    VALUES(l_entity_v(i),
    l_data_v(i),
        l_count_v(i),
        bpm_rec.process_id,
    BPM_rec.sequence,
    bpm_rec.report_num);
    end if;
    select round(avg(value),2) into l_actual_value from xx_bpm_data where process_id=bpm_rec.process_id and sequence=bpm_rec.sequence and report_num=bpm_rec.report_num;
    update xx_test_bpm_dynamic set value=l_actual_value where process_id=bpm_rec.process_id and sequence=Bpm_rec.sequence and report_num= bpm_rec.report_num;
    end loop;
    Commit;
    END;

    When I tried to run this program I am getting below error:
    ORA-01007 - variable not in select list.Please help to resolve.
    You likely would not need any help in you wrote and tested your code using standard best practices.
    Your code has NO exception handler and you are NOT identifying each step in the code so that the exception handler could print/log a message telling you EXACTLY which step raised the exception.,
    v_step NUMBER;
    -- before step 1
    v_step := 1;
    -- before step 2
    v_step := 2;
    Then in the exception handler the value of 'v_step' will tell you which step raised the exception.
    The exception you posted refers to a 'select list' so examine ALL of the select lists in your code. If you do that you will see that the primary query being run is obtained from a database table and then executed using dynamic SQL
    execute immediate bpm_rec.query BULK COLLECT INTO l_ENTITY_v,l_DATA_v,l_count_v;
    We have no way of knowing what query is in 'bpm_rec.query' when the exception happens or what columns that query returns. For all we know the query returns 2 columns and you are trying to load 3 collections. Or maybe the query returns 8 columns and you are trying to load 3 collections.
    Why don't you print out the query and execute it manually so you can see exactly what the result set looks like?
    dbms_output.put_line(bpm_rec.query);
    And don't even get us started on why you are using such security-prone dynamic sql to perform this processing instead of using ordinary SQL statements. Or why you are using associative arrays for the BULK COLLECT instead of nested tables.
    In short your code could blow up in several places and, because you have NO logging statements, control statements or exception handlers, anyone having to troubleshoot that code would have absolutely no idea what part of it may be the problem.

  • Problem with alter table in execute immediate

    We have PL/SQL scripts which modify the data structure, add data etc to en existing database. These scripts basically ensure that the db is compatible with what the software expects.
    The reason for doing it in PL/SQL rather than SQL script is A) The scripts are launched using GUI so that they are more user friendly. sqlplus is launched as a background process which executes these scripts. All the scripts have EXIT FAILURE WHENEVER SQLERROR as first line to ensure that the control does not hang in the sqlplus background process.
    Going from one version to other, we have added a few tables to the database and also modified a few tables. since (i think) DDL is not allowed in PL/SQL block, we had to resort to putting them in EXECUTE IMMEDIATE enclosures.
    Now for the real question,
    If I create a table using EXECUTE IMMEDIATE clause, I can immediately have insert as a next statement to insert data in this table. but, if I alter the table and add a column to the existing table, I cannot immediately add data to that column, it throws an error saying 'invalid identifier'
    At code level, the following is allowed :
    EXECUTE IMMEDIATE 'CREATE TABLE SP_TEST_TABLE
                             ID     NUMBER,
                             NAME     Varchar2(40)
    INSERT INTO SP_TEST_TABLE(ID, NAME) Values(1, 'SP');
    but I get error for the following :
    EXECUTE IMMEDIATE 'ALTER TABLE SP_TEST_TWO ADD
                        ANOTHER_COLUMN     number
    UPDATE     SP_TEST_TWO SET          ANOTHER_COLUMN = 1;
    In this case, it says ANOTHER_COLUMN invalid identifier
    Does anybody know why?
    any workaround will be greatly appreciated.
    --SP                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Friends,
    Thanks to all of you for your help. The spelling mistakes might have occurred becuase i changed the actual script to something 'short and complete' to show the problem.
    I could solve the problem by having more than one PL/SQL block within my file. something like :
    BEGIN
    --alter table statements here
    END;
    BEGIN
    --insert the values in column here.
    END;
    I am still not sure why the error is presented only on alter table statement and not for create table statement. Probably somebody with the knowledge of oracle internals will be able to throw more light on it. I am trying to get the naswers, if I get the answer, I'll surely post it here.
    Regards,
    --Saurabh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • EXECUTE IMMEDIATE in Pro*C

    I am trying to use Execute immediate as following.
    strcpy (sqlstmt, "select id_tag, desc from notice where id = 2");
    EXEC SQL EXECUTE IMMEDIATE :sqlStmt INTO :id_tag, :desc;
    Pro*C is not letting me do INTO, while same thing works in PL/SQL fine.
    Any Idea on how to do this, other option for me is declare a cursor and do a FETCH INTO.
    Thanks in advance.
    Sandeep

    If you wanted it that way, this is one way to do it:
    #include <stdio.h>
    EXEC SQL INCLUDE SQLCA ;
    EXEC SQL BEGIN DECLARE SECTION ;
         VARCHAR sqlstmt[1000] ;
         VARCHAR userid[100] ;
         int     cnt ;
    EXEC SQL END DECLARE SECTION ;
    int main(void)
         strcpy(userid.arr, "scott/tiger") ;
         userid.len = strlen(userid.arr) ;
         EXEC SQL CONNECT :userid ;
         strcpy (sqlstmt.arr, "select count(*) from emp where deptno = :deptno");
         sqlstmt.len = strlen(sqlstmt.arr) ;
         EXEC SQL EXECUTE
              BEGIN
                   EXECUTE IMMEDIATE :sqlstmt INTO :cnt USING 10 ;
              END ;
         END-EXEC ;
         printf("Count=%d\n", cnt) ;
         EXEC SQL ROLLBACK WORK RELEASE ;
    }And the output:
    D:\>dynamic
    Count=3
    D:\>

  • Error on converting EXECUTE IMMEDIATE from oracle to SQL

    Hi,
    I am converting db from oracle to SQL using SSMA.
    I get following error while converting schema-
    This is the statement on source side (oracle) which is giving below error -EXECUTE IMMEDIATE sqlStat INTO objects_count; 
             *   SSMA error messages:
             *   O2SS0013: EXECUTE IMMEDIATE statement was converted into EXEC(...) statement, but dynamic string was not converted. It must be converted manually.
             EXECUTE (@sqlStat)
    Another issue is that I get below warning when converting this - temHEX NUMBER;
    from oracle to sql.
             *   SSMA warning messages:
             *   O2SS0356: Conversion from NUMBER datatype can cause data loss.
    It is converting to this in SQL - @temHEX float(53), 
    Please suggest.
    Thanks.

    Hi,
    I faced same error again-
    Below is the EXECUTE IMMEDIATE statement. Please help.
                               *   SSMA error messages:
                               *   O2SS0013: EXECUTE IMMEDIATE statement was converted into EXEC(...) statement, but dynamic string was not converted. It must be converted manually.
                               EXECUTE (
                                  'insert into Table1 (C_REPORTNAME,C_REPORTCODE,C_DATE,C_WEEK,C_MONTH,C_YEAR,'
                                   + 
                                  ISNULL(@sColumnNames, '')
                                   + 
                                  ') values ('''
                                   + 
                                  ISNULL(@sReportName, '')
                                   + 
                                   + 
                                  ISNULL(@sReportCode, '')
                                   + 
                                   + 
                                  ISNULL(CAST(@dInputDate AS nvarchar(max)), '')
                                   + 
                                   + 
                                  ISNULL(@sWeekNumber, '')
                                   + 
                                   + 
                                  ISNULL(@sMonth, '')
                                   + 
                                   + 
                                  ISNULL(@sYear, '')
                                   + 
                                   + 
                                  ISNULL(@sName, '')
                                   + 
                                   + 
                                  ISNULL(@sDescription, '')
                                   + 
                                   + 
                                  ISNULL(CAST(@nFail_Count AS nvarchar(max)), '')
                                   + 
                                   + 
                                  ISNULL(CAST(@nPass_Count AS nvarchar(max)), '')
                                   + 
                                   + 
                                  ISNULL(CAST(@nPassing_Fraction AS nvarchar(max)), '')
                                   + 
                                   + 
                                  ISNULL(@sEnabled, '')
                                   + 

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

  • Error in execute immediate statement

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

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

  • Using EXECUTE IMMEDIATE with Create Table SQL Statement not working

    Hi ,
    I am all the privileges given from the SYSTEM user , but still i am not able to create a table under procedure . Please see these and advice.
    create or replace procedure sp_dummy as
    begin
    Execute Immediate 'Create table Dummy99_99 (Dummy_Field number)';
    end;
    even i tried this way also
    create or replace PROCEDURE clearing_Practise(p_file_id in varchar2, p_country in VARCHAR2,p_mapId in VARCHAR2)
    AUTHID CURRENT_USER AS
    strStatusCode VARCHAR2(6);
    BEGIN
    EXECUTE IMMEDIATE 'create table bonus(name varchar2(50))';
    commit;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line('ERROR Creating Table');
    END ;

    William Robertson wrote:
    Since the syntax is correct, my guess is you do not have CREATE TABLE system privilege granted directly to your account. A common scenario is that you have this privilege granted indirectly via a role, allowing you to create tables on the command line, but stored PL/SQL is stricter and requires a direct grant and therefore the procedure fails with 'insufficient privileges'.A bit like he's already been told on his first thread...
    Using of Execute Immediate in Oracle PLSQL
    Generally you would not create tables from stored PL/SQL. Also as you have found out, it's best not to hide exceptions with 'WHEN OTHERS THEN [some message which gives less detail than the one generated by Oracle]'.Again like he was told on the other thread.
    There's just no telling some people eh! :)

  • Dynamic Sql Using Execute Immediate

    I am trying to construct a dynamic statement that takes in a supplied column name (COL_NAME), then do an Update on the column based on a supplied username. The table myTable has 4 columns and I would like to update a column thats supplied each time.
    NOT DYNAMIC
    PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
    BEGIN
    Update myTable
    set userid = '002'
    where username= aauser;
    [b]DYNAMIC
    PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
    BEGIN
    EXECUTE IMMEDIATE 'UPDATE myTable
    Set ' ||COL_NAME||' = val
    where myTable.username = aauser';
    END UpdateUser;
    However I get the following error when I execute this statement. Please help me.
    Connecting to the database Local.
    ORA-00904: "aaUser": invalid identifier
    ORA-06512: at "ANOLD.PUB", line 1433
    ORA-06512: at line 10
    Process exited.
    Disconnecting from the database Local.

    TEST@XE SQL> desc mytable
    Name                                                  Null?    Type
    USERNAME                                                       VARCHAR2(30)
    USERID                                                         VARCHAR2(30)
    COL3                                                           NUMBER
    COL4                                                           NUMBER
    TEST@XE SQL> insert into mytable values('TEST','001',1,2);
    1 row created.
    TEST@XE SQL> create or replace PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
      2  BEGIN
      3     EXECUTE IMMEDIATE  'UPDATE myTable
      4     Set ' ||COL_NAME||' = ' || chr(39) ||val|| chr(39) ||
      5     ' where myTable.username = ' || chr(39) ||aauser|| chr(39);
      6  END UpdateUser;
    TEST@XE SQL> /
    Procedure created.
    TEST@XE SQL> exec UpdateUser('TEST','userid','002');
    PL/SQL procedure successfully completed.
    TEST@XE SQL> select * from mytable;
    USERNAME                       USERID                                    COL3            COL4
    TEST                           002                                          1               2
    TEST@XE SQL> exec UpdateUser('TEST','col3',111);
    PL/SQL procedure successfully completed.
    TEST@XE SQL> select * from mytable;
    USERNAME                       USERID                                    COL3            COL4
    TEST                           002                                        111               2
    TEST@XE SQL>

  • Can't create a sequence within a pl/sql block with execute immediate.

    Hi All. I created a user and granted it the 'create sequence' privilege though a role. In a pl/sql block I try to create a sequence using 'execute immediate' but get a 1031-insufficient privileges error. If I grant create sequence directly to the user, the pl/sql block completes successfully. Can anyone explain this behavior? We're running 11.2 Enterprise Editon.
    Thanks,
    Mark

    In a definer's rights stored procedure (the default), you only have access to privileges that have been granted directly, not via a role.
    There are two basic reasons for that. First, roles can be enabled or disabled, default and non-default, password-protected, etc. so the set of roles a particular user actually has is session-specific. Oracle needs to know at compile time what privileges the owner of the procedure has. The only way to do that (without deferring the privilege check) is to ignore privileges granted through roles.
    Second, since 99% of privilege management DBAs do involves granting and revoking roles, it's helpful that changing role privileges will never cause objects to be marked invalid and recompiled which can have side-effects on applications. DBAs only need to worry about causing problems on those rare cases where they are granting or revoking direct privileges to users.
    You can create an invoker's rights stored procedure by adding the clause (AUTHID CURRENT_USER). That defer's the security check to run-time but allows the procedure to see privileges granted through roles in the current session. But that means that the caller of the procedure would need to have the CREATE SEQUENCE privilege through the role, not the owner of the procedure.
    And just to make the point, dynamic object creation in PL/SQL is almost always a red flag that there is something problematic in your design. If you are creating sequences dynamically, that means that you'd have to refer to them dynamically throughout your code which means that your inserts would need to use dynamic SQL. That's not a particularly easy or safe way to develop code.
    Justin

Maybe you are looking for

  • TS1538 Gen. 2 Nano refuses to be recognized by iTunes

    I tried hooking my old Gen. 2 iPod up to my laptop yesterday, and it refuses to be recognized by the computer or by iTunes.  It does however charge through all of my USB cables, so I know they work.  I've never had this particular iPod hooked up to t

  • Help with centralising a box in the absolute middle og the browser screen

    Hello there, i was wondering if someone could help me out with a little problem im having. im trying to design a site which basically has a box in the middle of the browser where all the info is displayed. now i know that if u set the horizontal alig

  • Multiple Web Applications WLS 7.0

    Hi, I am trying to configure multiple web applications on the same WL 7.0 server and am having trouble doing the following. I would like to be able to use the following URLS: Application #1: http://myserver/st/aems - where st/aems maps to the path X:

  • LRF1 TO display

    Hi , I have two step confirmation for a warehouse.After Picking confirmation, the TO should not be present in LRF1 transaction.But they are.Where is the setting to turn off the TO to be present in the LRF1 after picking confirmation.

  • How to authenticate UNIX command?

    As specified in KB article TS2754 <http://support.apple.com/kb/TS2754> I'd like to use this UNIX command to correct a user's computer: dseditgroup -o edit -p -a admin -t group _lpadmin I am trying to send this UNIX command via Remote Access 3.3 but e