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
| CREATE TRIGGER E_I_IU_etudiant_note
ON dbo.V_etudiant_note
INSTEAD OF INSERT, UPDATE
AS
--SET NOCOUNT ON;
-- variable locale du déclencheur
DECLARE @Matricule INT, @Nom VARCHAR(32), @Prenom VARCHAR(25), @date_naiss DATE, @Matiere VARCHAR(16), @Note DECIMAL(4,2);
-- curseur pour lire les INSERT / UPDATE sur la vue
DECLARE C CURSOR
LOCAL
FORWARD_ONLY
STATIC
READ_ONLY
FOR
SELECT Matricule, Nom, Prenom, date_naiss, Matiere, Note
FROM inserted;
-- ouverture du curseur
OPEN C;
-- lecture de la première ligne dans le curceur
FETCH C INTO @Matricule, @Nom, @Prenom, @date_naiss, @Matiere, @Note;
-- gestion d'erreur
BEGIN TRY
-- bouche tant qu'une ligne a été lue avec succès
WHILE @@FETCH_STATUS = 0
BEGIN
-- si matricule NULL alors c'est une insertion
IF @Matricule IS NULL
BEGIN
INSERT INTO dbo.etudiant VALUES (@Nom, @Prenom, @date_naiss);
-- récupération de la clef auto incrémentée
SET @Matricule = SCOPE_IDENTITY();
END;
IF @Matricule IS NOT NULL AND (@Nom IS NOT NULL OR
@Prenom IS NOT NULL OR
@date_naiss IS NOT NULL)
BEGIN
-- sinon c'est une modif
UPDATE dbo.etudiant
SET Nom = @Nom, Prenom = @Prenom, date_naiss = @date_naiss
WHERE Matricule = @Matricule;
END;
-- insertion d'une note, sauf si Note pas spécifiée
IF @Note IS NOT NULL
AND NOT EXISTS(SELECT *
FROM dbo.Note
WHERE Matiere = @Matiere
AND Matricule = @Matricule)
BEGIN
INSERT INTO dbo.Note (Matiere, Matricule, Note)
SELECT @Matiere, @Matricule, @Note;
END;
-- modification d'une note
IF EXISTS(SELECT *
FROM dbo.Note
WHERE Matiere = @Matiere
AND Matricule = @Matricule)
BEGIN
UPDATE dbo.Note
SET Note = @Note
WHERE Matiere = @Matiere
AND Matricule = @Matricule;
END;
-- lecture ligne suivante
FETCH C INTO @Matricule, @Nom, @Prenom, @date_naiss, @Matiere, @Note;
END;
-- fermutre du curseur
CLOSE C;
DEALLOCATE C;
RETURN;
-- fin test erreur
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK;
END CATCH
GO |
Partager