Exercice Langage SQL : Procédure Stockée et Cursor
Rédigé par , Publié le 13 Décembre 2011, Mise à jour le Mardi, 30 Novembre 1999 00:00Participez au vote ☆☆☆☆☆★★★★★
Utilisation de Procédure Stockée & Cursor
Travail à Faire:
Créer une procédure Stockée qui a pour rôle de mettre à jour la table USER a partir d'un autre table ou vue.
NB:
- si l'utilisateur existe déja, on va rafraichir les Informations
- si l'utilisateur n'existe pas, on va donc le créer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
CREATE PROCEDURE dbo.AddOrUpdateUser AS DECLARE @MatriculeSalarie AS nvarchar(50), @NumSalarie AS nvarchar(50), @Nom AS nvarchar(50), @Prenom AS nvarchar(50), @Num_adherent AS int, @Situation_Familiale AS nvarchar(50), @Nb_Enfant AS int, @Categorie AS nvarchar(50), @Service AS nvarchar(50), @Famille_Categorie AS nvarchar(50) -- Utilisation d'un curseur pour parcourir tout les données DECLARE Curseur1 CURSOR FOR SELECT DISTINCT MatriculeSalarie, SA_CompteurNumero, Nom, Prenom, Num_Adhesion, SituationFamille, NB_Enfant, Catégorie, Service FROM VIEW_SAl_Information WHERE (DateHist IS NULL) AND (hstDate_Famil IS NULL) ORDER BY SA_CompteurNumero OPEN Curseur1 FETCH NEXT FROM Curseur1 INTO @MatriculeSalarie , @NumSalarie , @Nom , @Prenom ,@Num_adherent , @Situation_Familiale ,@Nb_Enfant ,@Categorie , @Service WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS(SELECT Matricule FROM dbo.Dossier_Personnel WHERE (dbo.Dossier_Personnel.Matricule = @MatriculeSalarie)) -- Dans cette partie, le Compte existe déja, on a donc juste besoin de rafraichir les Informations BEGIN UPDATE dbo.Dossier_Personnel SET dbo.Dossier_Personnel.Nom = @Nom, dbo.Dossier_Personnel.Prenom = @Prenom, dbo.Dossier_Personnel.Num_adherent = @Num_adherent, dbo.Dossier_Personnel.Situation_Familiale = @Situation_Familiale, dbo.Dossier_Personnel.Nb_Enfant = @Nb_Enfant, dbo.Dossier_Personnel.Categorie = @Categorie, dbo.Dossier_Personnel.Service = @Service WHERE dbo.Dossier_Personnel.Matricule = @MatriculeSalarie END ELSE -- Dans cette partie, le compte n'existe pas, on va donc le créer BEGIN INSERT INTO dbo.Dossier_Personnel (Matricule, NumSalarie, Nom, Prenom, Num_adherent, Situation_Familiale, Nb_Enfant, Categorie, Service) VALUES (@MatriculeSalarie, @NumSalarie, @Nom, @Prenom, @Num_adherent, @Situation_Familiale, @Nb_Enfant, @Categorie, @Service) END FETCH NEXT FROM Curseur1 INTO @MatriculeSalarie , @NumSalarie , @Nom , @Prenom ,@Num_adherent , @Situation_Familiale ,@Nb_Enfant ,@Categorie , @Service END CLOSE Curseur1 DEALLOCATE Curseur1 |