Inf 12
Inf 12
TRIGGERS
What is a Trigger :
A trigger is a stored procedure that defines an action the database automatically initiates when some
database related events such as INSERT, UPDATE OR DELETE occurs.
Why Triggers:
A trigger is a fragment of code that you tell Oracle to run before or after a table is modified. A
trigger has the power to :-
make sure that a column is filled in with default information
make sure that an audit row is inserted into another table
after finding that the new information is inconsistent with other stuff in the database, raise an error that
will cause the entire transaction to be rolled back
The different types of integrity constraints provide a declarative mechanism to associate “simple”
conditions with a table such as a primary key, foreign keys or domain constraints.
Complex integrity constraints that refer to several tables and attributes cannot be specified within table
definitions. Triggers,in contrast, provide a procedural technique to specify and maintain integrity
constraints.
Triggers Vs Procedures:
Triggers Execute Implicitly while Procedure execute explicitly.
It do not accept arguments while Procedures may or may not have arguments.
Triggers are fired for DML(Insert, Update or Delete) statements while procedures execute all DML
statements including SELECT.
Trigger Vs constraints:
Triggers affect only the row added after the trigger is enabled.
Executing Triggers
When using SQL*Plus, you have to provide a / character to get the program to evaluate a trigger or
PL/SQL function definition. You then have to say "show errors" if you want SQL*Plus to print out what
went wrong. Unless you expect to write perfect code all the time, it can be convenient to leave these
SQL*Plus incantations in your .sql files.
Types of Triggers
Row level triggers
Statement Level Trigger
Before and after Trigger
Instead of Trigger
Trigger on system events and user events
Example: 1
SQL> Create or replace trigger empcount
After insert on emp
For each row
Declare
n integer;
Begin
Select count(*) into n from emp;
dbms_output.put_line(‘total no. of records in a table is : ‘||n);
End;
In a row trigger thus it is possible to specify comparisons between old and new attribute values in the
PL/SQL block,
e.g., “if :old.SAL < :new.SAL then . . . ”.
If for a row trigger the trigger time point before is specified, it is even possible to modify the new values of
the row, e.g., :new.SAL := :new.SAL * 1.05 or :new.SAL := :old.SAL.
Example : 1
Example : 2
Example 4:
For example:
If you had a trigger called orders_before_insert,
you could enable it with the following command:
ALTER TRIGGER orders_before_insert ENABLE;
Disable a Trigger
syntax :
Drop a Trigger
syntax :
DROP TRIGGER trigger_name;
For example:
DROP TRIGGER orders_before_insert;
Example:
create or replace trigger check_budget_EMP
after insert or update of SAL, DEPTNO on EMP
declare
cursor DEPT_CUR is select DEPTNO, BUDGET from DEPT;
DNO DEPT.DEPTNO%TYPE;
ALLSAL DEPT.BUDGET%TYPE;
DEPT_SAL number;
begin
open DEPT_CUR; Material Downloaded From SUPERCOP 4/7
loop
fetch DEPT_CUR into DNO, ALLSAL;
exit when DEPT_CUR%NOTFOUND;
select sum(SAL) into DEPT_SAL from EMP where DEPTNO = DNO;
if DEPT_SAL > ALLSAL then
raise_application_error(-20325, 'Total of salaries in the department '|| to_char(DNO) || ' exceeds
budget');
end if;
end loop;
close DEPT_CUR;
end; /
More about triggers :
Triggers are not exclusively used for integrity maintenance. They can also be used for
• Monitoring purposes, such as the monitoring of user accesses and modifications on certain sensitive
tables.
• Logging actions, e.g., on tables:
Contd..
create trigger LOG EMP
after insert or update or delete on EMP
begin
if inserting then
insert into EMP LOG values(user, ’INSERT’, sysdate);
end if ;
if updating then
insert into EMP LOG values(user, ’UPDATE’, sysdate);
end if ;
if deleting then
insert into EMP LOG values(user, ’DELETE’, sysdate);
end if ;
end;
By using a row trigger, even the attribute values of the modified tuples can be stored in the table EMP LOG.
• automatic propagation of modifications. For example, if a manager is transferred to another
department, a trigger can be defined that automatically transfers the manager’s employees to the new
department.
If a trigger is specified within the SQL*Plus shell, the definition must end with a point “.” in the last
line. Issuing the command run causes SQL*Plus to compile this trigger definition.
A trigger definition can be loaded from a file using the command @. Note that the last line in the file
must consist of a slash “/”.
A trigger definition cannot be changed, it can only be re-created using the or replace clause.
The command drop <trigger name> deletes a trigger.
After a trigger definition has been successfully compiled, the trigger automatically is enabled.
The command alter trigger <trigger name> disable is used to deactivate a trigger. All
triggers defined on a table can be (de)activated using the command
alter table <Tablename> enable | disable all trigger;
The data dictionary stores information about triggers in the table USER TRIGGERS. The information
includes the trigger name, type, table, and the code for the PL/SQL block.
Difference b/w For and Do Loops: When No. of repetitions are known then For loop is used, and if the
No. of iterations are unknown then do loops are used.
Material Downloaded From SUPERCOP 5/7
Difference b/w While and Until: While means as long as the condition is true, the loop execute the body
Whereas Until means as long as the condition is not true, the loop repeats
Exiting from Loop: Exit statement helps to terminate any of the loops directly.
EXIT DO : To terminate any Do loop
EXIT FOR : To terminate for loop
Use of For Each … Next Loop: It is used to repeat a group of statements for each element in a dynamic
array as we are not sure about the size of the array.
Two Basic Operations on Arrays: Traversing means processing each element of the array
Searching means to find a given element in array.
With a call statement - Call procedure-name ( actual arguments list) Eg: Call abc (x , y)
Without call statement- procedure – name actual arguments Eg: abc x, y
If Private/Public keyword is not specified with a procedure then the procedure becomes Public.
The value being returned by the function is assigned to the function name, which automatically returns it to
the calling procedure or function. A function may return only one value.
*Sub procedure does not return a value, so a call to a sub procedure is a complete statement.
* Function procedure returns a value, so a call to a function procedure is part of an expression.
In a procedure, optional parameters are declared in argument list from right hand side.
Exit sub and Exit Function statements can be used to Exit from a sub procedure or a function procedure.
If a variable is declared as PUBLIC A as Integer in form1 and it’s value is 20, then it can be used in
form2 as form1.A.
Try this:
Sub MyProc1 ( )
Dim A as Integer
A = 12
Print A
Call MyProc2 ( A )
A=A+2
Print A
End Sub
Sub MyProc2 ( B as Integer)
Print B
B = B + 10
Print B
End Sub
O/P is:
12
12
22
24
When a number is converted to a string, a leading space is always reserved for its sign.
Cint ( ) function returns truly rounded number. Eg. : Print CInt (-14.8) will print -15.
***