Wednesday, March 18, 2009

Instead of Trigger

Scott wants to create a view of salary totals by department. He will need to be granted that privilege by System.
SQL> Connect System/******
Connected.
SQL> Grant Create View To Scott;
Grant succeeded.
SQL> Connect Scott/Tiger
Connected.

Create or Replace View v_TotSal
As
Select DeptNo
------------------
, Sum(Sal) As
SumSal
------------------
From Emp
Group By DeptNo
Order By DeptNo;


View created.

SQL> Select *
2 From v_TotSal;

DEPTNO SUMSAL
------ ---------
10 $9,268
20 $11,065
30 $10,055
If you try to delete one of the rows in this view, you are stopped with an ORA error.
SQL> Delete From v_TotSal
2 Where DeptNo = 10;
Delete From v_TotSal
*
ERROR at line 1:
ORA-01732: data manipulation operation not legal on
this view
Since you can't delete directly from that view, you'll need to create a trigger that will delete from the base table based on the input given.
Create Or Replace Trigger v_TotSal_Del
Instead Of Delete On v_TotSal
For Each Row
Begin
Delete From Emp
Where DeptNo = :Old.DeptNo;
End;
/


Trigger created.

SQL> Delete From v_TotSal
2 Where DeptNo = 10;

1 row deleted.
This time, it was successful.
SQL> Select Distinct DeptNo
2 From Emp;

DEPTNO
------
30
20

No comments:

Post a Comment