0% found this document useful (0 votes)
63 views

Mysql Advanced FR

MySQL tutorials series containing advanced topics (Functions | Procedures | Transactions ...) the tutorial is in french

Uploaded by

aimranedr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Mysql Advanced FR

MySQL tutorials series containing advanced topics (Functions | Procedures | Transactions ...) the tutorial is in french

Uploaded by

aimranedr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

GÉRER LES DONNÉES

Préparé par : OUATOUCH ABDELJALIL


MySQL Delimiter

DELIMITER $$

CREATE PROCEDURE sp_name(parameter_list)


BEGIN
-- statements
END $$

DELIMITER ;
MySQL CREATE PROCEDURE statement

 The following statement creates a new stored procedure


that wraps the query:
DELIMITER //

CREATE PROCEDURE GetAllProducts()


BEGIN
SELECT * FROM products;
END //

DELIMITER ;
MySQL CREATE PROCEDURE statement
Executing a stored procedure
Drop Procedure
 drop procedure If EXISTS GetAllEmploye
Declaring variables

 To declare a variable inside a stored procedure, you use


the DECLARE statement as follo

DECLARE variable_name datatype(size) [DEFAULT


default_value];
❖ DECLARE totalSale DEC(10,2) DEFAULT 0.0;
❖ DECLARE x, y INT DEFAULT 0;
Assigning variables

 SET variable_name = value;


 DECLARE total INT DEFAULT 0; SET total = 10;
 DECLARE productCount INT DEFAULT 0;

SELECT COUNT(*) INTO productCount FROM products;


Assigning variables (examples)
MySQL Stored Procedure Parameters
 IN parameters
IN is the default mode. When you define an IN
parameter in a stored procedure, the calling
program has to pass an argument to the stored
procedure.
In addition, the value of an IN parameter is
protected. It means that even you change the value
of the IN parameter inside the stored procedure, its
original value is unchanged after the stored
procedure ends. In other words, the stored
procedure only works on the copy of the IN
parameter.
MySQL Stored Procedure Parameters
 OUT parameters
The value of an OUT parameter can be changed
inside the stored procedure and its new value is passed
back to the calling program.

Notice that the stored procedure cannot access the initial


value of the OUT parameter when it starts.
MySQL Stored Procedure Parameters
 INOUT parameters
An INOUT parameter is a combination of IN and
OUT parameters. It means that the calling program may
pass the argument, and the stored procedure can modify
the INOUT parameter, and pass the new value back to the
calling program.
Defining a parameter

 Here is the basic syntax of defining a parameter in


stored procedures:

[IN | OUT | INOUT] parameter_name datatype[(length)]


MySQL stored procedure parameter examples

 Here is the basic syntax of defining a parameter in


stored procedures:

[IN | OUT | INOUT] parameter_name datatype[(length)]


MySQL stored procedure parameter examples

DELIMITER //

CREATE PROCEDURE GetOfficeByCountry(


IN countryName VARCHAR(255)
)
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

DELIMITER ;

CALL GetOfficeByCountry('USA');
MySQL stored procedure parameter example1

DELIMITER $$

CREATE PROCEDURE GetOrderCountByStatus (


IN orderStatus VARCHAR(25),
OUT total INT
)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;
MySQL stored procedure parameter example2
;
MySQL stored procedure parameter example3
MySQL simple IF-THEN statement

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

 The following is the basic syntax of the simple CASE


statement:
CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
END CASE;
MySQL CASE Statement (example)
MySQL CASE Statement (example)
Searched CASE statement

 Here is the basic syntax of the searched CASE


statement:
CASE
WHEN search_condition1 THEN statements
WHEN search_condition1 THEN statements
...
[ELSE else-statements]
END CASE;
Searched CASE statement (example)
Introduction to MySQL LOOP statement

 Here is the basic syntax of the LOOP statement:

[begin_label:] LOOP
statement_list
END LOOP [end_label]
Introduction to MySQL LOOP statement ( example )
Introduction to MySQL LOOP statement ( example )

 The LEAVE statement immediately exits the loop. It works


like the break statement in other programming
languages like PHP, C/C++, and Java.

 you can use the ITERATE statement to skip the current


loop iteration and start a new iteration. The ITERATE is
similar to the continue statement in PHP, C/C++, and
Java.
Introduction to MySQL WHILE loop statement

[begin_label:] WHILE search_condition DO


statement_list
END WHILE [end_label]
Introduction to MySQL WHILE loop statement (
example)
MySQL REPEAT Loop

[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) :

 Atomicité : Toutes les opérations dans une transaction sont traitées


comme une seule unité. Soit toutes les opérations sont effectuées, soit
aucune ne l'est.
 Cohérence : Une transaction amène la base de données d'un état valide
à un autre état valide. Les contraintes d'intégrité sont maintenues avant
et après l'exécution de la transaction.
 Isolation : Les transactions s'exécutent de manière isolée les unes des
autres, ce qui signifie qu'une transaction en cours d'exécution n'est pas
visible par d'autres transactions tant qu'elle n'est pas validée.
 Durabilité : Une fois qu'une transaction est validée, les modifications
effectuées dans la base de données sont permanentes, même en cas de
panne du système.
Début, Validation et Annulation d'une Transaction :

 Début d'une transaction :


Cela peut être fait avec une instruction BEGIN ou une instruction
START TRANSACTION
❑ Validation d'une transaction :
COMMIT;
 Annulation d'une transaction
Exemples Pratiques d'Utilisation :

 Exemple -1 d'une Transaction Simple :


START TRANSACTION;
UPDATE Comptes SET solde = solde - 100 WHERE id = 1;
INSERT INTO Transactions (id_compte, montant) VALUES (1, -100);
COMMIT;
 Exemple -2 d'une Transaction avec Validation Conditionnelle :
START TRANSACTION;
UPDATE Inventaire SET quantite = quantite - 50 WHERE produit_id = 1;
IF (SELECT quantite FROM Inventaire WHERE produit_id = 1) >= 0 THEN
COMMIT;
ELSE
ROLLBACK;
END IF;
Exemples Pratiques d'Utilisation

 Exemple -3 d'une Transaction Simple :


START TRANSACTION;
-- 1. Ajouter un nouveau client
INSERT INTO clients (nom, email) VALUES ('John Doe', '[email protected]');
SET @nouveauClientId = LAST_INSERT_ID(); -- Récupérer l'ID du nouveau client

-- 2. Insérer une commande pour ce client


INSERT INTO commandes (client_id, produit, quantite) VALUES
(@nouveauClientId, 'Produit A', 2);

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

 Gestion de deux exceptions de type (SQLEXCEPTION , NOT FOUND )


MySQL Cursor

 To handle a result set inside a stored procedure, you use a


cursor. A cursor allows you to iterate a set of rows returned
by a query and process each row individually.
 MySQL cursor is read-only, non-scrollable and asensitive.
MySQL Cursor - Working with MySQL cursor

 1. DECLARE cursor_name CURSOR FOR SELECT_statement;


 2. OPEN cursor_name;
 3. FETCH cursor_name INTO variables list;
 4. CLOSE cursor_name;

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 $$

DROP FUNCTION IF EXISTS nom_fonction;


CREATE FUNCTION nom_fonction ([parameter(s)])
RETURNS type_retour
déclaration informative
Instructions

DELIMITER ;

déclaration informative : [NOT DETERMINISTIC; DETERMINISTIC ; READS SQL DATA


MODIFIES SQL DATA ; CONTAINS SQL ; NO SQL ]
MySQL Stored Function

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

1. Ajouter la colonne effectif dans la table service


2. Créer un trigger qui rempli le champs après chaque insertion d’un nouveau employé
Solutions:
 use gestionemploye;
 DELIMITER $$
 drop trigger if exists tr_insert_age_controle $$
 CREATE TRIGGER tr_insert_age_controle
 BEFORE INSERT
 ON employe
 FOR EACH ROW
 BEGIN
 IF ( (datediff(curdate(),new.datenaissance) / 365 ) < 18 ) then
 SIGNAL SQLSTATE '50000’
 SET MESSAGE_TEXT = 'La personne doit etre agee de plus de 18 ans.’;
 END IF;
 END $$DELIMITER ;
Solutions:

 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 ;

You might also like