Skip to main content

Triggers In SQL

Triggers In SQL

A trigger is essentially a special type of stored procedure that can be executed in response to one of three conditions:

  • INSERT
  • UPDATE
  • DELETE
The Transact-SQL syntax to create a trigger looks like this:
CREATE TRIGGER TRIGGER_NAME
ON TABLE_NAME
FOR{INSERT, UPDATE, DELETE}
AS SQL_STATEMENTS

Triggers are most useful for enforcing referential integrity. The referential integrity enforces rules used to ensure that data remains valid across multiple tables.
Suppose a user entered the following command:
insert into Orders(OrderId, OrderName, Quantity, CustomerId) values(1, 'SQL Books', 2, 1)
GO
This perfectly valid SQL statement inserts a new record in the Orders table. However, a quick check of the Customers table shows that there is no CustomerId =1. A user with insert privileges in the Orders table can completely destroy your referential integrity.

Triggers and Transactions

The actions executed within a trigger are implicitly executed as part of a transaction. Here's the broad sequence of events:
  1. The BEGIN TRANSACTION statement is implicitly issued (for tables with triggers).
  2. The INSERT, UPDATE, or DELETE operation occurs.
  3. The trigger is called and its statements are executed.
  4. The trigger either rolls back the transaction or the transaction is implicitly committed.
Examples

This example illustrates the solution to the Orders table update problem mentioned earlier.
CREATE TRIGGER CHECK_CUSTOMERS
ON ORDERS
FOR INSERT, UPDATE AS
IF NOT EXISTS(SELECT * FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.CUSTOMER_ID=ORDERS.CUSTOMER_ID)
BEGIN
PRINT 'ILLEGAL CUSTOMER_ID'
ROLLBACK TRANSACTION
END
GO
A similar problem could exists for deletes from the ORDERS table. Suppose that when you delete an customer's only record from the ORDERS table, you also want to delete the customer from the CUSTOMERS table. If the records have already been deleted when the trigger is fired, how do you know which CUSTOMER_ID should be deleted? There are two methods to solve this problem:

First, Delete all the customers from the CUSTOMERS table who no longer have any orders in the ORDERS table.
CREATE TRIGGER DELETE_CUSTOMERS
ON ORDERS
FOR DELETE AS
BEGIN
DELETE FROM CUSTOMERS WHERE CUSTOMER_ID NOT IN(
SELECT CUSTOMER_ID FROM ORDERS
)
END
GO


Second, Examine the deleted logical table. Transact-SQL maintains two tables: DELETED and INSERTED. These tables, which maintain the most recent changes to actual table, have the same structure as the table on which the trigger is created. Therefore, you could retrieve the customer ID's from the DELETED table and then delete these ID's from the CUSTOMERS table.
CREATE TRIGGER DELETE_CUSTOMERS
ON ORDERS
FOR DELETE AS
BEGIN
DELETE CUSTOMERS FROM CUSTOMERS, DELETED
WHERE CUSTOMERS.CUSTOMER_ID = DELETED.CUSTOMER_ID 
END
GO

Restrictions On Using Triggers

The trigger is a powerful feature of the relational database that promotes flexibility and maximized control of data processing. However, triggers do have their limitations. You must observe the following restrictions when you use triggers:
  • Triggers cannot be created on temporary tables.
  • Triggers must be created on tables in the current database.
  • Triggers cannot be created on views.
  • When a table is dropped, all triggers associated with that table are automatically dropped with it.

Comments

Popular posts from this blog

FORCE ORDER in SQL Server

The FORCE ORDER is a query hint it executes the order of the tables exactly specified in a statement. When we use this query hint in a statement it will tell SQL server not to change the order of the joins in the query. Basically, the SQL server rearrange your joins to be in the order that it thinks it will be optimal for your query to execute. Now, Lets see the execution plan without the FORCE ORDER: The above execution plan demonstrates the optimal order of the joins returned by the SQL server. As you can see the order starts from the sales details and goes by bank details to employee details. Suppose if you don't want the SQL server to change the order of the joins in a query you can use FORCE ORDER to stop the default ordering. The syntax for FORCE ORDER query hint is, OPTION ( FORCE ORDER ); Now, Lets see the execution plan with the FORCE ORDER: select * from tbl_EmployeeDetails as e inner join tbl_BankDetails as b on e.Id=b.EmpID inner join tbl_S...

How to create comma separated values in SQL server?

Comma Separated Values in SQL Predominantly in reporting, you may gone through a situation where you need to convert a comma separated values into list of rows or to convert a list of rows into single column to display in a report. In this splash reading, you will understand the following: How to convert comma separated data in a column to multiple rows How to convert multiple rows into one comma separated values Using COALESCE function Using STUFF function Convert comma separated data in a column to multiple rows Here we have an Customer table with a list of products bought by each customer, ID CUSTOMER PRODUCTS 1 Stuart Chain Saw,Circular Saw 2 Michael Drill,Hammer 3 Jonathan Sticky Notes,Mouse 4 Nabeel Mobile,Headset Suppose you want to return this as a single table, list of products bought by each customer. we need to create a function that splits our comma separated col...

OPTION (MERGE JOIN) in SQL Server

OPTION (MERGE JOIN) in SQL Server The MERGE JOIN query hint is a best available join algorithm in SQL server. It is based on first sorting  both data sets according to the join conditions and then traversing through the sorted data sets and finding matches. The MERGE JOIN itself is very fast, but it can be an expensive choice if sort operations are required. This produces the best optimal execution plan. The syntax is, OPTION ( MERGE JOIN ); Now, Lets see how to use MERGE JOIN with SELECT statement.? select * from tbl_EmployeeDetails as e inner join tbl_BankDetails as b on b.EmpId=e.Id OPTION(MERGE JOIN); The statement returned optimal execution plan is, The MERGE JOIN operator gets a row from each input and compares them. In above statement, it merges all joins and first sorting data sets and then traversing through the sorted data sets and finding matches, if they are equal the rows are returned. If they are not equal, the lower-value row is rem...

How to manipulate JSON data in SQL server?

Manipulate JSON data in SQL Server JavaScript Object Notation (JSON) is a lightweight popular data exchangeable format used across modern IoT platforms, web and mobile applications etc. It is a language independent textual data format. JavaScript Object Notation (JSON) is also used for storing unstructured data in log files or NoSQL Databases such as Microsoft Azure Cosmos DB. Many RESTful web services that allow us to store and retrieve JSON formatted texts among different protocols using different Endpoints. The example of JSON text is as follows, [{         "customer":"Michael",         "products":["Watch","Mobile","Books"] }, {         "customer":"Stuart",         "products":["Laptop","Keyboard","Mouse"] } ] In this article you will understand the following, Read JSON data from table Modify JSON data in a table Validate JSON objects  ...

OPTION Loop Join in SQL Server

The OPTION ( LOOP JOIN ) would enforce LOOP JOIN across all joins in the query. Using the OPTION ( LOOP JOIN ) appears to allows the query optimizer to join the tables using the nested loops in which ever order SQL server decides it is optimal. The OPTION clause must be a last clause in a statement. The syntax is, OPTION ( LOOP JOIN ); Now, Lets see how to use LOOP JOIN with SELECT statement.? select *from tbl_EmployeeDetails as e inner join tbl_BankDetails as b on b.EmpID=e.Id inner join tbl_SalesDetails as s on s.BankId=b.Id OPTION(LOOP JOIN); The statement returned execution plan is, The above statement loops through all the joins that starts from sales details and goes by bank details to employee details in which the order that SQL server thinks it is optimal. This does not follow the order of joins that we specify. Suppose, if you want the SQL server to follow the order of joins that you specify you have to use FORCE ORDER in OPTION clause. Howe...