fjtello / SQL-C-sharp

Common programming and coding tips and howtos
0 stars 0 forks source link

SQL [#trigger] [single trigger - three after] #45

Open fjtello opened 6 years ago

fjtello commented 6 years ago

SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Creation: 2018.09.11 -- Description: Audit Trigger -- ============================================= CREATE TRIGGER dbo.Trg_Character ON dbo.Character AFTER INSERT, UPDATE, DELETE AS BEGIN

SET NOCOUNT ON;

-- Insert

INSERT INTO HisCharacter SELECT GETDATE() Date_Hour, 0 Action, i.IdCharacter, i.CharName, i.CharFamily, i.User, i.Creation, i.Deletion FROM inserted i LEFT JOIN deleted d ON (i.IdCharacter = d.IdCharacter) WHERE d.IdCharacter IS NULL

-- Update
INSERT INTO HisCharacter
    SELECT  GETDATE() Date_Hour, 1 Action, i.IdCharacter, i.CharName, i.CharFamily, i.User, i.Creation, i.Deletion
    FROM inserted i
    LEFT JOIN deleted d ON (i.IdCharacter = d.IdCharacter)
    WHERE d.IdCharacter IS NOT NULL -- innecesario

-- Delete
INSERT INTO HisCharacter
    SELECT  GETDATE() Date_Hour, 2 Action, d.IdCharacter, d.CharName, d.CharFamily, d.User, d.Creation, d.Deletion
    FROM deleted d 
    LEFT JOIN inserted i ON (i.IdCharacter = d.IdCharacter)
    WHERE i.IdCharacter IS NULL

END GO