DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
 
 
SITE SEARCH SQLUSA.com VIDEOS
 
 
SQL E/BOOKS   WORLD, USA & SQL NEWS   FORMAT
SCRIPTS SQL 2005 SQL 2008 ARTICLES
How to architect a trigger on column update?

Execute the following Microsoft SQL Server T-SQL scripts in SSMS Query Editor to create triggers.

-- Create trigger to prevent DELETE from the Inventory table

CREATE TRIGGER InventoryTrigger

  ON Inventory AFTER DELETE

AS

BEGIN

 IF (SELECT COUNT(*) FROM deleted) > 0 AND @@TRANCOUNT > 0

 BEGIN

   ROLLBACK TRAN;

   RAISERROR('No deletion allowed from Inventory table',16,1);

 END

END;

GO

------------

The following trigger creates two (2) audit trail entries: previous data and new data(replacing data). The OUTPUT clause can also be used in similar application.

-- SQL insert audit trail table when sensitive data changes

-- SQL after trigger - SQL trigger - SQL column update trigger
-- Fires when Salary or SSN column is updated - single row or multiple rows

USE Payroll

GO

 

CREATE TRIGGER trgEmployeeUpdate

ON Employee

AFTER UPDATE

AS

  IF (Update(Salary)

       OR Update(SSN))

    BEGIN

      INSERT INTO CorpSecurityEmployeeHistory

                 (auditlogtype,

                  auditEmployeeDeptID,

                  auditEmployeeID,

                  auditEmployeeSalary,

                  auditEmployeeSSN,

                  auditUpdatedBy)

      SELECT 'PREVIOUSDATA',

             DeptID,

             EmployeeID,

             Salary,

             SSN,

             User_name()

      FROM   DELETED

      

      INSERT INTO CorpSecurityEmployeeHistory

                 (auditlogtype,

                  auditEmployeeDeptID,

                  auditEmployeeID,

                  auditEmployeeSalary,

                  auditEmployeeSSN,

                  auditUpdatedBy)

      SELECT 'NEWDATA',

             DeptID,

             EmployeeID,

             Salary,

             SSN,

             User_name()

      FROM   INSERTED

    END;

 

GO

Related articles:

CREATE TRIGGER (Transact-SQL)

Triggers in SQL SERVER

 

Exam Prep 70-461
SQL 2016 DESIGN & PROGRAMMING
 
 
 
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE