Introduction to Triggers in SQL Server

Tiggers are commonly used to automate data updates in SQL Server. This article describes the fundamentals of triggers in SQL, the different categories of triggers, and how to implement triggers in SQL Server.

What is the SQL Server Trigger?

A SQL trigger is a database object that executes when a database event occurs. When a record is inserted, updated, or deleted, for example, we can execute a SQL query that will “do something” in the database. A trigger can be set on a record insert in a database table, for instance. For instance, to increase the blog count in the Reports table when a new record is inserted into the Blogs table, we can construct a trigger on the Blogs table on INSERT and update the Reports table by increasing the blog count by 1.

Types of SQL Server Triggers

Two categories of triggers exist:

  • DDL Trigger
  • DML Trigger
  • DDL Triggers in SQL Server

The DDL triggers are activated in response to DDL (Data Definition Language) command events that begin with Create, Alter, and Drop, such as Create_table, Create_view, drop_table, Drop_view, Alter_table, and Alter_view.

The DDL Trigger Code

create trigger saftey
on database
for
create_table,alter_table,drop_table
as
print'you can not create ,drop and alter table in this database'
rollback;

When we create, alter, or drop any table in a database, then the following message appears,

DML Triggers in SQL Server

The DML triggers are fired in response to DML (Data Manipulation Language) command events that start with Insert, Update, and Delete. Like insert_table, Update_view and Delete_table.

create trigger deep
on emp
for
insert,update,delete
as
print'you can not insert,update and delete this table i'
rollback;

When we insert, update, or delete a table in a database, then the following message appears,

Logon Triggers in SQL Server

In SQL Server, logon triggers are special types of triggers that are designed to execute automatically in response to a user’s logon event. When a user connects to a SQL Server instance, the logon trigger fires before the user’s session is established, allowing you to perform certain actions or enforce specific rules based on the user’s login.

CREATE TABLE dbo.LogonAudit (
    LogonAuditID INT IDENTITY(1,1) PRIMARY KEY,
    LoginName NVARCHAR(50),
    LoginTime DATETIME,
    ClientHost NVARCHAR(50)
);
GO

CREATE TRIGGER LogonAuditTrigger
ON ALL SERVER WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN
    -- Insert logon event details into an audit table
    INSERT INTO dbo.LogonAudit (LoginName, LoginTime, ClientHost)
    VALUES (ORIGINAL_LOGIN(), GETDATE(), HOST_NAME())
END;
GO

In this example, we create a logon trigger called LogonAuditTrigger that fires for all logon events on the server. The trigger is configured to execute under the context of the sa account, which requires appropriate permissions.

Within the trigger’s body, we perform an action of inserting logon event details into an audit table called LogonAudit. The ORIGINAL_LOGIN() function retrieves the login name of the user who is attempting to log in. GETDATE() returns the current date and time when the logon occurs. HOST_NAME() retrieves the client host name or IP address from which the logon originates.

By using this logon trigger, each time a user logs in to the SQL Server instance, the trigger will capture and store the login name, login time, and client host information in the LogonAudit table, providing an audit trail of logon events.

Types of DML triggers

There are two types of DML Triggers in SQL Server.

AFTER Triggers

AFTER triggers are executed after the action of an INSERT, UPDATE, or DELETE statement.

create trigger insertt
on emp
after insert
as
begin
insert into empstatus values('active')
end

INSTEAD Of Triggers
It will tell the database engine to execute the trigger instead of the statement. For example, an insert trigger executes when an event occurs instead of the statement that would insert the values in the table.

CREATE TRIGGER instoftr
ON v11
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO emp
SELECT I.id, I.names
FROM INSERTED I

INSERT INTO emp1values
SELECT I.id1, I.name1
FROM INSERTED I
END

When we insert data into a view by the following query, it inserts values in both tables.

insert into v11 values(1,'d','dd')

You can see both tables by the following query.
select * from emp

select * from emp1values