An event trigger runs predefined T-SQL code automatically when specific server-level or database-level events occur, such as DDL changes, logons, or error messages.
Event triggers automate auditing, enforce naming conventions, block unwanted schema changes, and log suspicious logons without relying on application code. They centralize control at the database or server scope.
Use CREATE TRIGGER ON DATABASE FOR event_group. Common event groups include DDL_DATABASE_LEVEL_EVENTS and DDL_TABLE_EVENTS.The trigger body contains T-SQL that executes after the event fires.
This trigger writes a row to AuditLog whenever a table is created or altered. It helps track schema drift in production environments.
CREATE TRIGGER trg_AuditTables
ON DATABASE
FOR DDL_TABLE_EVENTS
AS
INSERT INTO AuditLog(event_type, object_name, occured_at)
SELECT EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(256)'),
SYSDATETIME();
GO
Prepend ALL SERVER to scope.Typical use cases: blocking risky logons or capturing CREATE DATABASE events for governance.
CREATE TRIGGER trg_BlockTestLogins
ON ALL SERVER
FOR LOGON
AS
IF ORIGINAL_LOGIN() = 'test'
ROLLBACK;
GO
Event triggers target meta-events, not row-level changes. Pair them with AFTER INSERT/UPDATE/DELETE DML triggers to cover data events on Customers, Orders, Products, and OrderItems.
Keep trigger bodies short; call stored procedures for complex logic. Always include TRY…CATCH to handle errors.Monitor sys.server_triggers and sys.trigger_events regularly.
Disable temporarily with DISABLE TRIGGER, or remove permanently using DROP TRIGGER. Specify ALL SERVER for server-scope triggers or DATABASE for database-scope ones.
.
Yes. Place complex logic in a stored procedure and call it inside the trigger body for cleaner code and easier maintenance.
Server-level triggers fire regardless of the target database, but database-level triggers are scoped to the current database only.
Query sys.server_triggers for server scope or sys.triggers for database scope. Join with sys.trigger_events for detailed event mappings.