Tuesday, March 3, 2009

User-Raised Exception

The first time this program is run, the information from department 10 is displayed. The second time, an invalid department number is entered which displays a user-raised exception.
Set Serveroutput on Verify Off Feedback Off Trimspool On
--+----------------------------------------------------
--| Declaration section
--+----------------------------------------------------
Declare
v_DeptNo Emp.DeptNo%Type := &DeptNumber;

Cursor c_Salaries Is
Select Sal
, Ename
, Sum(Sal) Over (Partition By DeptNo)
As
Sum_Sal
From Emp
Where DeptNo = v_DeptNo;

v_Rec c_Salaries%Rowtype; /* All Columns */
v_Dept_Err Exception;
v_SqlCode Number;
v_SqlErrM Varchar2(255);
--+----------------------------------------------------
--| Execution section
--+----------------------------------------------------
Begin
Open c_Salaries;
----------------------------------------------------
Loop
Fetch c_Salaries Into v_Rec; -- v_Sal, v_Ename;
-----------------------------
If (c_Salaries%Rowcount = 0)
Then Raise v_Dept_Err;
End If;
-----------------------------
Exit When c_Salaries%Notfound;
Dbms_Output.Put_Line (v_Rec.Ename|| ' Earns ' ||
To_Char(v_Rec.Sal,'9,999'));
End Loop;
----------------------------------------------------
Close c_Salaries;
Dbms_Output.Put_Line (Chr(10)|| ' Total Salary = '
|| To_Char(v_Rec.Sum_Sal
, '$9,999,990'));
--+----------------------------------------------------
--| Exception Handling section
--+----------------------------------------------------
Exception
When v_Dept_Err
Then Dbms_Output.Put_Line ('Invalid Dept '
|| v_DeptNo);
v_SqlCode := SqlCode;
v_SqlErrM := SqlErrM;
Dbms_Output.Put_Line ('Error Code: '
|| To_Char(v_SqlCode)
|| ' Message: '
|| v_SqlErrM);
End;
/

No comments:

Post a Comment