OPEN out_cur FOR        SELECT  exception handling help

Here is the stored procedure for reading a data based on the input, if no data then return null ref cursor and proper error message.
I am not sure, i am handling proper exception handling ? Please help me to complete this item.
Thanks.
PROCEDURE testing
module IN VARCHAR2,
module_id IN VARCHAR2,
out_cur OUT SYS_REFCURSOR,
out_error_no OUT NUMBER
BEGIN
out_error_no := 0;
CASE
WHEN module = 'a' AND module_id = 'b' THEN
BEGIN
OPEN out_cur FOR
SELECT id,
mime_type,
file_length,
file_name ,
uploadeddate,
created_user ,
status_name
FROM l_table_cnt
WHERE id = module_id;
EXCEPTION
WHEN OTHERS THEN
OPEN out_cur_file_cursor FOR
SELECT
NULL id,
NULL mime_type,
NULL file_length,
NULL file_name,
NULL uploadeddate,
NULL created_user,
NULL status_name
FROM dual
WHERE 1= 0;
out_error_no := 2;
RAISE_APPLICATION_ERROR(-20024,'No Document ');
END;

Venkadesh wrote:
The correct way is to just open the ref cursor and pass it back and then the receiving code that is going to use that cursor handles whether there is any code in it or not. can you please explain with simple exampleIs it really that difficult?
Ok...
Here's the procedure to return a ref cursor...
SQL> ed
Wrote file afiedt.buf
  1  create or replace procedure get_rc(p_deptno in number, p_rc out sys_refcursor) is
  2  begin
  3    open p_rc for 'select * from emp where deptno = :1' using p_deptno;
  4* end;
SQL> /
Procedure created.Now we have some application that wants to consume a ref cursor... in this case the application is SQL*Plus, but it could be Java or .NET etc.
It declares it's local reference to the ref cursor...
SQL> var r refcursor;then calls the procedure to get a ref cursor reference assigned...
SQL> exec get_rc(10, :r);
PL/SQL procedure successfully completed.Now, the application itself determines if there is any data when it comes to actually perform the fetches on it...
SQL> print r;
     EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
      7782 CLARK      MANAGER         7839 09-JUN-1981 00:00:00       2450                    10
      7839 KING       PRESIDENT            17-NOV-1981 00:00:00       5000                    10
      7934 MILLER     CLERK           7782 23-JAN-1982 00:00:00       1300                    10in the above case it had data, so it displayed it.
So what if there isn't any data...
SQL> exec get_rc(90, :r);
PL/SQL procedure successfully completed.
SQL> print r;
no rows selected
SQL>SQL*Plus (the application that calls the procedure) is the one that has determined that there was not data when it came to fetch it (using the print statement in this case). And when it found there was no data it handled it itself (in this case printing the message "no rows returned").
The procedure doesn't have to do any overhead of determining if there is data going to be returned or not, because it's not it's responsibility and completely unnecessary. The calling application can easily determine if there is data or not when it starts to try and fetch it.

Similar Messages

  • Problem with OPEN My_Cursor FOR SELECT ...

    Please, I need some help here. I'm developing an ASP NET application with Crystal Reports and Oracle 9i as DB.
    I'm desining a report. I use a Stored Procedure (in a package). I know that in order to CR be able to read the stored procedure, I have to use Cursor in this way: OPEN My_Cursor FOR SELECT * FROM My_Table;
    The problem is that I need to do other sub-queries to get the names of 3 people (from TBL_TWO) and show them in my Cursor (from TBL_ONE). How can I do it? I tried as my example, but I get error when try to connect from ASP NET: "ORA-24338 statement handle not executed"
    Apparantly, CR needs to read just only OPEN My_Cursor FOR ... Is there any way to resolve this problem?
    PROCEDURE SP_REP_OP_03 (My_CURSOR OUT MY_REF_CURSOR,
    i_Cod_OP IN INTEGER)
    IS
    v_id_1 char(8);
    v_Names_1 varchar(25);
    v_id_2 char(8);
    v_Names_2 varchar(25);
    v_id_3 char(8);
    v_Names_3 varchar(25);
    BEGIN
    SELECT TWO.Id, PER1.Names -- may or may not exist
    INTO v_id_1, v_Names_1
    FROM TBL_TWO TWO, PADRON.PADRON PER1
    WHERE TWO.Cod_OP = i_cod_op AND
    TWO.Cod_Rep = '01' AND
    TWO.Id = PER1.Id;
    IF v_id_1 IS NULL THEN
    v_id_1:= '';
    v_Names_1:= '';
    END IF;
    SELECT TWO.Id, PER1.Names -- may or may not exist
    INTO v_id_2, v_Names_2
    FROM TBL_TWO TWO, PADRON.PADRON PER1
    WHERE TWO.Cod_OP = i_cod_op AND
    TWO.Cod_Rep = '02' AND
    TWO.Id = PER1.Id;
    IF v_id_2 IS NULL THEN
    v_id_2:= '';
    v_Names_2:= '';
    END IF;
    SELECT TWO.Id, PER1.Names -- may or may not exist
    INTO v_id_3, v_Names_3
    FROM TBL_TWO TWO, PADRON.PADRON PER1
    WHERE TWO.Cod_OP = i_cod_op AND
    TWO.Cod_Rep = '03' AND
    TWO.Id = PER1.Id;
    IF v_id_3 IS NULL THEN
    v_id_3:= '';
    v_Names_3:= '';
    END IF;
    -- I tried to "attach" v_id and v_Names to My_Cursor, but CR can't get it
    OPEN My_CURSOR FOR
    SELECT ONE.Cod_Exp AS Cod_Exp,
    ONE.Cod_Exp_OP AS Cod_Exp_OP,
    ONE.Cod_OP AS Cod_OP,
    ONE.cod_ficha AS cod_ficha,
    v_id_1 As id_1 ,
    v_Names_1 As Names_1,
    v_id_2 As id_2 ,
    v_Names_2 As Names_2,
    v_id_3 As id_3 ,
    v_Names_3 As Names_3,
    FROM TBL_ONE ONE
    WHERE OP.Cod_op = i_Cod_op;
    END SP_REP_OP_03;

    Why can't you just have a single SQL query that outer-joins the tables and returns the values you need? It looks like it should start in TBL_ONE and outer-join three times to TBL_TWO and PADRON, perhaps something like:
    SELECT one.cod_exp
         , one.cod_exp_op
         , one.cod_op
         , one.cod_ficha
         , id1.id AS id_1
         , per1.names AS names_1
         , id2.id AS id_2
         , per2.names AS names_2
         , id3.id AS id_3
         , per3.names AS names_3
    FROM   tbl_one one
         , tbl_two id1
         , padron.padron per1
         , tbl_two id2
         , padron.padron per2
         , tbl_two id3
         , padron.padron per3
    WHERE  one.cod_op = i_cod_op
    AND    id1.cod_op (+)= one.cod_op
    AND    id1.cod_rep (+)= '01'
    AND    per1.id (+)= id1.id
    AND    id2.cod_op (+)= one.cod_op
    AND    id2.cod_rep (+)= '02'
    AND    per2.id (+)= id2.id
    AND    id3.cod_op (+)= one.cod_op
    AND    id3.cod_rep (+)= '03'
    AND    per3.id (+)= id3.id;

  • OPEN lcur_trade_cursor FOR select Syntax

    HI I am new to cursors .i am seeing this code in my package .any help what the code in block will do?what for this is defined ?
    or can u please explain the behaviour of this cursor meaning the data how populated?
    I would like to understand especially this block in square brackets
    [rec
                        WHERE      rec.par_amt <> rec.fa_trade_quantity OR
              rec.original_face_amt <> rec.fa_original_face_amt OR
              ( rec.current_trade_status_cd = 'EX' AND rec.fa_trade_status_cd <> '12' OR
              (rec.current_trade_status_cd = 'SAVED' AND (rec.sent_to_downstream = 'N' or rec.sent_to_downstream IS NULL)
                        AND rec.fa_trade_status_cd <> '11') OR
              ((rec.current_trade_status_cd = 'PN' AND rec.sent_to_downstream = 'Y') AND rec.fa_trade_status_cd <> '11') OR
              rec.current_trade_status_cd = 'TR' AND rec.fa_trade_status_cd <> '12');]
    OPEN lcur_trade_cursor FOR
                        SELECT pv_cycle_date_i,
                        FI_S2O_TRD_DIFF_SEQ.NEXTVAL,
                        rec.trade_effective_dt AS fide_trd_eff_dt,
                        rec.pot_trade_id AS pot_trade_id,
                        rec.fa_trade_id AS fide_trade_id,
                        rec.transaction_alternate_id AS transaction_alternate_id,
                        rec.fi_instrument_id AS fi_instrument_id,
                        rec.portfolio_id AS portfolio_id,
                        'Trades in FIDE and UDE but difference in Par Amount or Original Face Value or Trade Status',
                        rec.par_amt AS ude_par_amt,
                        rec.original_face_amt AS ude_original_face_amt,
                        rec.fa_trade_quantity AS fide_par_amt,
    rec.fa_original_face_amt AS fide_original_face_amt,
                        rec.txn_source_system_cd AS fide_source_system,
                        rec.trade_src_cd AS ude_source_system,
                        rec.settlement_dt AS settlement_dt,
                        pv_recon_type_i,
                        SYSTIMESTAMP,
                   USER,
                   SYSTIMESTAMP,
                   USER,
                        SYSTIMESTAMP
                        FROM (
                             SELECT
                             trd.trade_effective_dt ,
                             trd.transaction_alternate_id ,
              ude.pot_trade_id ,
              trd.fa_trade_id ,
              trd.fi_instrument_id ,
              trd.portfolio_id ,
                             trd.fa_trade_quantity          ,
                             trd.fa_original_face_amt          ,
                             ude.par_amt ,
                             ude.original_face_amt ,
                             trd.txn_source_system_cd ,
                             ude.trade_src_cd ,
                             trd.settlement_dt ,
                             ude.current_trade_status_cd ,
                             trd.fa_trade_status_cd ,
                             trd.sent_to_downstream
                        FROM FUND_TRADE_V trd,
                                  STG_SYB_TRADES ude,
                                  FI_FUND_SUBPORTFOLIO sub,
                                  INSTRUMENT_ALTERNATE_ID ia
                        WHERE trd.trade_effective_dt >= pv_cycle_date_i
                        AND ude.trade_effective_dt >= pv_cycle_date_i
                        AND trd.transaction_alternate_id = ude.trade_sequence_nbr
                        AND ude.trade_effective_dt = trd.trade_effective_dt
                        AND ude.recon_type = pv_recon_type_i
                        AND trd.portfolio_id = sub.portfolio_id
                        AND ude.fund_nbr = sub.fund_nbr
                        AND ude.subportfolio_nbr = sub.subportfolio_nbr
                        AND trd.fi_instrument_id = ia.fi_instrument_id
                        AND ia.alternate_id_type_code ='FMR_CUSIP'
                        AND ude.fmr_cusip = ia.alternate_id
                        AND EXISTS
              ( SELECT 1
              FROM HLDGS_RECON_TAXBD_GRP_FUND_MV mm,
                                            FUND fnd
              WHERE mm.parent_grp = 'OMS_FUND'
              AND mm.member_grp = 'MM_FUND'
              AND mm.fund_nbr = ude.fund_nbr
                                  AND mm.fund_nbr     = fnd.fund_nbr
                                  AND fnd.fund_ending_dt IS NULL
                   ) rec
                        WHERE      rec.par_amt <> rec.fa_trade_quantity OR
              rec.original_face_amt <> rec.fa_original_face_amt OR
              ( rec.current_trade_status_cd = 'EX' AND rec.fa_trade_status_cd <> '12' OR
              (rec.current_trade_status_cd = 'SAVED' AND (rec.sent_to_downstream = 'N' or rec.sent_to_downstream IS NULL)
                        AND rec.fa_trade_status_cd <> '11') OR
              ((rec.current_trade_status_cd = 'PN' AND rec.sent_to_downstream = 'Y') AND rec.fa_trade_status_cd <> '11') OR
              rec.current_trade_status_cd = 'TR' AND rec.fa_trade_status_cd <> '12');
    Edited by: 945400 on Aug 23, 2012 3:24 AM

    This is one of those situations where if you formatted the code for readability the answer falls right out.
    OPEN lcur_trade_cursor FOR
    SELECT pv_cycle_date_i,
           FI_S2O_TRD_DIFF_SEQ.NEXTVAL,
           rec.trade_effective_dt AS fide_trd_eff_dt,
           rec.pot_trade_id AS pot_trade_id,
           rec.fa_trade_id AS fide_trade_id,
           rec.transaction_alternate_id AS transaction_alternate_id,
           rec.fi_instrument_id AS fi_instrument_id,
           rec.portfolio_id AS portfolio_id,
           'Trades in FIDE and UDE but difference in Par Amount or Original Face Value or Trade Status',
           rec.par_amt AS ude_par_amt,
           rec.original_face_amt AS ude_original_face_amt,
           rec.fa_trade_quantity AS fide_par_amt,
           rec.fa_original_face_amt AS fide_original_face_amt,
           rec.txn_source_system_cd AS fide_source_system,
           rec.trade_src_cd AS ude_source_system,
           rec.settlement_dt AS settlement_dt,
           pv_recon_type_i,
           SYSTIMESTAMP,
           USER,
           SYSTIMESTAMP,
           USER,
           SYSTIMESTAMP
      FROM (SELECT trd.trade_effective_dt,
                   trd.transaction_alternate_id,
                   ude.pot_trade_id,
                   trd.fa_trade_id,
                   trd.fi_instrument_id,
                   trd.portfolio_id,
                   trd.fa_trade_quantity,
                   trd.fa_original_face_amt,
                   ude.par_amt,
                   ude.original_face_amt,
                   trd.txn_source_system_cd,
                   ude.trade_src_cd,
                   trd.settlement_dt,
                   ude.current_trade_status_cd,
                   trd.fa_trade_status_cd,
                   trd.sent_to_downstream
              FROM FUND_TRADE_V trd,
                   STG_SYB_TRADES ude,
                   FI_FUND_SUBPORTFOLIO sub,
                   INSTRUMENT_ALTERNATE_ID ia
             WHERE     trd.trade_effective_dt >= pv_cycle_date_i
                   AND ude.trade_effective_dt >= pv_cycle_date_i
                   AND trd.transaction_alternate_id = ude.trade_sequence_nbr
                   AND ude.trade_effective_dt = trd.trade_effective_dt
                   AND ude.recon_type = pv_recon_type_i
                   AND trd.portfolio_id = sub.portfolio_id
                   AND ude.fund_nbr = sub.fund_nbr
                   AND ude.subportfolio_nbr = sub.subportfolio_nbr
                   AND trd.fi_instrument_id = ia.fi_instrument_id
                   AND ia.alternate_id_type_code = 'FMR_CUSIP'
                   AND ude.fmr_cusip = ia.alternate_id
                   AND EXISTS
                          (SELECT 1
                             FROM HLDGS_RECON_TAXBD_GRP_FUND_MV mm, FUND fnd
                            WHERE     mm.parent_grp = 'OMS_FUND'
                                  AND mm.member_grp = 'MM_FUND'
                                  AND mm.fund_nbr = ude.fund_nbr
                                  AND mm.fund_nbr = fnd.fund_nbr
                                  AND fnd.fund_ending_dt IS NULL)) rec
    WHERE    rec.par_amt != rec.fa_trade_quantity
           OR rec.original_face_amt != rec.fa_original_face_amt
           OR (       rec.current_trade_status_cd = 'EX'
                  AND rec.fa_trade_status_cd != '12'
               OR (    rec.current_trade_status_cd = 'SAVED'
                   AND (   rec.sent_to_downstream = 'N'
                        OR rec.sent_to_downstream IS NULL)
                   AND rec.fa_trade_status_cd != '11')
               OR (    (    rec.current_trade_status_cd = 'PN'
                        AND rec.sent_to_downstream = 'Y')
                   AND rec.fa_trade_status_cd != '11')
               OR     rec.current_trade_status_cd = 'TR'
                  AND rec.fa_trade_status_cd != '12');'rec' is an alias for a query defined in the FROM clause.

  • Open sys_refcursor for select from table variable?

    Hi,
    I've got a challenge for you! :-)
    I've got a procedure that has a lot of logic to determine what data should be loaded into a table variable. Because of various application constraints, i can not create a global temporary table. Instead, i'd like to create a table variable and populate it with stuff as i go through the procedure.
    The end result of the procedure is that i must be able to pass the results back as a sys_refcursor. This is a requirement that is beyond my control as well.
    Is there a way to make this sort of procedure work?
    Create Or Replace Procedure Xtst
    Mu_Cur In Out Sys_Refcursor
    Is
    Type Xdmlrectype Is Record (Col1 Varchar2(66));
    Type Xdmltype Is Table Of Xdmlrectype;
    Rtn Xdmltype;
    Begin
    Select Internal_Id Bulk Collect Into Rtn From Zc_State;
    open mu_cur for select col1 from table(rtn);
    end;
    11/42 PLS-00642: local collection types not allowed in SQL statements
    11/36 PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    11/19 PL/SQL: SQL Statement ignored
    Show Errors;

    Not anything i'd want to personally implement.
    But for educational purposes only of course....
    create table this_will_be_gross
       column1 number,
       column2 varchar2(30)
    insert into this_will_be_gross values (1, 'begin the ugliness');
    insert into this_will_be_gross values (2, 'end the ugliness');
    variable x refcursor;
    ME_XE?
    declare
       Rtn sys.ODCIVARCHAR2LIST;
    BEGIN
       SELECT
          column1 || '-' || column2 Bulk Collect
       INTO
          Rtn
       FROM
          this_will_be_gross;
       OPEN :x FOR
       SELECT 
          regexp_substr (column_value, '[^-]+', 1, 1) as column1,
          regexp_substr (column_value, '[^-]+', 1, 2) as column2      
       FROM TABLE(CAST(rtn AS sys.ODCIVARCHAR2LIST));
    end;
    17  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.09
    ME_XE?
    ME_XE?print :x
    COLUMN1                        COLUMN2
    1                              begin the ugliness
    2                              end the ugliness
    2 rows selected.
    Elapsed: 00:00:00.11In the above example i 'knew' that a hypen was a safe character to use to break up my data elements (as it would not be found anywhere in the data itself).
    I would strongly encourage you not to implement something like this. I realize it's tempting when you are working in strict environments where it can take a serious battle to get structures like temporary tables or SQL Types created, but that's really the proper approach to be taking.

  • Best Practice for Implementing Exception Handling in BPEL

    Hi All,
    what is the best practice and the approach to follow Exception Handling in BPEL.
    1) Do we need to implement Exception Handling in BPEL as we do in Java, means
         method 3 throws error to method 2 (if any) and
         method 2 throws error to method 1 (if any) and
         finally method 1 throws error to the main Class.
    If we replicate the above scenario to BPEL
    In BPEL main Scope have Custom Fault, Catch ALL
         Each Invoke is surrounded by a Scope Activity with Remote Fault, Binding Fault & Custom Fault
    and follow the paradigm of Java, assuming we have Inner Scopes
         [ OR ]
    2) In BPEL main Scope have all exceptions defined like
         Remote Fault,
         Binding Fault,
         anyOther System Fault (selectionFailure / forcedTermination),
         Custom Fault (if required) and
         CatchALL
         and also
         each Invoke is surrounded by a Scopes Acitivity with Custom Fault (business fault) exception Handling
    I feel 1st one may not be a good practice, may be i am wrong...
    Any Suggestions from experts.
    Thanks in Advance
    anvv sharma

    Hi-
    In you can create different scope and use catch branch to catch binding, remote, custom faults, business faults etc. If an error happens in a scope it will not move to the next scope( eg: you have 3 scope, error occured in 2nd scope then it will not propogate to the 3rd scope. One thing to be noticed here is your transaction in the 1st scope doesnt gets commited when an error happens in 2d scope).
    You can have a catch all to catch error which are not being caught at catch level. So if any error happens which is not defined in catch block then then it will be caught in catch all branch.
    Edited by: 333333 on Apr 12, 2011 9:39 AM

  • Exception Handling -- Help pls.

    This is the function that calculates cost taking deatils from two other tables .could you help me how handle exception for the second select statement, Which will have no value at some stage and also it will return multiple values.
    CREATE OR REPLACE FUNCTION get_cost_value
    (provis_id number,fyr_id number)
    return number
    as
    commi_id number;
    costperunit number;
    units_p number;
    weeklycost number;
    cost number := 0;
    weeks number;
    pro_s_date date;
    pro_e_date date;
    v_flag varchar2(1);
    begin
    begin
    select actual_start_date, actual_end_date
    into pro_s_date,pro_e_date
    from provisions
    where
         identifier = provis_id;
    exception
    WHEN no_data_found THEN
         v_flag := 'N';
    END;
    [b]for x in
    (select identifier, units_provided
    from cost_commitments
    where
    provis_identifier = provis_id)
    loop
    commi_id := x.identifier;
    units_p := x.units_provided;
    if v_flag != 'N'
    then
    costperunit := to_number(get_rate_value(pro_s_date,provis_id,commi_id));
    weeks := num_weeks(pro_e_date,fyr_id);
    cost := units_p * costperunit * weeks;
    else
    cost := 0;
    end if;
    return cost;
    end loop;
    end;
    /*EXCEPTION
    WHEN no_data_found THEN
    v_flag := 'N';*/

    Isn't it what you need ?
    SQL> var flag char(1);
    SQL> var dept number;
    SQL> exec :flag := 'Y';
    PL/SQL procedure successfully completed.
    SQL> exec :dept := 10;
    PL/SQL procedure successfully completed.
    SQL> declare
      2   cnt number;
      3  begin
      4   for v in (select empno from emp where deptno = :dept) loop
      5    cnt := 1;
      6   end loop;
      7   if cnt is null then
      8    raise no_data_found;
      9   end if;
    10  exception
    11    when no_data_found then
    12     :flag := 'N';
    13  end;
    14  /
    PL/SQL procedure successfully completed.
    SQL> print flag
    FLAG
    Y
    SQL> exec :dept := 100;
    PL/SQL procedure successfully completed.
    SQL> declare
      2   cnt number;
      3  begin
      4   for v in (select empno from emp where deptno = :dept) loop
      5    cnt := 1;
      6   end loop;
      7   if cnt is null then
      8    raise no_data_found;
      9   end if;
    10  exception
    11    when no_data_found then
    12     :flag := 'N';
    13  end;
    14  /
    PL/SQL procedure successfully completed.
    SQL> print flag
    FLAG
    NRgds.

  • Report for CRM-Opportunities - Open CRMD_ORDER for selected ALV row

    Hello,
    i created a report which can be used to find the relevant opportunities and list them in a ALV table.
    I have the requirement that by doubleclick on the table line the selected opportunity shall open in tx crmd_order.
    I have the GUID and the object_id of the opportunity in my ALV tableline.
    Has anybody already experience how to achieve this?
    Thank you
    Best regards
    Manfred

    It works perfectly for me. Look at the code (this works)
    REPORT ytestfhe3.
    DATA: gv_1o_manag    TYPE REF TO cl_crm_1o_manag,
          gv_1o_main     TYPE REF TO cl_crm_1o_main.
    DATA: gv_dynnr       TYPE sydynnr.
    DATA: gv_1o_frame_pa TYPE crmt_1o_frame_pa.
    DATA: gv_guid        TYPE crmt_object_guid.
    DATA: gv_boolean     TYPE crmt_boolean VALUE 'X'.
    PARAMETERS: p_order TYPE crmd_orderadm_h-object_id.
    START-OF-SELECTION.
      SELECT SINGLE guid FROM crmd_orderadm_h
                         INTO gv_guid
                        WHERE object_id EQ p_order.
    END-OF-SELECTION.
      gv_1o_frame_pa-transaction_guid = gv_guid.
      CREATE OBJECT gv_1o_manag
        EXPORTING
          iv_with_navig  = gv_boolean
          iv_1o_frame_pa = gv_1o_frame_pa.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno
                   WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        EXIT.
      ENDIF.
      CALL METHOD gv_1o_manag->get_main_screen
        IMPORTING
          ev_dynnr = gv_dynnr.
      CALL FUNCTION 'CRM_1O_MANAG_CALL_SCREEN_UI'
        EXPORTING
          iv_dynnr       = gv_dynnr
          iv_1o_frame_pa = gv_1o_frame_pa.

  • FOR Loop Exception Handling

    Given the following code:
    for x in my_cursor loop
        begin
            <<stmt_1>>
            <<stmt_2>>
        exception
            when others then
                <<log_error>>
        end;
    end loop;Say there are 5 x's in my_cursor. On element x3, stmt_1 works fine but stmt_2 throws an exception. I'd like to rollback ONLY the work done on x3 (in this case, stmt_1), then continue the loop from the next element, x4. Can this be achieved with some combination of savepoint/rollback?

    As I said, you can put the increment operation at the end of the block when you know no more exceptions could be raised, i.e.
    declare
        cnt number;
        ex  exception;
    begin
        cnt := 0;
        for x in 1..5 loop
            begin
                savepoint s;
                insert into test_tbl values(1/(3-x));
                cnt := cnt+1;
            exception
                when others then
                    rollback to savepoint s;
            end;
        end loop;
        dbms_output.put_line('cnt='||cnt);
    end;You could also increment the counter outside of the PL/SQL block, i.e.
    declare
        cnt number;
        ex  exception;
        num_success number;
    begin
        cnt := 0;
        for x in 1..5 loop
            begin
                num_success := 0;
                savepoint s;
                insert into test_tbl values(1/(3-x));
                num_success := sql%rowcount;
            exception
                when others then
                    rollback to savepoint s;
            end;
            cnt := cnt + num_success;
        end loop;
        dbms_output.put_line('cnt='||cnt);
    end;And you can refactor your code so that the components to hide some of this complexity, i.e.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure try_insert_test_tbl(
      2    p_val in number,
      3    p_num_success out number )
      4  as
      5    divide_by_zero exception;
      6    pragma exception_init( divide_by_zero, -1476 );
      7  begin
      8    savepoint s;
      9    insert into test_tbl values( 1/(3-p_val ) );
    10    p_num_success := sql%rowcount;
    11  exception
    12    when divide_by_zero
    13    then
    14      p_num_success := 0;
    15* end;
    SQL> /
    Procedure created.
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2      cnt number;
      3      ex  exception;
      4      num_success number;
      5  begin
      6      cnt := 0;
      7      for x in 1..5 loop
      8          try_insert_test_tbl( x, num_success );
      9          cnt := cnt + num_success;
    10      end loop;
    11      dbms_output.put_line('cnt='||cnt);
    12* end;
    SQL> /
    cnt=4
    PL/SQL procedure successfully completed.There is no way for DCL statements to affect the state of PL/SQL variables. But you can generally structure your code in such a way that this is unnecessary.
    Justin

  • Noob Exception Handling Help

    OK, basicly. Theres 3 fields. If a user enters data into 1 of the fields, it searches and prints something out of the DB. But if a user enters nothing it should throw an error telling them to input something. It all occurs in the doGet. Experts.. halp?
    import javax.servlet.http.*;
    import java.sql.*;
    import java.io.*;
    public class PizzaQuery extends HttpServlet
    private Statement st;
    private Connection con;
    private     String sRecords = new String();
    private String sSQL = new String();
    private String sMessage = new String();
    private final String url = "jdbc:odbc:Pizza";
    private PrintWriter out;
         public void init(){
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con = DriverManager.getConnection(url);
              catch (ClassNotFoundException e)
                   sMessage = "Failed to load the driver" +e;
              catch (SQLException e)
                   sMessage = "Unable to connect"+e;
              public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
                   try
                   if (req.getParameter("Name") != null) {
                        String name = req.getParameter("Name");
                        sSQL = "SELECT * FROM PizzaOrder WHERE Name=?";
                        PreparedStatement ps = con.prepareStatement(sSQL);
                        ps.setString(1,name);
                        ResultSet rec = ps.executeQuery();
                        while (rec.next())
                             sRecords += "<tr><td>" + rec.getString(1);
                             sRecords += "</td><td>" + rec.getString(2);
                             sRecords += "</td><td>" + rec.getString(3);
                             sRecords += "</td><td>" + rec.getString(4);
                             sRecords += "</td><td>" + rec.getString(5);
                             sRecords += "</td><td>" + rec.getString(6);
                             sRecords += "</td></tr>";
                   if (req.getParameter("City") != null) {
                        String city = req.getParameter("City");
                        sSQL = "SELECT * FROM PizzaOrder WHERE City=?";
                        PreparedStatement ps = con.prepareStatement(sSQL);
                        ps.setString(1,city);
                        ResultSet rec = ps.executeQuery();
                        while (rec.next())
                             sRecords += "<tr><td>" + rec.getString(1);
                             sRecords += "</td><td>" + rec.getString(2);
                             sRecords += "</td><td>" + rec.getString(3);
                             sRecords += "</td><td>" + rec.getString(4);
                             sRecords += "</td><td>" + rec.getString(5);
                             sRecords += "</td><td>" + rec.getString(6);
                             sRecords += "</td></tr>";
                   if(req.getParameter("Size") != null) {
                        String size = req.getParameter("Size");
                        sSQL = "SELECT * FROM PizzaOrder WHERE Size=?";
                        PreparedStatement ps = con.prepareStatement(sSQL);
                        ps.setString(1,size);
                        ResultSet rec = ps.executeQuery();
                        while (rec.next())
                             sRecords += "<tr><td>" + rec.getString(1);
                             sRecords += "</td><td>" + rec.getString(2);
                             sRecords += "</td><td>" + rec.getString(3);
                             sRecords += "</td><td>" + rec.getString(4);
                             sRecords += "</td><td>" + rec.getString(5);
                             sRecords += "</td><td>" + rec.getString(6);
                             sRecords += "</td></tr>";
                   if (sRecords != null)
                        res.setContentType("text/html");
                        out = res.getWriter();
                        out.println("<b><u>Pizza Orders</u></b><br /><br /><table border = 6>");
                        out.println("<th>Order</th><th>Name</th><th>Address</th><th>City</th><th>Size</th><th>Toppings</th>");
                        out.println(sRecords);
                        out.println("</table>");     
                        out.println("<br>");     
                        out.println("<br>");                    
                   } else {
                        sMessage = "Please input SOMETHING!";
                        out.println(sMessage);     
                   sRecords ="";
                   catch (SQLException e)
                        sMessage = "Failed to submit data "+e;
              public void destroy()
                   try
                        st.close();
                        con.close();     
                   catch (SQLException e)
                        sMessage = "Database not closed " + e;
    }

    FuNk wrote:
    Exacly rayom. It just doens't want to work?...
    rayom, flounder, can i show you through vnc if you have time?No.
    Well here is something you could do that is less ideal but should work.
    boolean isProcessed = false;
    if(A){
      // do A
      isProcessed = true;
    if((!isProcessed)&&(B)){
      // do B
      isProcessed = true;
    if((!isProcessed)&&(C)){
      // do C
      isProcessed = true;
    if(!isProcessed){
      // user did not supply ANY values. say something here.
    }That's an idea anyway. It's copying the if else structure which I suppose you got lost in the braces somewhere or something. But give it a shot.
    Have to walk my dog and eat dinner now so don't panic if I'm not back for awhile.

  • Exception handling help

    I am working on JTable.
    Vector properties = MainFrame.getPropertyList(Object);
    if(properties.size() > 1) {
    tm.setDataVector(properties, colNames);
    txtProperties.setText(dataModelObject.toString());
    else {
    if the properties i.e the vector is null I want to throw an exception i.e in the else part of the code. Which says the not valid properties or something like that.
    I don't know how to write an exception. Need help with this. Thanks.

    Create a new Exception Class. All exceptions of class "Exception" or subclasses thereof--except
    "RuntimeException"s--must be caught.
    RuntimeException:
    public class NullDefException extends RuntimeException
    String errorMsg;
    public void NullDefException(String errorMsg){
    this.errorMsg=errorMsg;
    public String getErrorMsg()
    return errorMsg;
    If NullDefException is not a "RuntimeException", the Java compiler would ask you to either "try-catch"
    "NullDefException " or declare it in the throws clause of the method.
    public class NullDefException extends Exception{
    String errorMsg;
    public void NullDefException(String errorMsg){
    this.errorMsg=errorMsg;
    public String getErrorMsg()
    return errorMsg;
    Method with throws clause:
    public void DataVector throws NullDefException(){
    Vector properties = MainFrame.getPropertyList(Object);
    if(properties==null)
    throw NullDefException;
    if(properties.size() > 1) {
    tm.setDataVector(properties, colNames);
    txtProperties.setText(dataModelObject.toString());
    else {
    Method with try-catch:
    public void DataVector (){
    try{
    Vector properties = MainFrame.getPropertyList(Object);
    if(properties.size() > 1) {
    tm.setDataVector(properties, colNames);
    txtProperties.setText(dataModelObject.toString());
    else {
    catch(NullDefException e){System.out.println("NullDefException:"+e.getErrorMsg);}
    }

  • Exception Handling - Help me out here

    This is my program...
    public void addTransaction() {
    data.addElement(JOptionPane.showInputDialog("Enter Transaction Number: "));
    data.addElement(JOptionPane.showInputDialog("Enter Name of Client: ")); data.addElement(JOptionPane.showInputDialog("Enter Transaction Type: "));     
    data.addElement(JOptionPane.showInputDialog("Enter Account Number: "));
    data.addElement(JOptionPane.showInputDialog("Enter the Total Amount: "));
    where "data" is a vector element.
    i need to make sure that a valid input is entered for each Input Dialog. If there is no input, the same dialog box should appear until a valid input is entered...

    Do not crosspost: http://forum.java.sun.com/thread.jsp?forum=54&thread=353639

  • OPEN ....... FOR 'SELECT...........with references to string var

    I am having a problem refencing a string variable within the WHERE clause of an OPEN statement, where DATASET is a ref cursor and the string variables are defined below. Sorry if too much detail below.
    Thank you for any help,
    Scott
    Error msg = ORA-00904: invalid column name
    strInvCountTableName := 'cats_invcount' || to_char(sysdate, 'MMDDYYHH24MISS');
    strUsageTableName := 'cats_partusage'|| to_char(sysdate, 'MMDDYYHH24MISS');
    strCSSLType := 'S';
    strPDType := 'P';
    strVanType := 'V';
    strMCDCType := 'M';
    strSpareStatus := 'S';
    strAvailableStatus := 'A';
    OPEN dataset FOR 'SELECT
    Inv.PARTID, Inv.LOCATIONDETAILID,Inv.Total,Inv.Average,
    Part.PARTCODE,Part.MFGPARTNUMBER,Part.MANUFACTURER,Part.DESCRIPTION,
    (Usg.USAGECOUNT/Inv.Average) TURN,Usg.USAGECOUNT,Usg.USAGECODE,
    Ldel.LOCATIONDETAILCODE,
    Loc.NAME LOCATIONNAME,Loc.REGION,Loc.MTA
    FROM ' || <<this
    strInvCountTableName || ' Inv,' || <<works
    strUsageTableName || ' Usg, <<fine
    CATS_PART PART,
    CATS_LOCATIONDETAIL LDEL,
    CATS_LOCATION LOC,
    CATS_LOCATIONSTATUS STAT,
    CATS_LOCATIONTYPE TYP
    WHERE
    Inv.PARTID = Usg.PARTID AND
    Inv.LOCATIONDETAILID = Usg.LOCATIONDETAILID AND
    Inv.PARTID = Part.PARTID AND
    Inv.LOCATIONDETAILID = Ldel.LOCATIONDETAILID AND
    Ldel.LOCATIONID = Loc.LOCATIONID AND
    Ldel.LOCATIONSTATUSID = STAT.LOCATIONSTATUSID AND
    Loc.LOCATIONTYPEID = TYP.LOCATIONTYPEID AND
    (STAT.CODECOMPONENT = ' || strSpareStatus || ' AND << this does not work
         (TYP.CODECOMPONENT = ' || strCSSLType || ' OR <<
    TYP.CODECOMPONENT = ' || strPDType || ' OR << i've tried putting literals in " "
    TYP.CODECOMPONENT = ' || strVanType || ') OR << but still no luck
    (STAT.CODECOMPONENT = ' || strAvailableStatus || ' AND <<
         TYP.CODECOMPONENT = ' || strMCDCType || '))'; <<

    This is just the 'double single quote' problem. Just add two single quotes around the reference - these two quotes will resolve to a single quote:
    (STAT.CODECOMPONENT = ''' || strSpareStatus || ''' ANDor
    (STAT.CODECOMPONENT = ''S'' AND

  • F4 Help for selecting the file

    Hi All,
    I want to select the file into my selection screen by providing the browsing option for user to locate the file.
    But i want only '.CSV' files to be displayed. I am not sure if f4_filename provides option to restrict file type to '.csv' instead of '.*'.
    I tried the fm 'KD_GET_FILENAME_ON_F4' .It has an option mask where i can enter the file type.The file type which i enter comes in the file dialog box but those files are not available for selecting.
    Kindly help me in this regard.
    Regards,
    S.Subasree

    hi,
    have you pass all the value which is shown in the below code
    CALL FUNCTION 'KD_GET_FILENAME_ON_F4'
    EXPORTING
       PROGRAM_NAME        = SYST-REPID
       DYNPRO_NUMBER       = SYST-DYNNR
       FIELD_NAME          = 'P_FILE '
       STATIC              = 'X'
       MASK                = '.excel , *.xls '
      CHANGING
        file_name           = p_file
    EXCEPTIONS
       MASK_TOO_LONG       = 1
       OTHERS              = 2          .
    IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    hope this hwlps
    Regards
    Ritesh

  • Open cursor for string and select from partition (cannot bind)

    Hi,
    i don't manage to use a bind variable for a select ... from ... PARTITION(...).
    It doesn't work to use something like
    open cur for 'select ... from ... PARTITION(:1) where ...' using 'NDAY_20120301';So i have to create the cursor string with string functions each time i change the partition.
    But that means, that the string changes each time.
    Doesn't that prevent from re-use in library_cache?
    best regards,
    Frank

    >
    So i have to create the cursor string with string functions each time i change the partition.
    But that means, that the string changes each time.
    >
    Yes it does.
    Doesn't that prevent from re-use in library_cache?
    >
    Yes it does.
    So why do you care? Unless you have large numbers of partitions what difference does it make? Bind variables are useful to keep Oracle from doing hard parses of queries that are basically the same but use different filter values. Such as an INSERT statement that uses different values FOR EACH ROW rather
    You are just constructing the main (non-filter) part of the query one time and need a single value for the entire query regardless of how many rows - that isn't really a use case for bind variables and isn't going to provide any real benefit.
    So the real question is why do you even care about something that wouldn't provide any benefit to you even if you could do it?
    Looks like you just want to 'roll your own' parallel processing rather that use, and pay for, Oracle's parallel functionality.
    If each partition uses its own tablespace you could filter on the FILE Id of the ROWIDs since the file number will be different for each tablespace and datafile.
    1. Determine the list of file numbers for each partitions tablespace.
    2. Use a WHERE DBMS_ROWID.ROWID_RELATIVE_FNO (ROWID) = :n filter (or use IN (:n1, :n2))to filter rows based on file number(s) for the partition you want
    See DBMS_ROWID.ROWID_RELATIVE_FNO in the PL/SQL Packages and Types doc
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_rowid.htm#i1004259

  • Good exception handling policy for Java web application

    I'm looking for a good exception handling policy for Java web application. First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
    Then I found this Oracle page The Message-Driven Bean Class - The Java EE 6 Tutorial, which does just that. So now I'm confused. Is there a good page online for an exception handling policy for Java EE Web applications? I have a hard time finding one. I've read that you should not catch the Exception class. I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop. We have a loop which runs once a minute implemented using the Quartz framework. Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.

    I'm looking for a good exception handling policy for Java web application.
    If you have not done so I suggest you start by reviewing the several trails in The Java Tutorials.
    Those trails cover both HOW to use exceptions and WHEN to use them.
    This trail discusses  the 'controversy' you mention regarding 'Unchecked Exceptions'
    http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
    Unchecked Exceptions — The Controversy
    Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
    Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
    The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
    Generally don't catch an exception unless you plan to HANDLE the exception. Logging, by itself is NOT handliing.
    First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace(); 
    That article, like many, has some good advice and some poor or even bad advice. You get what you pay for!
    I've read that you should not catch the Exception class.
    Ok - but all that does is indicate that a problem of some sort happened somewhere. Not very useful info. Java goes to a lot of trouble to provide specific exceptions for specific problems.
    I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop.
    If the exception is 'unknown' then maybe it NEEDS to 'stop all other customers from executing later on in the loop'.
    That is EXACTLY why you don't want to do that. You need to identify which exceptions should NOT stop processing and which ones should.
    Some 'unknown' exceptions can NOT be recovered and indicate a serious problem, perhaps with the JVM itself. You can NOT just blindly keep executing and ignore them without risking data corruption and/or the integrity of the entire system Java is running on.
    Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.
    No - not if you want a well-behaved system.
    Don't catch exceptions unless you HANDLE/resolve them. There are times when it makes sense to log the exception (which does NOT handle it) and then raise it again so that it gets handled properly later. Yes - I know that is contrary to the advice given in that article but, IMHO, that article is wrong about that point.
    If you have ever had to maintain/fix/support someone else's Java code you should already understand how difficult it can be to find WHERE a problem occurs and WHAT the exact problem is when exceptions are not handled properly.

Maybe you are looking for

  • Sharing one music library between two users on a mac

    I want to set my wife up as a separate user on my mac and share my music file with her so we no longer mix up our iPhone apps. I don't want a second copy on my hard drive. I've tried one method on here HT1203 but it makes a second copy and fills up m

  • IPod Touch video out to Composite "Hard Starting"!

    Did you ever own a car that was a beast to start on a cold winter morning? Well, same thing with my iPod Touch 4 to a composite video display.  I connect it, then go to YouTube to play a video or into my Movies folder to play one of my own. I press p

  • Equipment is common for both the plants.How to differentiate the cost seperatly

    Hi Guys, Maintenance plants are Ex:2076 and 2023 and planning is done by 2076 for both the plants.Equipments is unique for both the plants. Suppose for example i have a equipment installed in 2023 and i will have the cost center of 2023 plant.When i

  • Allocation of Cost based on Match for 2 Dimensions

    Hi Experts, We are running an allocation where we assign an expense account balance (transportation costs) based on the combination of the dimensions entity and country.  Please see the attached for a full example. A brief example: ORIGINAL DATA Enti

  • Colors printing blue instead of yellow, red and brown

    Red yellow and brown colors in a flower, print as shades of blue in PSE 7.  Violet colors print as pink.  Green prints as green. The colors print more accurately in photoshop album starter than PSE 7 so I don't think it's my HP laserjet 2605 printer