Mysql Advanced FR
Mysql Advanced FR
DELIMITER $$
DELIMITER ;
MySQL CREATE PROCEDURE statement
DELIMITER ;
MySQL CREATE PROCEDURE statement
Executing a stored procedure
Drop Procedure
drop procedure If EXISTS GetAllEmploye
Declaring variables
DELIMITER //
DELIMITER ;
CALL GetOfficeByCountry('USA');
MySQL stored procedure parameter example1
DELIMITER $$
IF condition THEN
statements;
END IF;
IF condition THEN
statements;
ELSE
else-statements;
END IF;
MySQL simple IF-THEN statement
MySQL simple IF-THEN statement ( example)
MySQL simple IF-THEN statement ( example)
MySQL simple IF-THEN statement
IF condition THEN
statements;
ELSEIF elseif-condition THEN
elseif-statements;
...
ELSE
else-statements;
END IF;
MySQL simple IF-THEN statement ( example )
MySQL CASE Statement
[begin_label:] LOOP
statement_list
END LOOP [end_label]
Introduction to MySQL LOOP statement ( example )
Introduction to MySQL LOOP statement ( example )
[begin_label:] REPEAT
statement
UNTIL search_condition
END REPEAT [end_label]
MySQL REPEAT Loop ( example )
Gestion des transactions
Par défaut, le client MySQL est configuré pour utiliser la
validation automatique.
On n'a donc pas à le faire. Si on souhaite avoir la possibilité
d'annuler l'instruction INSERT, on doit utiliser une transaction
Cela peut être fait avec une instruction BEGIN ou une
instruction START TRANSACTION.
Exemple Pratique :
Atomicité, Cohérence, Isolation et Durabilité
(ACID) :
COMMIT;
Gestion des exceptions
Afin d’éviter qu’un programme ne s’arrête dès la première erreur suite à une
instruction SQL, il est indispensable de prévoir les cas potentiels d’erreurs et
d’associer à chacun de ces cas la programmation d’une exception (handler dans le
vocabulaire de MySQL).
Les exceptions peuvent être gérées dans un sous-programme (fonction ou
procédure cataloguée) ou un déclencheur
Une exception MySQL correspond à une condition d’erreur et peut être associée à
un identificateur (exception nommée).
Une exception est détectée (aussi dite « levée ») si elle est prévue dans un handler
au cours de l’exécution d’un bloc (entre BEGIN et END ).
Une fois levée, elle fait continuer (ou sortir du bloc) le programme après avoir
réalisé une ou plusieurs instructions que le programmeur aura explicitement
spécifiées.
Deux mécanismes qui peuvent être mis en œuvre pour gérer une exception en
Mysql : CONTINUE et EXIT.
Déclaration et gestion d’une exception mysql
Lever une exception explicitement
Utilisation de SIGNAL pour Générer des Erreurs Personnalisées :
La déclaration SIGNAL est utilisée pour générer des erreurs personnalisées avec un code d'état spécifique et un message
d'erreur personnalisé
DELIMITER //
CREATE PROCEDURE exemple_procedure()
BEGIN
-- Vérifier une condition
IF condition_non_satisfaite THEN
-- Générer une exception avec SIGNAL
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Condition non satisfaite : Une exception a été générée.';
ELSE
-- Effectuer l'opération si la condition est satisfaite
-- ...
-- Afficher un message de réussite (pour cet exemple)
SIGNAL SQLSTATE '00000' SET MESSAGE_TEXT = 'Opération réussie.';
END IF;
END //
DELIMITER ;
Gestion des exceptions
Utilisation de SIGNAL pour Générer des Erreurs Personnalisées :
Gestion des exceptions
When working with MySQL cursor, you must also declare a NOT FOUND
handler to handle the situation when the cursor could not find any row.
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
MySQL Cursor - Working with MySQL cursor (
example )
MySQL Cursor - Working with MySQL cursor for
update ( example )
CREATE PROCEDURE getUpdateSalaireService (pidService int)
BEGIN
declare c_matricule int; declare finished integer default 0;
declare cursorUpdate cursor for select matricule from employe where idService = pidService for
update;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1; open cursorUpdate;
boucle : loop
fetch cursorUpdate into c_matricule;
IF finished = 1 THEN
LEAVE boucle;
END IF;
update employe set salaire = salaire + 0.05 * salaire where matricule = c_matricule;
end loop boucle;
CLOSE cursorUpdate;
end$
MySQL Stored Function
USE nom_bd;
DELIMITER $$
DELIMITER ;
DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for
the same input parameters and NOT DETERMINISTIC otherwise. This is mostly used with string or
math processing, but not limited to that.
READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from
databases, thus, it does not contain instructions that modify data, but it contains SQL instructions
that read data (e.q. SELECT).
MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for
example, it contain UPDATE, INSERT, DELETE or ALTER instructions).
MySQL Stored Function ( example)
MySQL Stored Function (call function)
LES TRIGGERS BEFORE INSERT
use gestionemploye;
delimiter $$
drop trigger if exists `trigger_insert_before`$$
CREATE TRIGGER `trigger_insert_before`
BEFORE INSERT
ON employe
FOR EACH ROW
BEGIN
set NEW.NOM = UPPER(NEW.NOM);
set NEW.PRENOM=UPPER(NEW.PRENOM);
END $$
LES TRIGGERS ( BEFORE INSERT )
use gestionemploye;delimiter $$
drop trigger if exists `emp_details_BINS`$$
CREATE TRIGGER `emp_details_BINS`
BEFORE INSERT
ON service
FOR EACH
BEGIN
SET NEW.nomService = UPPER(TRIM(NEW.nomService));
END;
$$
insert into service values(600,"service600");
select * from service;
LES TRIGGERS AFTER INSERT
drop trigger if exists `trigger_insert`$$
CREATE TRIGGER `trigger_insert`
AFTER INSERT ON employe
FOR EACH ROW
BEGIN
INSERT INTO employe_audit VALUES(NEW.matricule,
NEW.NOM,NEW.PRENOM,'INSERT’,curdate(),curtime());
END $$
show triggers;
insert into employe(nom,prenom) values('nn','pp’)
select * from employe_audit;
LES TRIGGERS BEFORE DELETE
use gestionemploye ;
delimiter $$
CREATE TRIGGER before_delete_employes
BEFORE DELETE
ON employe
FOR EACH ROW
BEGIN
insert into employe_audit values( old.matricule,old.nom,,old.prenom,
,'delete’,curdate(),curtime(),'abondonne de poste’);
END$$
delete from employe where matricule = 124;
select * from employe_audit;
LES TRIGGERS AFTER DELETE
use gestionemploye ;
delimiter $$
CREATE TRIGGER after_delete_employes
AFTER DELETE
ON employe
FOR EACH ROW
BEGIN
UPDATE BudgetService
SET TotalBudget = TotalBudget - old.salaire where idService = old.IdService;
END$$
LES TRIGGERS BEFORE UPDATE
DELIMITER $$
CREATE TRIGGER before_Bloc_update_salaire
BEFORE UPDATE
ON employe FOR EACH ROW
BEGIN
IF new.salaire != old.salaire THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = ’vous ne devez pas modifier de salaire’;
END IF;
END $$
DELIMITER ;
LES TRIGGERS AFTER UPDATE
DELIMITER $$
CREATE TRIGGER after_update_studentsInfo
AFTER UPDATE
ON students FOR EACH ROW
BEGIN
INSERT into students_log VALUES (user(),
CONCAT('Update Student Record ', OLD.name, ' Previous Class :',
OLD.class, ' Present Class ', NEW.class));
END $$
DELIMITER ;
LES TRIGGERS AFTER UPDATE
use gestionemploye;
delimiter $$
drop trigger if exists `trigger_update_salaire`$$
CREATE TRIGGER `trigger_update_salaire`
AFTER update
ON employe
FOR EACH ROW
BEGIN if( New.salaire !=old.salaire) then
INSERT INTO employe_audit VALUES(NEW.matricule,
NEW.NOM,NEW.PRENOM,'UpdateSalaire’,Curdate(),Curtime(),’Concours promotion
ou echlons ’,old.salaire,new.salaire,new.salaire-oldsalaire);
end if;
END $$
Exercices
1. Ajouter la colonne datenaissance
2. Créer un trigger qui vérie que l’age des employés est supérieure de 18 ans après
chaque insertion
use gestionemploye;
DELIMITER $$
drop trigger if exists tr_effectif $$
CREATE TRIGGER tr_effectif
AFTER INSERT
ON employe
FOR EACH ROW
BEGIN
declare nb int;
set nb = (select count(*) from employe where idService = New.idService);
update service set effectif = nb where idService = New.idService;
END
$$DELIMITER ;