SQL Trigger
The SQL Trigger creates a DML, DDL or logon trigger. A trigger is a special type of stored procedure that automatically runs when an event occurs in a SQL database server.
DML triggers run when a user tries to modify data through a Data Manipulation Language (DML) event. DML events are INSERT, UPDATE or DELETE statements on a table or view. These triggers fire when any valid event fires, whether table rows are affected or not. For more information, see DML triggers.
DDL triggers run in response to a variety of Data Definition Language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations.
Logon triggers fire in response to the LOGON event that's raised when a user's session is being established. You can create triggers directly from SQL statements or from methods of assemblies that are created in the Microsoft .NET Framework Common Language Runtime (CLR) and uploaded to an instance of SQL Server. SQL Server lets you create multiple triggers for any specific statement
Similarly, if you write a Trigger for a delete operation on a table, it creates a table in memory named DELETED and then deletes the row.
Syntax
- CREATE trigger employeeDetail1
- ON EmpoyeeDetail
- AFTER INSERT, UPDATE
- AS print ('you can not insert, update and delete this table EmployeeDetails');
- rollback;
The DML Trigger with a reminder message
The following DML trigger prints a message to the client when anyone tries to add or change data in the EmployeeDetail table in the Sample database.
Syntax
- CREATE trigger reminder1
- ON EmpoyeeDetail
- AFTER INSERT, UPDATE
- AS print ('you can not insert, update and delete this table EmployeeDetails');
- rollback;
The DML Trigger with a reminder e-mail message
The following example sends an e-mail message to a specified person (Rahul) when the EmployeeDetail table changes.
Syntax
- CREATE TRIGGER reminder2
- ON EmployeeDetails
- AFTER INSERT, UPDATE, DELETE
- AS
- EXEC msdb.dbo.sp_send_dbmail
- @profile_name = 'Sample Administrator',
- @recipients = '[email protected]',
- @body = 'Don''t forget to print a report for the Details.',
- @subject = 'Reminder';
- GO
Example
Why and When to use a Trigger?
We use a trigger when we want some event to happen automatically on certain desirable scenarios.
Let's see an example
You have a table that changes frequently, now you want to know how many times and when these changes take place. In that case you can create a trigger that will insert the desired data into another table whenever any change in the main table occurs.
The DML AFTER Trigger to enforce a business rule between the purchase order header and vendor tables
The DML AFTER trigger can enforce a business rule. Because CHECK constraints reference to only the columns on which the column-level or table-level constraint is defined, you must define any cross-table constraints (in this case, business rules) as triggers. The following example creates a DML trigger in the Sample database. This trigger checks to make sure the credit rating for the vendor is good (not 5) when there's an attempt to insert a EmpName into the EmployeeDetail table. To get the credit rating of the vendor, the Vendor table must be referenced. If the credit rating is too low a message appears and the insertion doesn't happen.
Syntax
- CREATE TRIGGER Purchasing.LowCredit ON Purchasing.PurchaseOrderHeader
- AFTER INSERT
- AS
- IF (ROWCOUNT_BIG() = 0)
- RETURN;
- IF EXISTS (SELECT *
- FROM Purchasing.PurchaseOrderHeader AS p
- JOIN inserted AS i
- ON p.PurchaseOrderID = i.PurchaseOrderID
- JOIN Purchasing.Vendor AS v
- ON v.BusinessEntityID = p.VendorID
- WHERE v.CreditRating = 5
- )
- BEGIN
- RAISERROR ('A vendor''s credit rating is too low to accept new
- purchase orders.', 16, 1);
- ROLLBACK TRANSACTION;
- RETURN
- END;
- GO
- INSERT INTO Purchasing.PurchaseOrderHeader (RevisionNumber, Status, EmployeeID,
- VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt, Freight)
- VALUES (
- 2
- ,3
- ,261
- ,1652
- ,4
- ,GETDATE()
- ,GETDATE()
- ,44594.55
- ,3567.564
- ,1114.8638 );
- GO
Using a database-scoped DDL Trigger
The following example uses a DDL Trigger to prevent any synonym in a database from being dropped.
Syntax
- CREATE TRIGGER safety
- ON DATABASE
- FOR DROP_SYNONYM
- AS
- IF (@@ROWCOUNT = 0)
- RETURN;
- RAISERROR ('You must disable Trigger "safety" to remove synonyms!', 10, 1)
- ROLLBACK
- GO
- DROP TRIGGER safety
- ON DATABASE;
- GO
Using a server-scoped DDL trigger
This example uses a DDL trigger to print a message if any CREATE DATABASE event occurs on the current server instance, and uses the EVENTDATA function to retrieve the text of the corresponding Transact-SQL statement. For more examples that use EVENTDATA in DDL triggers.
Syntax
- CREATE TRIGGER ddl_trig_database
- ON ALL SERVER
- FOR CREATE_DATABASE
- AS
- PRINT 'Database Created.'
- SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
- GO
- DROP TRIGGER ddl_trig_database
- ON ALL SERVER;
- GO
Using a logon trigger
The following logon trigger example denies an attempt to log in to SQL server as a member of the login_test login if there are already three user sessions running under that login.
Syntax
- USE SAMPLE ;
- GO
- CREATE LOGIN login_test WITH PASSWORD = '3KHJ6dhx(0xVYsdf' MUST_CHANGE,
- CHECK_EXPIRATION = ON;
- GO
- GRANT VIEW SERVER STATE TO login_test;
- GO
- CREATE TRIGGER connection_limit_trigger
- ON ALL SERVER WITH EXECUTE AS 'login_test'
- FOR LOGON
- AS
- BEGIN
- IF ORIGINAL_LOGIN()= 'login_test' AND
- (SELECT COUNT(*) FROM sys.dm_exec_sessions
- WHERE is_user_process = 1 AND
- original_login_name = 'login_test') > 3
- ROLLBACK;
- END;
-
Viewing the events that cause a trigger to fire
The following example queries the sys.EmployeeDetails and sys.EmployeeDetail catalog views to determine which Transact-SQL language events cause trigger safety to fire. The trigger safety is created in example D found above.3
Syntax
- SELECT TE.*
- FROM sys.EmployeeDetails AS TE
- JOIN sys. EmployeeDetail AS T ON T.object_id = TE.object_id
- WHERE T.parent_class = 0 AND T.name = 'safety';
- GO
In this article, you learned how to use a SQL Create Trigger statement with various options.