Dbms Exp9
Dbms Exp9
Dbms Exp9
student
Experiment 09 Date
No
Title of To implement PL/SQL funcAons and triggers
the
Experime
nt
Related Course outcome :
CO4: Formulate SQL queries
Objec&ve:
Example:
create or replace function squareFunc(num
numeric) returns numeric
Language
plpgsql As
$$
BEGIN
return num*num;
End; $$
To access funcAon:
Select squareFunc(6);
If you drop and then recreate a funcAon, the new funcAon is not the same enAty as the old; you
will have to drop exisAng rules, views, triggers, etc. that refer to the old funcAon. Use CREATE OR
REPLACE FUNCTION to change a funcAon definiAon without breaking objects that refer to the
funcAon.
The trigger can be specified to fire before the operaAon is aVempted on a row (before constraints
are checked and the INSERT, UPDATE, or DELETE is aVempted); or aXer the operaAon has
completed (aXer constraints are checked and the INSERT, UPDATE, or DELETE has completed); or
instead of the operaAon (in the case of inserts, updates or deletes on a view). If the trigger fires
before or instead of the event, the trigger can skip the operaAon for the current row, or change the
row being inserted (for INSERT and UPDATE operaAons only). If the trigger fires aXer the event, all
changes, including the effects of other triggers, are "visible" to the trigger.
Syntax of Trigger
[ FROM referenced_table_name ]
where event can be one of: INSERT UPDATE [ OF column_name [, ... ] ] DELETE TRUNCATE To create
a trigger on a table, the user must have the TRIGGER privilege on the table. The user must also have
EXECUTE privilege on the trigger funcAon. Use DROP TRIGGER to remove a trigger.
Implementa&on:
1. Write a function to find factorial of a number
Query :
Query:
Query:
create or replace
function AvgSal()
returns numeric
language plpgsql as $$
declare avg numeric;
begin
select avg(salary) into avg from
emp; return avg; end $$ select
AvgSal();
4. Write a trigger that would fire after delete operation performed on emp table, insert
the deleted tuple in emp1(emp-id,name,salary) table and display the appropriate
message. Query:
5. Write a trigger that would fire after insert/update/delete operations performed on emp
table displaying the date on which data manipulation performed.
Query:
language plpgsql;
3.Update
create trigger updatetriggger1
before update on emp for each
row execute procedure
updaterow(); create or replace
function updaterow() returns
trigger as $$ begin raise
notice 'updation not allowed';
return null; end; $$ language
plpgsql;