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:\>

Similar Messages

  • Execute Immediate Statment

    Hello Every one,
    Can any one explain me Pros & cons for usage of Execute Immediate statement also whether to go for Dynamic Sql or Static Sql
    Warm Regards,
    Jagdish

    Hi,
    execute immediate is new for 9i and is more easy to write and understand, it is limited by command max size of 32 k if i remember correctly.
    regarding wether to use Dyn. or Stat sql it is up to you to decide if you need it or not.
    dBarak.

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

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

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

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

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

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

  • Execute immediate and dynamic sql

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

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

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

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

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

  • How can i have '&' in EXECUTE IMMEDIATE statement?

    I have PL/SQL procedure, where i will be inserting data to a table. Data which i am inserting is having a '&' value in it. If i use the below statement for insert then sqlplus is prompting for the value '&' like a substitution value while compile this procedure.
    EXECUTE IMMEDIATE 'INSERT INTO TABLE_TEST VALUES (:1,:2)' USING 'root/direct/&text', SYSDATE;If i replace the '&' by assigning this value to VARCHAR field then it is working properly. But when i populate an xml from this table using DBMS.XMLGEN, then the value '&' is not entity escaped in the XML which is normally replaced with '&amp;' in XML.
    Please help.

    Vel wrote:
    i can't go by both ways because i am using '&' in various files to get some values. Also in this package i am using the '&' to get another substitution variable. Is there any other workaround possible?I prefer not to mess with server-side SQL and PL/SQL code to fix, or work around, a problem on the client-side. Not a very sensible thing IMO.
    In such a case as you've described, I would set the substitution character to a character that I'm not using in server-side code. I have done this a couple of times in the past for db create and installation scripts. Oracle uses the same approach for their Apex installation scripts.
    I think Oracle uses the +#+ character for their Apex install scripts. E.g.
    set define '#'I think I used the tilde (char <i>~</i>) at a stage as substitution char as it is very seldom used in PL/SQL and SQL code.
    The bottom line is that you will need to change your code. Set define off and on where needed to ensure substitution only happens where needed. Set the substitution char to a different char and update your substitution variables. Or hack your server-side code (as suggested above) and use the char() function instead.

  • Error in execute immediate statement

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

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

  • Java Stored Procedure in EXECUTE IMMEDIATE

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

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

  • 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

  • Problem wile EXECUTE IMMEDIATE DDL statement in procedure

    Hi ,
    This is my procedure and it's getting compiled but while executing procedure getting this error,
    can anyone please tell me how to fix this?
    create or replace procedure construct_Table (name_table IN VARCHAR2)
    IS
    v_tab_name varchar2(40):=NULL;
    v_sql_Stmt varchar2(32767) := NULL;
    finalquery varchar2(32767) :=NULL;
    cursor tp is
    select COLUMN_NAME,DATA_TYPE,DATA_PRECISION,CHAR_LENGTH  from all_tab_cols where table_name=name_table;
    BEGIN
    begin
    select TABLE_NAME into v_tab_name from user_tables where table_name=name_table;
    EXCEPTION
    WHEN no_Data_found
    THEN
    DBMS_OUTPUT.PUT_LINE('No such table exist');
    end;
    if(v_tab_name IS NOT NULL)then
    finalquery := 'CREATE TABLE '||v_tab_name||'_DUMMY (';
       FOR I IN tp LOOP
       if(I.data_type='VARCHAR2') then
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type||'('||I.char_length||') ';
       elsif(I.data_type='NUMBER') then
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type||'('||I.DATA_PRECISION ||') ';
       else
       v_sql_stmt := finalquery ||I.column_name||' '||I.data_type ;
       end if;
       finalquery := v_sql_stmt || ',';
       END LOOP;
       finalquery := SUBSTR(finalquery,1,LENGTH(finalquery) - 1)||')';
       dbms_output.put_line(finalquery);
       EXECUTE IMMEDIATE'grant create any table to cmsuser';
       EXECUTE IMMEDIATE finalquery;
    end if; 
    END;
    /This is the error I am getting
    Error starting at line 1 in command:
    begin
    construct_Table ('EMP');
    end;
    Error report:
    ORA-01031: insufficient privileges
    ORA-06512: at "CMSUSER.CONSTRUCT_TABLE", line 30
    ORA-06512: at line 2
    01031. 00000 -  "insufficient privileges"
    *Cause:    An attempt was made to change the current username or password
               without the appropriate privilege. This error also occurs if
               attempting to install a database without the necessary operating
               system privileges.
               When Trusted Oracle is configure in DBMS MAC, this error may occur
               if the user was granted the necessary privilege at a higher label
               than the current login.
    *Action:   Ask the database administrator to perform the operation or grant
               the required privileges.
               For Trusted Oracle users getting this error although granted the
               the appropriate privilege at a higher label, ask the database
               administrator to regrant the privilege at the appropriate label.Thanks ,
    Deekay.

    Deekay,
    If you grant create table privilege and create table in the same procedure, then how you will differentiate that which user you granted the privilege and in which schema, you are creating the table. Here, you are granting to "cmuser", but in the same schema, you are creating the table also. How can a user grant privilege to himself?
    Login as DBA, grant create any table privilege to "cmuser" from dba. Then, you can execute you procedure in "cmuser" schema.

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

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

  • 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

  • How can i pass multiple values by a single variable to EXECUTE IMMEDIATE

    Hi All,
    I want to pass multiple values for where condition for execute immediate. Something Like this:-
    bold
    Declare
    v_cond varchar(1000);
    Begin
    v_cond := '''INR','USD'''; --(OPTION 1)
    v_cond := 'INR,USD'; --(OPTION 2)
    EXECUTE IMMEDIATE 'Delete from table where colm in (:v_cond)' using v_cond;
    END;
    bold
    I am using this into a procedure
    Now option 1 gives an error ie a syntax error (; expected or something like that)(I am sorry, i can't tell the exact error here as i am not in the office right now)
    and option 2 makes the procedure execute but obviously doesn't delete the records, as it takes the whole as one.
    Please Help
    Regards
    Neeraj Bansal

    See the links containing examples under
    *7. List of values in an IN clause?*
    SQL and PL/SQL FAQ
    from the SQL and PL/SQL FAQ.

Maybe you are looking for