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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| -- Table journal des erreurs
CREATE TABLE log_erreurs
(
id_erreur int NOT NULL IDENTITY CONSTRAINT PK_log_erreurs PRIMARY KEY
, module sysname
, error_msg nvarchar(2048) NOT NULL
, date_erreur datetime NOT NULL CONSTRAINT DF_log_erreurs__source_date DEFAULT (GETDATE())
)
GO
-- Table dans laquelle vous faites votre INSERT
CREATE TABLE table_source
(
source_id int NOT NULL IDENTITY CONSTRAINT PK_table_source PRIMARY KEY
, source_valeur int NOT NULL
, source_date datetime NOT NULL CONSTRAINT DF_table_source__source_date DEFAULT (GETDATE())
)
GO
-- Table dans laquelle vous historisez l'INSERT dans table_source
CREATE TABLE table_historisation
(
table_historisation_id int NOT NULL CONSTRAINT PK_table_historisation PRIMARY KEY
, table_historisation_valeur int NOT NULL
, table_historisation_date datetime NOT NULL
)
GO
-- Trigger d'historisation de l'INSERT dans table_source
CREATE TRIGGER TR_AI_table_source
ON dbo.table_source
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO table_historisation
(
table_historisation_id
, table_historisation_valeur
, table_historisation_date
)
SELECT source_id
, source_valeur
, source_date
FROM INSERTED
END
GO
-- Procédure d'insertion dans table_source
-- provoque une erreur lorsque @_source_valeur n'est pas valué (la colonne source_valeur est NOT NULL)
ALTER PROCEDURE ps_source_ajoute
@_source_valeur int = NULL
AS
BEGIN
SET NOCOUNT ON
-- Tentative d'insertion
BEGIN TRY
INSERT INTO dbo.table_source
(
source_valeur
)
VALUES
(
@_source_valeur
)
END TRY
-- En cas d'erreur, on la stocke dans log_erreurs
BEGIN CATCH
DECLARE @error_msg nvarchar(2048)
, @error_procedure sysname
, @error_state int
, @error_severity int
SELECT @error_msg = ERROR_MESSAGE()
, @error_procedure = ERROR_PROCEDURE()
, @error_state = ERROR_STATE()
, @error_severity = ERROR_SEVERITY()
INSERT INTO dbo.log_erreurs
(
module
, error_msg
)
VALUES
(
@error_procedure
, @error_msg
)
RAISERROR(@error_msg, @error_severity, @error_state)
END CATCH
END
GO
-- Appel provoquant l'erreur
EXEC ps_source_ajoute
-- Visualisation de l'erreur
SELECT *
FROM dbo.log_erreurs |
Partager