SQL Server Performance

  • Home
  • Articles
  • Forums
  • Tips
  • Training
  • FAQ's
  • Blogs
  • Software
  • Books
  • About Us
RSS Feeds
Sign in | Join


Article Topics

All Articles
Performance Tuning
Audit
Business Intelligence
Clustering
Reporting Services
SQL Azure
Developer
General DBA
ASP.NET / ADO.NET
SQL Azure

USEFUL SITES :

ASP.NET Tutorials
Windows and SQL Azure Tutorials
Cloud Hosting Magazine
SharePoint Tutorials
Windows Server Help

Write for Us

Share your SQL Server knowledge with others and raise your profile in the community More...
Latest Articles

A High Level Comparison Between Oracle and SQL Server - Part ...
A High Level Comparison Between Oracle and SQL Server - Part ...
A High Level Comparison Between Oracle and SQL Server - Part ...
A High Level Comparison Between Oracle and SQL Server

More     
 
Latest FAQ's

Add Node to A SQL Server failover Cluster failed with invalid ...
SQL Server Destination remote server error
Setting Up Data And Log Files For SQL Server
Will Check Constraints Improve Database Performance?

More     
   
Latest Software Reviews

dbForge Review
Spotlight on ApexSQL Diff - Server-based database comparison tool ...
Spotlight on ApexSQL Data Diff - Server-based database comparison tool ...
Spotlight on ApexSQL Doc 2008

More     

articles >> general dba >> Understanding the Basic of Triggers

Understanding the Basic of Triggers

By : Tharindu Dhaneenja
Jan 28, 2009

 A trigger is an operation that is executed when some kind of event occurs to the database. It can be a data or object change.  Listed below are the different types of tiggers:

Types of Triggers

  • DML(data manipulation language) triggers (SQL Server 2000- 80.0)
    • AFTER triggers (Only Tables)
    • INSTEAD OF triggers (Tables or Views)
  • DDL(data definition language) triggers (SQL Server 2005- 90.0)
  • SQLCLR triggers (SQL Server 2005- 90.0)

Rules of Triggers

  • cannot create or modify Database objects using triggers
    • For example, cannot perform “CREATE TABLE… or ALTER TABLE” sql statements under the triggers
  • cannot perform any administrative tasks
    • For example, cannot perform “BACKUP DATABASE…” task under the triggers
  • cannot pass any kind of parameters
  • cannot directly call triggers
  • WRITETEXT statements do not allow a trigger

Advantage of Triggers

Triggers are useful for auditing data changes or auditing database as well as managing business rules.  Below are some examples:

  • Triggers can be used to enforce referential integrity (For example you may not be able to apply foreign keys)
  • Can access both new values and old values in the database when going to do any insert, update or delete

Disadvantage of Triggers

  • Triggers hide database operations.  For example when debugging a stored procedure, it's possible to not be aware that a trigger is on a table being checked for data changes
  • Executing triggers can affect the performance of a bulk import operation

Best Programming Practice

  • Do not use triggers unnecessarily, if using triggers use them to resolve a specific situation
  • Where possible, replace a trigger operation with a stored procedure or another kind of operation
  • Do not write lengthy triggers as they can increase transaction duration; and also reduce the performance of data insert, update and delete operations as the trigger is fired everytime the operation occurs.

How Triggers Work?



When a trigger is executed SQL Server creates two virtual tables called INSERTED and DELETED. For example when inserting a recode into a table, SQL Server creates a virtual table call INSERTED and loads data into the inserted table then executes the trigger statements and writes the related data pages. One feature of this is joining other tables to the virtual tables.

DML (data manipulation language)
One Table or View can have multiple triggers. Table triggers are executed whenever table data changes and view triggers only execute when data changes are made through the view.

Syntax:
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)
CREATE TRIGGER [schema_name.]trigger_name
ON {table | view}
[WITH <dml_trigger_option> [ ,...n ] ]
{FOR | AFTER | INSTEAD OF}
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[WITH APPEND]
[NOT FOR REPLICATION]
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

 <dml_trigger_option>::=
    [ENCRYPTION]
    [EXECUTE AS Clause]

<method_specifier> ::=
    assembly_name.class_name.method_name

AFTER triggers(Only Tables)

An after trigger is a database object that is Bind to a related table and these are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. It’s never executed if a constraint violation occurs. This cannot be defined on views.

Example
USE [AdventureWorks]
GO
--create table
CREATE TABLE [tblDataAuditLog](
 [DALID] [int] IDENTITY(1,1) NOT NULL,
 [comments] [varchar](250) NOT NULL,
 [recordedDate] [datetime] NOT NULL CONSTRAINT [DF_tblDataAuditLog_recordedDate]  DEFAULT (getdate()),
 [transactionType] [char](1) NOT NULL
);
GO
-- Drop the trigger.
IF OBJECT_ID ('Sales.trgDataAuditInsert','TR') IS NOT NULL
    DROP TRIGGER Sales.trgDataAuditInsert
GO
-- Create the trigger (INSERT)
CREATE TRIGGER [Sales].[trgDataAuditInsert]
  ON [Sales].[Customer]
  AFTER INSERT
AS
 DECLARE @AccountNumber varchar(15)
 SELECT @AccountNumber=INSERTED.AccountNumber FROM INSERTED
 INSERT INTO [dbo].[tblDataAuditLog]([comments],[transactionType])
 SELECT 'Insert new customer - '+ @AccountNumber , 'I';
GO
-- Create the trigger (DELETE)
CREATE TRIGGER [Sales].[trgDataAuditDelete]
  ON [Sales].[Customer]
  AFTER DELETE
AS
 DECLARE @AccountNumber varchar(15)
 SELECT @AccountNumber=DELETED.AccountNumber FROM DELETED
 INSERT INTO [dbo].[tblDataAuditLog]([comments],[transactionType])
 SELECT 'Delete customer - '+ @AccountNumber , 'D';
GO
-- Create the trigger (UPDATE)
CREATE TRIGGER [Sales].[trgDataAuditUpdate]
  ON [Sales].[Customer]
  AFTER UPDATE
AS
 DECLARE @AccountNumber varchar(15)
 SELECT @AccountNumber=DELETED.AccountNumber FROM DELETED
 INSERT INTO [dbo].[tblDataAuditLog]([comments],[transactionType])
 SELECT 'Update customer - '+ @AccountNumber , 'U';
GO

-- Disable trigger
IF OBJECT_ID ('Sales.trgDataAuditInsert','TR') IS NOT NULL
    DISABLE TRIGGER Sales.trgDataAuditInsert ON Sales.Customer;
GO

--insert
INSERT INTO sales.Customer(TerritoryID, CustomerType, ModifiedDate)
VALUES(1,'S',getdate());
--update
UPDATE Sales.Customer
SET ModifiedDate=getdate()+2
WHERE CustomerID=(SELECT MAX(CustomerID) FROM Sales.Customer);
--delete
DELETE FROM Sales.Customer
WHERE CustomerID=(SELECT MAX(CustomerID) FROM Sales.Customer);
GO
SELECT * FROM [tblDataAuditLog]
GO


        








C# Help and Tutorials | PHP MySQL Tutorial | Sharepoint Tutorial | Azure Tutorial | Cloud Hosting Magazine | ASP.NET Tutorials | Windows Server Help | Windows Phone Pro | Silverlight Ace | Visual Studio Tutorials | Home | Peformance Articles | Audit Articles | Business Intelligence Articles | Clustering Articles | Developer Articles | Reporting Services Articles | DBA Articles | ASP.NET / ADO.NET Articles | SQL Server Training Videos | DBA FAQ's | Developer Peformance FAQ's | DBA Peformance FAQ's | Developer FAQ's | Clustering FAQ's | Error Messages | Audit Tool Reviews | Backup Tool Reviews | Coding Tool Reviews | Compare Tool Reviews | Documentation Tool Reviews | Design Tool Reviews | Monitoring Tool Reviews | Log Tool Reviews | Reporting Tool Reviews | Clustering Tool Reviews | Security Tool Reviews | Change Management Tool Reviews | Remote Access Tool Reviews | Book Reviews | Security Tool Reviews | ADO.NET / ASP.NET | Administration | Analysis/OLAP Services | Application Development | Configuration | Components | ETL | Hardware | High Availability | Hints | Index | Misc | Operating Systems | Performance Tuning | Replication | T-SQL | Views


              © 2010 Jude O'Kelly. All rights reserved