简体   繁体   中英

Stored procedure exception handling

SQL>  DECLARE
2    TotalUpd   NUMBER(36) := 0;
3  BEGIN
4   dbms_output.put_line ('Job Start time............... : ' || to_char(SYSDATE, '             hh24:mi:ss'));
5   UPDATE Asset SET _status = 'PROGRESS' WHERE status is null;
6   TotalUpd := SQL%ROWCOUNT;
7   dbms_output.put_line('Total Records Updated. : ' || TotalUpd);
8    COMMIT;
9   EXCEPTION
10   WHEN NO_DATA_FOUND THEN
11  dbms_output.put_line ('No more data to update.');
12  WHEN OTHERS THEN
13  dbms_output.put_line ('Error while status as SUCCESS ');
14  END ;
15  /

The result for the above procedure is Job Start time............... : 04:41:41 Total Records Updated. : 0

But my expected result is "No more row to be updated" must be printed,since i have truncated the table Asset.Please tell where I went wrong in this.

it is as simple as the update does not geneate an error if there is no data.

you need to look at the value of TotalUpd if you want to control the flow of your code

 DECLARE 
 TotalUpd   NUMBER(36) := 0;
 BEGIN
    dbms_output.put_line ('Job Start time............... : ' 
        || TO_CHAR(SYSDATE, '             hh24:mi:ss'));
    UPDATE Asset SET _status = 'PROGRESS' WHERE status IS null;
    TotalUpd := SQL%ROWCOUNT; 
    IF TotalUpd = 0 THEN
        dbms_output.put_line ('No more data to update.');
    ELSE
        dbms_output.put_line('Total Records Updated. : '
            || TotalUpd);
    END IF; 
    COMMIT; 
 EXCEPTION 
 WHEN OTHERS THEN
    dbms_output.put_line ('Error while status as SUCCESS '); 
 END; 

The NO_DATA_FOUND error is not thrown in update statements.

It is thrown in select into statements if the select statement would return nothing.

See also Tahiti on select into under select_item : *If the SELECT INTO statement returns no rows, PL/SQL raises the predefined exception NO_DATA_FOUND.*

Oracle does not consider it an exception if an update statement does not update anything, hence no exception is thrown. However, if a select into statement cannot fill the variables, it is considered an error (and therefore in this case the NO_DATA_EXCEPTION is thrown(

NO_DATA_FOUND is thrown if a select into does not return any row, not if no rows were updated after an update statement.

I suggest you move your logic for handling this exception after the update itself:

IF (SQL%ROWCOUNT = 0) THEN  
  dbms_output.put_line ('No more data to update.');

Think NO_DATA_FOUND exception is only raised by a SELECT statement which you aren't using. Try testing SQL%COUNT and output as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM