How to report an error from anonymous PL/SQL blocks

Hello,
The following SQL*Plus script
WHENEVER OSERROR EXIT FAILURE
WHENEVER SQLERROR EXIT FAILURE
DECLARE
EXIST_INDEXES BOOLEAN := FALSE;
BEGIN
FOR INDEX IN (SELECT * FROM INDEXES)
LOOP
EXIST_INDEXES := TRUE;
DBMS_OUTPUT.PUT_LINE(INDEX.SCHEMA || '.' || INDEX.NAME);
END LOOP;
IF EXIST_INDEXES THEN
RAISE_APPLICATION_ERROR(-20000,'Before proceeding, it is recommended to drop the indexes listed above');
END IF;
END;
-- Here go SQL statements that should be executed if no indexes were found
produces this output when there is an entry in table/view INDEXES:
SCHEMA_1.INDEX_1
DECLARE
ERROR at line 1:
ORA-20000: Before proceeding, it is recommended to drop the indexes listed above
ORA-06512: at line 13
When there are entries in table/view INDEXES, how to:
- suppress the 'DECLARE' and '*' lines from appearing in the script output;
- skip executing the SQL statements after the PL/SQL block;
- have the script return a non-zero code?
Regards,
Angel Tsankov

1 You want the rest of the code not to execute, SO all code should be in one anonymous block.
The scope of exceptions is one block.
2 If you want to suppress
- suppress the 'DECLARE' and '*' lines from appearing in the script output;you should not use raise_application_error, because this is how raise_application_error works.
- whenever you raise an exception, the return code will be non-zero.
The code you posted is really very poor, and inefficient, but as it is unclear what you are up to (you seem to want to skip executing everything when there are any indexes, if so you can just count them), it is not possible to provide working code.
If you want to skip the rest of the code, you can declare your own exceptions, and you should just raise your own exception and the block will abort.
Hth
Sybrand Bakker
Senior Oracle DBA

Similar Messages

  • How to send a mail from a PL/SQL-block in Apex

    Hi, I am using Apex 3.0. On a page in my application users are fill out some fields, and clicking a button Apex inserts a new record in an table processing a PL/SQL-block.
    I would like to add "something" in this block so that Apex every time when it adds a new reord, also sends a mail to some people to inform them....
    A short e-mail: sender:...... receiver..... subject: New record, Text: New record was added
    Is that possible??Thx

    Hey Robert2,
    Apex has an API for sending emails: APEX_MAIL, you will need to have an SMTP server for this.
    Have a look in the user_guid, you will find what you need there.
    OLI

  • How to solve this error from window phone 80073cf9 lumia 630.

    any one know how to solve this error from window phone 80073cf9  lumia 630.

    Hello Muhammad,
    We appreciate the post, but this forum is for Windows Store and Phone Developer related questions. Your question can best be answered through the
    Windows Phone support page.
    Thanks!
    -Jonathan
    Windows Store Developer Support
    Office Store Developer Support

  • How to re-execute anonymous PL/SQL block in package definition ?

    Hi all,
    I implemented a package which contains procedures and an anonymous PL/SQL block.
    This anonymous PL/SQL block is executed only once when the package is called.
    and charge in-memory the content of table to avoid multiple SQL access each
    time one procedure is called.
    As my application open many sessions to the Oracle database, I would like to try
    a solution to signal all sessions to reload the content of table when the content
    of table is modified. The solution to stop and to restart the connection is not
    acceptable.
    Best regards
    Sylvain

    > .. to avoid multiple SQL access each time one procedure is called.
    As I understand your posting, this is the actual technical requirement. You want to force serialisation of PL/SQL code. Correct? (only one session at a time can run the procedure)
    This feature typically used to accomplish this in o/s code is called a semaphore. PL/SQL does not specifically support semaphores. However, it supports a range of IPC (Inter Process Communication) methods - from message queues to pipes.
    One of these IPC interfaces is DBMS_LOCK - which allows a unique lock to be defined and processes to manage their resource usage/execution/etc via this lock using the DBMS_LOCK API.
    I've found this a pretty clean and manageable solution to enforce serialisation. Of course, it is even better not to enforce serialisation. Rather design the code to be thread safe and capable of multi-processing/parallel processing.
    Personally, I would not use a table as an IPC mechanism as Oracle already provides better IPC mechanisms for PL/SQL code. As for "signalling sessions to re-load the table" - not possible as Oracle sessions cannot register callbacks to handle events. Oracle sessions are not event driven processes from a PL/SQL (application development) perspective.

  • How to create database link from oracle to sql server

    Please help with how to create database link from oracle to sql server
    Best regards,
    Vishal

    Please help with how to create database link from oracle to sql server
    Best regards,
    Vishal
    Hi Vishal,
    I found a lof of information regarding how to create a database link from Oracle to SQL Server, please see:
    https://www.google.co.in/?gws_rd=cr&ei=vd3XUvGFO8TgkAXqlYCADg#q=how+to+create+database+link+from+oracle+to+sql+server
    We discuss SQL Server related issue in this forum. If you have any more question regarding Oracle, please post it in Oracle communities forum for better support.
    Regards,
    Elvis Long
    TechNet Community Support

  • Alter database statement in anonymous pl/sql block

    Is it possible to include an alter database statement in an anonymous pl/sql block?
    When I execute this code to query user_tables for all table names, disable their constraints and drop the table, I got the following error:
    ***MY CODE
    -- DECLARE VARIABLE(S)
    DECLARE
         v_TABLE_NAME TABLE_NAME.USER_TABLE%TYPE;
    -- DECLARE AND DEFINE CURSOR
    CURSOR c_GETTABLES is
         SELECT TABLE_NAME from USER_TABLES;
    BEGIN
    OPEN c_GETTABLES;
    LOOP
    FETCH c_GETTABLES into v_TABLE_NAME;
    EXIT when c_GETTABLES%notfound;     
    ALTER TABLE v_TABLE_NAME DISABLE PRIMARY KEY CASCADE;
    DROP TABLE v_TABLE_NAME;
    END LOOP;
    CLOSE c_GETTABLES;
    END;
    ***RESPONSE FROM SERVER
    ALTER TABLE v_TABLE_NAME DISABLE PRIMARY KEY CASCADE;
    ERROR at line 15:
    ORA-06550: line 15, column 1:
    PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
    begin case declare exit for goto if loop mod null pragma
    raise return select update while with <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    close current delete fetch lock insert open rollback
    savepoint set sql execute commit forall merge
    <a single-quoted SQL string> pipe
    Thanks

    When you want to perform ddl statements in a (anonymous) PL/SQL block, you have to use dynamic SQL because ddl is not possible in pl/sql.
    Dynamic sql means that you sort of execute ddl statements in a sql manner. To use dynamic sql, two options exist:
    - dbms_sql package : for oracle before 8i. To use this package is not always easy. Read about it carefully first before using.
    - Native Dynamic SQL : implemented in 8i and very easy to use. An example would be :
    declare
    lv_statement varchar2(32676);
    begin
    lv_statement := 'ALTER TABLE MY_TABLE DISABLE CONSTRAINT MY_TABLE_CK1';
    execute immediate lv_statement;
    lv_statement := 'ALTER TABLE MY_TABLE ENABLE CONSTRAINT MY_TABLE_CK1';
    execute immediate lv_statement;
    end;
    Good luck.
    Edwin van Hattem

  • Calling 'start' from a pl/sql block or function

    hi all,
    i want to start a script from a Procedure, but using start is invalid, so i think the command 'start' is SQL*PLUS-Command. When i run the following code:
    declare
    stmt varchar2(200);
    begin
    stmt := 'start C:\null.sql';
    execute immediate stmt;
    end;
    i get this Error:
    ERROR at line 1:
    ORA-00900: invalid SQL statement
    ORA-06512: at line 5
    how can i run a script from a Procdure???
    thanks

    hi,
    i know that man can use java to run external commads, but this is not a system command. its sql*plus command!??
    my solution befor having the idea tu use "start sql_script" is to read the commands from the script file ( either using utl_file or java) and then executing it.
    is there an other way to run sql*plus commands (like start) from a PL/SQL block?

  • Pass values to Guid collection/array parameter for anonymous pl/sql block

    The following code pops the System.ArgumentException: Invalid parameter binding
    Parameter name: p_userguids
    at Oracle.DataAccess.Client.OracleParameter.GetBindingSize_Raw(Int32 idx)
    at Oracle.DataAccess.Client.OracleParameter.PreBind_Raw()
    at Oracle.DataAccess.Client.OracleParameter.PreBind(OracleConnection conn, IntPtr errCtx, Int32 arraySize)
    at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
    Any help or advice ?
    anonymous pl/sql block text:
    DECLARE
    TYPE t_guidtable IS TABLE OF RAW(16);
    p_userguids t_guidtable;
    BEGIN
    DELETE testTable where groupname=:groupname;
    INSERT INTO testTable (userguid, groupname)
    SELECT column_value, :groupname FROM TABLE(p_userguids);
    END;
    c# code:
    public static void SetGroupUsers(string group, List<Guid> users)
    OracleConnection conn = Database.ConnectionEssentus;
    try
    conn.Open();
    OracleCommand sqlCmd = new OracleCommand();
    sqlCmd.CommandText = sqls["SetGroupUsers"]; // above anonymous block
    sqlCmd.Connection = conn;
    sqlCmd.BindByName = true;
    OracleParameter p_guidCollection = sqlCmd.Parameters.Add("p_userguids", OracleDbType.Raw);
    p_guidCollection.Size = users.Count;
    p_guidCollection.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
    p_guidCollection.UdtTypeName = "t_guidtable";
    p_guidCollection.Value = users.ToArray();
    sqlCmd.Parameters.Add("groupname", OracleDbType.Varchar2, 30).Value = group;
    sqlCmd.ExecuteNonQuery();
    catch(Exception ex)
    System.Diagnostics.Debug.WriteLine(ex.ToString());
    finally
    conn.Close();
    }

    New question,
    How can I select records using "in" condition clause likes the following sentence?
    SELECT userguid, firstname, lastname FROM UserTable WHERE userguid in (SELECT column_value FROM TABLE(p_userguids))
    I tried using PIPE ROW like this, but ORACLE said "PLS-00629: PIPE statement cannot be used in non-pipelined functions"
    FOR i in p_userguids.first .. p_userguids.last
    LOOP
    SELECT userguid, firstname, lastname INTO l_userrecord FROM UserTable WHERE userguid=p_userguids(i);
    PIPE ROW(l_userrecord);
    END LOOP;

  • ODP 10.2.0.100 + anonymous PL/SQL block

    hi,
    my ODP dont wants anonymous PL/SQL blocks...
    my code:
    OracleConnection conn = new OracleConnection(sConnectionString);
    string text =
    "declare
    d int;
    begin
    SELECT nr INTO d FROM TMPTEXTS;
    end;
    OracleCommand cmd = new OracleCommand(text, conn);
    cmd.CommandType = CommandType.Text;
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
    // error message
    Oracle.DataAccess.Client.OracleException ORA-06550: Zeile 1, Spalte 1:
    PLS-00103: encountered the symbol "" expecting
    begin case declare exit for function ...
    any ideas ?
    lg dan

    The sample code at
    http://www.oracle.com/technology/oramag/oracle/06-jan/o16odpnet.html
    demonstrates using an anon block with a bind.

  • Create publicsynonyms for anonymous pl/sql block

    Hi,
    How do I create a public synonym for an anonymous PL/SQL block?
    BEGIN
         IF a IS NOT NULL
         THEN
              OPEN b;
              LOOP
                   FETCH b INTO Func;
              EXIT WHEN b%NOTFOUND;
                   c := c || Func || ',';
              END LOOP;
              CLOSE b;
              c := SUBSTR(c, 1, LENGTH(TRIM(c))-1);
         END IF;
         return c;
    END abc;
    ERROR at line 2:
    ORA-06550: line 2, column 5:
    PLS-00201: identifier 'a' must be declared
    ORA-06550: line 2, column 2:
    PL/SQL: Statement ignored
    ORA-06550: line 19, column 2:
    PLS-00372: In a procedure, RETURN statement cannot contain an expression
    ORA-06550: line 19, column 2:
    PL/SQL: Statement ignored

    Hi,
    CrackerJack wrote:
    Hi,
    How do I create a public synonym for an anonymous PL/SQL block?A synonym is an alternate name.
    Anonymous bblocks, by definition, don't have names, so they can't have alternate names. Also, they're not stored, so what good would it do if you could have synonyms for them?
    An anonymous block is just a quick and dirty alternative to a procedure, anyway. Why not make a procedure, or a function?
    BEGIN
         IF a IS NOT NULL
         THEN
              OPEN b;
              LOOP
                   FETCH b INTO Func;
              EXIT WHEN b%NOTFOUND;
                   c := c || Func || ',';
              END LOOP;
              CLOSE b;
              c := SUBSTR(c, 1, LENGTH(TRIM(c))-1);
         END IF;
         return c;
    END abc;
    ERROR at line 2:
    ORA-06550: line 2, column 5:
    PLS-00201: identifier 'a' must be declared
    ORA-06550: line 2, column 2:
    PL/SQL: Statement ignored
    ORA-06550: line 19, column 2:
    PLS-00372: In a procedure, RETURN statement cannot contain an expression
    ORA-06550: line 19, column 2:
    PL/SQL: Statement ignoredThis code looks like part of a function, that was named abc. Where is the beginning part of that function? The errors are caused because it is missing the part where this was declared as a function, and the part where the local variables a, c and func, and the cursor b, were defined.
    Does thsi function have something to do with the original question: "How do I create a public synonym for an anonymous PL/SQL block?"?
    What are you trying to do?

  • JDBC: send batch of SQL commands as anonymous PL/SQL block

    Hi All,
    I did a little measurement to see if I can improve jdbc
    applications by batching dissimilar SQL commands into one
    anonymous PL/SQL block and execute it once. To my surprise, for
    a batch of 5 SQL commands, it take 60% more time than execute
    each of the 5 SQL commands separately.
    The same JDBC code, using similar SQL text batching, running
    against Sybase or MSSQL shows 60%-300% improvement.
    Is there any other way to batch dynamic dissimilar SQL commands
    in Oracle other than using anonymous PL/SQL block? Here is an
    example of how the "text-batching" PL/SQL block looks like:
    "begin insert into testtab1(col1, col2) values(1, 'row1');
    insert into testtab2(col1, col2) values(100, 1);....; end;"
    Thanks,
    Nam Nguyen
    null

    If you do:
    declare
    l_sql varchar2(32767);
    l_value varchar2(32767);
    begin
    select query_sql into l_sql from lov where lov_id = 100;
    dbms_output.put_line(l_sql);
    end;
    You'll see something like that:
    SELECT
    l.DESCRIPTION || decode(l2.DESCRIPTION,null,'',l2.description, '-' || l2.description) || decode(a.DT,'Y',' - Distributed Training','N',null,null) as value1
    FROM ACTIVITY a
    ,MOUNTAINEERING m
    ,LOV l
    ,LOV l2
    WHERE a.JSATFA_ID = 82
    AND a.SPECIFIC_ACTIVITY_LOV_ID = l.LOV_ID
    AND m.ACTIVITY_ID(+) = a.ACTIVITY_ID
    AND m.CLASSIFICATION_LOV_ID = l2.LOV_ID(+);
    you need to duplicate the '
    you can do many things like:
    CTH@> select * from sqls;
    C
    select first_name || ' ' || last_name as value1 from employees where rownum=1
    1 fila seleccionada.
    CTH@>
    CTH@> ;
    1 declare
    2 l_sql varchar2(32767);
    3 l_value varchar2(32767);
    4 type generic_cursor is ref cursor;
    5
    6 c generic_cursor;
    7
    8 begin
    9 select replace(c, ''', ''''') into l_sql from sqls;
    10
    11 execute immediate l_sql into l_value;
    12 dbms_output.put_line(l_value);
    13* end;
    CTH@> /
    Ellen Abel
    Procedimiento PL/SQL terminado correctamente.
    CTH@>

  • Execute anonymous PL/SQL block via JDBC - OUT parameter not available

    I have a simple proc on the database:
    CREATE PROCEDURE TEST(X OUT BINARY_INTEGER, Y IN VARCHAR) AS
    BEGIN
      X := 33;
    END; I am trying to invoke it via JDBC using an anonymous PL/SQL block:
            try {
                Connection connection =
                  DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL",
                    "scott", "tiger");
                CallableStatement stproc_stmt = connection.prepareCall(
                    "DECLARE\n" +
                    " X_TARGET BINARY_INTEGER;\n" +
                    " Y_TARGET VARCHAR(20) := :2;\n" +
                    "BEGIN\n" +
                    " TEST(X=>X_TARGET, Y=>Y_TARGET);\n" +
                    " :1 := X_TARGET;\n" +
                    "END;"
                stproc_stmt.registerOutParameter(1, Types.NUMERIC);
                stproc_stmt.setString(2, "test");
                stproc_stmt.executeUpdate();
                Object o = stproc_stmt.getObject(1);
            catch (Exception e) {
                e.printStackTrace();
            } No exceptions are thrown, but the Object o does not get the value '33' - it is NULL.
    Any ideas?
    thanks in advance,
    Mike Norman

    I think the issue may be in how JDBC parameter binding is being managed throughout the block's lifecycle.
    The slightly-different TEST2 works:
    CREATE PROCEDURE TEST2(Y IN VARCHAR, X OUT BINARY_INTEGER) AS
    BEGIN
      X := 33;
    END;
    try {
        Connection connection =
          DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL",
         "scott", "tiger");
        CallableStatement stproc_stmt = connection.prepareCall(
         "DECLARE\n" +
         " Y_TARGET VARCHAR(20) := :1;\n" +
         " X_TARGET BINARY_INTEGER;\n" +
         "BEGIN\n" +
         " TEST2(Y=>Y_TARGET, X=>X_TARGET);\n" +
         " :2 := X_TARGET;\n" +
         "END;"
        stproc_stmt.setString(1, "test");
        stproc_stmt.registerOutParameter(2, Types.NUMERIC);
        stproc_stmt.executeUpdate();
        Object o = stproc_stmt.getObject(1);
    catch (Exception e) {
        e.printStackTrace();
    }The order of the bind indices ':1' and ':2' are reversed in the above anonymous block - we are returning via ':2'.
    I am wondering if 'under the covers' there isn't perhaps a cursor issue. When the original block is parsed and the first bind index is found to be position 2, somehow we can't go back to position 1 - a forwards-only cursor?

  • Running a anonymous PL/SQL block

    Hi,
    I have created an anonymous PL/SQL block and saved it in a file. And I am now trying to run it from the sql prompt using @.
    But this doesn't seem to be working. I get a wierd number as output and then it hangs.
    This is not the case if I copy paste the anonymous block. In this case I get the correct output.
    Please assist as to whether it is possible to run it using @ as it is important for me to do so..

    Hi,
    You forgot the slash after the anonymous block:
    USER is "YJAM"
    TEST>-- Create anonymous Block
    TEST>BEGIN
      2    NULL;
      3  END;
    4 /
    PL/SQL procedure successfully completed.
    TEST>-- save as script
    TEST>save ab.sql
    Created file ab.sql
    TEST>get ab
      1  BEGIN
      2    NULL;
      3* END;
    TEST>@ab
    PL/SQL procedure successfully completed.
    TEST>ed ab Here, I delete line 4. hence the Block won't run.
    TEST>@ab
      4
      5
      6
      7
      8  . a dot to exit input mode. a slash would run the block
    TEST>Regards,
    Yoann.

  • Anonymous PL SQL block runs in 2 minutes but runs for 4 hours in Applicatio

    We are facing an issue with a custom code. When we run the custom code as anonymous pl/sql block , it completes in 2 minutes.
    But when we run the same from Oracle Application as a concurrent program, it runs for more than 4 hours.
    There is absolute no change in the code.
    Anyone faced this issue?

    Does your code use context sensitive views such as po_headers?
    Maybe you have not set the context in the pl/sql block so the view returns 0 records.
    But when you run it in Apps, the context is automatically set and so it processes a large number of records.
    Set the context if you have not and then try again.
    begin
    dbms_application_info.set_client_info('&org_id'); --
    end;
    Sandeep Gandhi

  • Anonymous PL/SQL block within a select statement

    I read somewhere that it was possible to build an anonymous pl/sql block within a sql statement. Something along the lines of:
    select
    begin
    i = 0;
    return i;
    end;
    from dual;
    However, for the life of me, I can't find documentation on this. Could someone please point me to the right place, assuming I'm not just imagining it.
    Thanks.

    Did you mean, executing a pl/sql block generated from an sql.
    declare
    cmd varchar2(100);
    begin
    select 'declare i pls_integer := 0; begin i:=1; end;' into cmd from dual;
    execute immediate cmd;
    end;
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Dhcp server won't admit my Arch Linux (though Win's have no problems)

    1. Generally my dhcpcd works fine in every network (and always has, I have not changed anything substantial). 2. Currently I am in a network (for just a couple of weeks) in which it does not. 3. The network will ignore all my dhcp requests over both

  • Problem Purchase order created in SAP R/3 sent in to File XI?

    Hi all, I am new to XI, learning it myself. I am trying to "send purchase order created in SAP R/3 into XI". For that I am following the document titled as <b>"A Beginner’s Guide to SAP XI Settings, Part I "</b>. But I am getting problem in connectin

  • Data import for users of forms created with Livecycle Designer

    Hello, I have seen several posts regarding data import for forms created by Livecycle Designer but nothing that helps with something I am trying to accomplish.  I can create a data connection and import information in a form but what I would like to

  • Hierarchy dashboard prompt

    In the OBIEE 11.1.1.6, I make use of default RPD named 'SampleAppLite.rpd', and I created dashboard prompt for 'Product Hierarchy', however, in the request, there is no hierarchy, only has some columns, such as 'Brand','LOD' My issue is that the crea

  • Question about drop shadow...

    Hi, I need the drop shadow to still be visible around a cut out box shape. Can anyone tell me how to achieve this effect? (Please see attached picture). It may involve a compound clipping path but I'm not sure... I would need detailed step by step in