Sunday, August 4, 2024

DML Triggers

 DML (Data Manipulation Language) triggers in SQL Server are special types of stored procedures that automatically execute when a data modification event (INSERT, UPDATE, DELETE) occurs on a specified table or view. DML triggers can be used to enforce business rules, audit changes, and maintain referential integrity.

Types of DML Triggers

  1. AFTER Triggers: Execute after the triggering DML event has completed.
  2. INSTEAD OF Triggers: Execute in place of the triggering DML event.

Creating DML Triggers

AFTER Triggers

AFTER triggers are used to perform actions after the triggering event has been processed. They can be defined for INSERT, UPDATE, and DELETE events.

Example: AFTER INSERT Trigger
-- Create a table to log insert actions
CREATE TABLE InsertLog (
    LogID INT IDENTITY(1,1) PRIMARY KEY,
    InsertedDateTime DATETIME DEFAULT GETDATE(),
    InsertedData NVARCHAR(MAX)
);

-- Create the AFTER INSERT trigger
CREATE TRIGGER trgAfterInsert
ON YourTable
AFTER INSERT
AS
BEGIN
    INSERT INTO InsertLog (InsertedData)
    SELECT * FROM inserted;
END;
Example: AFTER UPDATE Trigger
-- Create a table to log update actions
CREATE TABLE UpdateLog (
    LogID INT IDENTITY(1,1) PRIMARY KEY,
    UpdatedDateTime DATETIME DEFAULT GETDATE(),
    OldData NVARCHAR(MAX),
    NewData NVARCHAR(MAX)
);

-- Create the AFTER UPDATE trigger
CREATE TRIGGER trgAfterUpdate
ON YourTable
AFTER UPDATE
AS
BEGIN
    INSERT INTO UpdateLog (OldData, NewData)
    SELECT deleted.*, inserted.*
    FROM inserted
    JOIN deleted ON inserted.PrimaryKeyColumn = deleted.PrimaryKeyColumn;
END;
Example: AFTER DELETE Trigger
-- Create a table to log delete actions
CREATE TABLE DeleteLog (
    LogID INT IDENTITY(1,1) PRIMARY KEY,
    DeletedDateTime DATETIME DEFAULT GETDATE(),
    DeletedData NVARCHAR(MAX)
);

-- Create the AFTER DELETE trigger
CREATE TRIGGER trgAfterDelete
ON YourTable
AFTER DELETE
AS
BEGIN
    INSERT INTO DeleteLog (DeletedData)
    SELECT * FROM deleted;
END;

INSTEAD OF Triggers

INSTEAD OF triggers override the default action of the triggering event. They can be defined for INSERT, UPDATE, and DELETE events.

Example: INSTEAD OF INSERT Trigger
-- Create the INSTEAD OF INSERT trigger
CREATE TRIGGER trgInsteadOfInsert
ON YourTable
INSTEAD OF INSERT
AS
BEGIN
    -- Custom logic before inserting data
    INSERT INTO AnotherTable (Column1, Column2)
    SELECT Column1, Column2 FROM inserted;

    -- Optionally, you can still insert into the original table
    INSERT INTO YourTable (Column1, Column2)
    SELECT Column1, Column2 FROM inserted;
Example: INSTEAD OF UPDATE Trigger
-- Create the INSTEAD OF UPDATE trigger
CREATE TRIGGER trgInsteadOfUpdate
ON YourTable
INSTEAD OF UPDATE
AS
BEGIN
    -- Custom logic before updating data
    INSERT INTO UpdateLog (OldData, NewData)
    SELECT deleted.*, inserted.*
    FROM inserted
    JOIN deleted ON inserted.PrimaryKeyColumn = deleted.PrimaryKeyColumn;

    -- Optionally, you can still update the original table
    UPDATE YourTable
    SET Column1 = inserted.Column1, Column2 = inserted.Column2
    FROM inserted
    WHERE YourTable.PrimaryKeyColumn = inserted.PrimaryKeyColumn;
END;
Example: INSTEAD OF DELETE Trigger
-- Create the INSTEAD OF DELETE trigger
CREATE TRIGGER trgInsteadOfDelete
ON YourTable
INSTEAD OF DELETE
AS
BEGIN
    -- Custom logic before deleting data
    INSERT INTO DeleteLog (DeletedData)
    SELECT * FROM deleted;

    -- Optionally, you can still delete from the original table
    DELETE FROM YourTable
    WHERE PrimaryKeyColumn IN (SELECT PrimaryKeyColumn FROM deleted);
END;

Using Trigger Context Tables: inserted and deleted

  • inserted table: Contains the new rows for INSERT and UPDATE operations.
  • deleted table: Contains the old rows for DELETE and UPDATE operations.

These context tables are used within the trigger to access the data affected by the DML operation.

Example: Using inserted and deleted Tables

-- Example of using inserted and deleted tables in an AFTER UPDATE trigger
CREATE TRIGGER trgUpdateAudit
ON YourTable
AFTER UPDATE
AS
BEGIN
    -- Audit table to log changes
    CREATE TABLE IF NOT EXISTS AuditLog (
        LogID INT IDENTITY(1,1) PRIMARY KEY,
        ChangeDateTime DATETIME DEFAULT GETDATE(),
        OldData NVARCHAR(MAX),
        NewData NVARCHAR(MAX)
    );

    INSERT INTO AuditLog (OldData, NewData)
    SELECT deleted.*, inserted.*
    FROM inserted
    JOIN deleted ON inserted.PrimaryKeyColumn = deleted.PrimaryKeyColumn;
END;

Best Practices for DML Triggers

  1. Keep It Simple: Avoid complex logic inside triggers. Keep them simple and efficient to avoid performance issues.
  2. Error Handling: Include proper error handling within triggers to manage exceptions gracefully.
  3. Avoid Recursive Triggers: Be cautious of recursive triggers that call themselves or other triggers, which can lead to infinite loops.
  4. Use Context Tables Wisely: Use the inserted and deleted context tables to access the affected data efficiently.
  5. Testing: Thoroughly test triggers in a development environment before deploying them to production.
  6. Documentation: Document the purpose and logic of each trigger to ensure maintainability and clarity.

By leveraging DML triggers effectively, you can automate business rules, enforce data integrity, and maintain a robust and efficient SQL Server database environment.

No comments:

Post a Comment