Dbms 9
Dbms 9
thestudent
Experiment No 09 Date
Objec ve:
Example:
create or replace function squareFunc(num
numeric)returns numeric
Language
ti
fi
ti
ti
fi
ti
ti
ti
ti
fi
ti
ti
fi
ti
ti
ti
plpgsqlAs
$$
BEGIN
return
num*num;End;
$$
To access func on:
Select squareFunc(6);
If you drop and then recreate a func on, the new func on is not the same en ty as the old; you
will have to drop exis ng rules, views, triggers, etc. that refer to the old func on. Use CREATE OR
REPLACE FUNCTION to change a func on de ni on without breaking objects that refer to the
func on.
The trigger can be speci ed to re before the opera on is a empted on a row (before constraints
are checked and the INSERT, UPDATE, or DELETE is a empted); or a er the opera on has completed
(a er constraints are checked and the INSERT, UPDATE, or DELETE has completed); or instead of the
opera on (in the case of inserts, updates or deletes on a view). If the trigger res before or instead
of the event, the trigger can skip the opera on for the current row, or change the row being inserted
(for INSERT and UPDATE opera ons only). If the trigger res a er the event, all changes, including
the effects of other triggers, are "visible" to the trigger.
Syntax of Trigger
[ FROM referenced_table_name ]
[ FOR [ EACH ] { ROW | STATEMENT } ] [ WHEN ( condi on ) ] EXECUTE PROCEDURE func on_name
(arguments )
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
haveEXECUTE privilege on the trigger func on. Use DROP TRIGGER to remove a trigger.
Implementa on:
1. Write a function to find factorial of a
numberQuery :
select Factorial(5);
Query:
Query:
Query:
5. Write a trigger that would fire after insert/update/delete operations performed on emp
tabledisplaying the date on which data manipulation performed.
Query:
1. Insert :
create trigger inserttrig
after insert on emp for each row
execute procedure insertrow();
create or replace function
insertrow()returns trigger
as $$
declare a
date;begin
select current_date into
a;raise notice 'Date: %',a;
return new;
end;
$$
language plpgsql;
2. Update :
create or replace function
updaterow()returns trigger
as $$
declare a
date;begin
select current_date into
a;raise notice 'Date: %',a;
return new;
end;
$$
language plpgsql;
3. Delete
create or replace function
deleterow()returns trigger
as $$
declare a date; begin
select current_date into
a;raise notice 'Date: %',a;
return old;
end;
$$
language plpgsql;
language plpgsql;
3. Update