SQL Server Database Triggers

  • A trigger is an object contained within an SQL Server database that is used to execute a batch of SQL code whenever a specific event occurs.
  • A trigger is “fired” whenever an INSERT, UPDATE, or DELETE SQL command is executed against a specific table.
  • A Trigger is associated with Database Table

There are three types of Database Triggers –

  1. INSERT TRIGGER
  2. UPDATE TRIGGER
  3. DELETE TRIGGER

INSERT TRIGGER

  • Body of trigger can have any block which a Stored Procedure can have
  • Body can call SP using Exec
  • When SQL server processes this “INSERT” command, it creates a new virtual table, which contains all nine of the fields in the “INSERT” command. This table is named “Inserted”, and is passed to the trig_addAuthor trigger.
  • At any one time, each trigger only deals with one row.
  • So for INSERT Trigger only hold reference of Inserted virtual Table

CREATE TRIGGER trig_addAuthor
ON authors
FOR INSERT
AS
— Get the first and last name of new author
DECLARE @newName VARCHAR(100)
SELECT @newName = (SELECT au_fName + ‘ ‘ + au_lName FROM
Inserted)
— Print the name of the new author
PRINT ‘New author “‘ + @newName + ‘” added.’

UPDATE TRIGGER

  • The “UPDATE” function is used to check whether or not the “au_fName” and “au_lName” fields have been updated by the “UPDATE” Query
  • “UPDATE” triggers have access to two virtual tables: Deleted (which contains all of the fields and values for the records before they were updated), and Inserted (which contains all of the fields and values for the records after they have been updated)
  • Update triggers can also be used to check field constraints and relationships

CREATE TRIGGER trig_updateAuthor
ON authors
FOR UPDATE
AS
DECLARE @oldName VARCHAR(100)
DECLARE @newName VARCHAR(100)
IF NOT UPDATE(au_fName) AND NOT UPDATE(au_lName)
BEGIN
RETURN
END
SELECT @oldName = (SELECT au_fName + ‘ ‘ + au_lName FROM Deleted)
SELECT @newName = (SELECT au_fName + ‘ ‘ + au_lName FROM Inserted)
PRINT ‘Name changed from “‘ + @oldName + ‘” to “‘ + @newName + ‘”‘

DELETE TRIGGER

  • It has only access to the virtual table “Deleted”
  • Same as INSERT, UPDATE

ADVANTAGES Of TRIGGERS

  1. When triggers are used correctly, they can save a lot of development work. One of the main benefits of using triggers is that they are stored in a central repository (the database), meaning that they are accessible from all client applications / web pages that can connect to the database.
  2. Before triggers came along, if we had a table that needed to be updated and we wanted to perform some actions after that update, then we would have to “hard code” the extra SQL into our application. This meant that if we wanted to change the code later down the track, then each client would need the updated version of our application. This is both annoying and time consuming.

Happy Coding 🙂

Optimizing SQL Server Database Design Tips & Tricks – Part 1

Database design is most crucial part in application development. Database can be anything SQL Server, MySQL, Oracle, etc. I will consider SQL SERVER as a part of discussion.

Tunning the database depends upon various factors like whether one datatype is better depends on the context of it’s usage. Following are most common datatypes used in database.

Numbers Datatype (For storing Primary Keys, Foreign Keys, Status etc) 

An int requires 4 times the storage of a tinyint. More storage means more data and

index pages to read / write, more I/O and thus potentially more seek time. It also means more memory consumption.

For eg. Desigining User Role and Users Table. Generally application will not have more than 5-10 user roles like Admin, Manager, Employee, etc. Most of developers design the table like - 

Table – UserRole

RoleId – Integer (whole number) data from –2^31 (–2,147,483,648) through 2^31–1 (2,147,483,647). It takes 4 Bytes to store.

RoleName – Varchar (50)

Which is not suiting to our requirements. Instead of int we can use tinyint – Integer data from 0 to 255. Storage size is 1 byte. 

 

DateTime Datatype (For storing dates)

Most of the times database tables required date to be stored to maintain record creation date. 

DateTime data type are stored internally two 4-byte integers. The first 4 bytes store the number of days before or after the base date: January 1, 1900. The base date is the system reference date. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

The smalldatetime data type stores dates and times of day with less precision than datetime. The Database Engine stores smalldatetime values as two 2-byte integers. The first 2 bytes store the number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight.

So, instead of using datetime as datatype smalldatetime is more efficient in general development.

 

STRING DATATYPE (Storing text data)

All string data stored inside varchar, text, ntext, nvarchar, etc. 

For eg. FirstName data field developers used varchar or nvarchar with default size i.e. 50. We should know the scope of the filed in terms of maximum characters. Generally first name, last name etc.. won’t take more than 20 – 25 characters. So instead of 50 if we use 20 characters we can save half the storage, index size which will increase performance of queries. 

 These are the basics which needs to keep in mind while developing applications. 

Happy Coding … 🙂