Showing posts with label Trigger. Show all posts
Showing posts with label Trigger. Show all posts

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

Trigger: Check Values Before Data Entry

This trigger is fired whenever the JOB column is inserted or updated on the EMP table.
Create or Replace Trigger t_Top_Dog
Before Insert or Update
Of Job
On Emp
For Each Row
Begin
If :New.Job = 'PRESIDENT'
Then Raise_Application_Error
(-20111,'Only one top dog allowed.');
End If;
End;
/

Trigger created.

SQL> Insert Into Emp Values
2 (7998,'TOBIAS','DEVELOPER',NULL,SYSDATE,3500,NULL,10);

1 row created.

SQL> Insert Into Emp Values
2 (7999,'ELMO','PRESIDENT',NULL,SYSDATE,6000,NULL,20);
Insert Into Emp Values
*
ERROR at line 1:
ORA-20111: Only one top dog allowed.
ORA-06512: at "SCOTT.T_TOP_DOG", line 3
ORA-04088: error during execution of trigger 'SCOTT.T_TOP_DOG'