Published on

January 8, 2013

Understanding SQL Server Triggers

A trigger is a special type of stored procedure that is executed automatically when certain data manipulation operations, such as inserting, deleting, or updating data, are performed on a table. Triggers are database objects that are bound to a specific table and can be used to enforce business rules, maintain data integrity, or perform additional actions based on the changes made to the table.

In SQL Server, triggers are classified into two main types: Instead of Triggers and After Triggers. Instead of Triggers are often used to handle complex views and can be used as interceptors for actions performed on a table. They allow us to insert data into virtual tables before checking constraints. On the other hand, After Triggers check constraints first and then insert data into virtual tables.

Let’s consider a scenario where we want to create a table column that can automatically generate a customized sequence. We can achieve this by using an Instead of Trigger. Here’s an example:

CREATE TABLE [dbo].[Employee1](
[id] CHAR(10) PRIMARY KEY,
[name] VARCHAR(50)
)
GO

-- Instead of Trigger
CREATE TRIGGER AutoIncrement_Trigger ON [dbo].[Employee1]
instead OF INSERT AS
BEGIN
DECLARE @ch CHAR
DECLARE @num INT
SELECT  @num=SUBSTRING(MAX(id),2,1) FROM [dbo].[Employee1]
SELECT  @ch=SUBSTRING(MAX(id),1,1) FROM [dbo].[Employee1]
IF @num=9
BEGIN
SET @num=0
SET @ch= CHAR( ( 1 + ASCII(@ch) ))
END
INSERT INTO [dbo].[Employee1] (id,name) SELECT (@ch+CONVERT(VARCHAR(9),(@num+1))),inserted.name FROM inserted
END

In the above code, the Instead of Trigger is used to automatically generate the next value for the “id” column. The trigger code retrieves the maximum value from the “id” column, parses the integer and character data, and stores them in variables. When the integer value reaches 9, it is reset to 0 and the character value is incremented to the next character. The new value is then inserted into the “Employee1” table.

By using this trigger, we can insert data into the “Employee1” table without specifying a value for the “id” column. The trigger will automatically generate the next value in the sequence.

It’s important to note that triggers should be used sparingly and only in special cases. It is always recommended to design your system in such a way that triggers are not necessary. The logic of a trigger can often be included in your code or procedures, which can help avoid the overhead and performance problems associated with triggers.

In conclusion, triggers are a powerful feature in SQL Server that can be used to automate actions and enforce business rules. However, they should be used judiciously and with caution to avoid unnecessary complexity and performance issues.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.