Files
sql/banque.procedures.md
2025-11-16 09:10:10 +01:00

2.5 KiB

Les procédures

Les procédures permettent d'exécuter plusieurs opérations en un seul appel dans un bloc de code

Si une erreur survient rien n'est enregistré

Banque

create or replace procedure add_bank (
  name text
)
language plpgsql
as $$
declare
  v_holder_id bigint;
begin

  insert into holder(type) values ('BANK')
  returning id into v_holder_id;

  insert into bank(id, name)
  values (v_holder_id, name);

  raise notice 'Titulaire créé : % = %',
    v_holder_id, name;
end;
$$;

Individu

create or replace procedure add_person (
  p_firstname text,
  p_lastname text,
  p_birthdate date
)
language plpgsql
as $$
declare
  v_holder_id bigint;
begin

  insert into holder(type) values ('PERSON')
  returning id into v_holder_id;

  insert into person(id, firstname, lastname, birthdate)
  values (v_holder_id, p_firstname, p_lastname, p_birthdate);

  raise notice 'Titulaire créé : % = % %',
    v_holder_id, p_firstname, p_lastname;
end;
$$;
call add_person('Françoise', 'Zanetti', '1995-04-12');
call add_person('Justin', 'Hébrard', '1993-03-11');

Société

create or replace procedure add_company (
 p_name text,
 p_registration_number text,
 p_created_at date
)
language plpgsql
as $$
declare
  v_holder_id bigint;
begin

  insert into holder(type) values ('COMPANY')
  returning id into v_holder_id;

  insert into company(id, name, registration_number, created_at)
  values (v_holder_id, p_name, p_registration_number, p_created_at);

  raise notice 'Titulaire créé : % = % %',
    v_holder_id, p_name, p_registration_number;
end;
$$;
call add_company('Boulangerie de Valorgue', 'FR19803269968', '2014-08-19');

d et r

create or replace procedure add_depot (
  p_account_id bigint,
  p_amount decimal
)
language plpgsql
as $$
declare
  v_id bigint;
begin
  insert into transaction (amount)
  values (p_amount)
  returning id into v_id;

  insert into operation (transaction_id, account_id, amount, direction)
  values (v_id, p_account_id, p_amount, 'CREDIT');

  raise notice 'Dépôt de % sur le compte %', p_amount, p_account_id;
end;
$$;
create or replace procedure add_retrait (
  p_account_id bigint,
  p_amount decimal
)
language plpgsql
as $$
declare
  v_id bigint;
begin
  insert into transaction (amount)
  values (p_amount)
  returning id into v_id;

  insert into operation (transaction_id, account_id, amount, direction)
  values (v_id, p_account_id, p_amount, 'DEBIT');

  raise notice 'Retrait de % sur le compte %', p_amount, p_account_id;
end;
$$;