Create table account
drop table if exists accounts;
create table accounts (
id int generated by default as identity,
name varchar(100) not null,
balance dec(15,2) not null,
primary key(id)
);
insert into accounts(name,balance) values('Bob',10000);
insert into accounts(name,balance) values('Alice',10000);
Create store procedure for update balance :
create or replace procedure sp_transfer (sender int, recever int, amount int)
language plpgsql
as
$$
begin
update accounts set balance = balance - amount where id=sender ;
update accounts set balance = balance + amount where id=recever ;
commit;
end
$$
Create function for update balance :
create or replace function fn_transfer()
returns trigger
language plpgsql
as
$$
begin
if new.balance<>old.balance then
insert into amount_audit(cust_id,c_name,t_amount,balance,datetime,status)
values (old.id,old.name,new.balance - old.balance,new.balance,current_timestamp,
CASE WHEN new.balance - old.balance > 0 then 'Cradit' else 'Debit' end );
end if;
return new;
end
$$
Create trigger
create trigger tg_transfer
before update
on accounts
for each row
execute procedure fn_transfer()
No comments:
Post a Comment