SQL Server
  Home arrow SQL Server arrow Page 2 - Using Triggers In MS SQL Server
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
SQL SERVER

Using Triggers In MS SQL Server
By: David Rusik
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 476
    2002-01-01

    Table of Contents:
  • Using Triggers In MS SQL Server
  • What exactly is a trigger?
  • UPDATE and DELETE triggers
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Using Triggers In MS SQL Server - What exactly is a trigger?


    (Page 2 of 4 )

    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. As the name suggests, a trigger is “fired” whenever an INSERT, UPDATE, or DELETE SQL command is executed against a specific table.

    Triggers are associated with a single table, and are automatically executed internally by SQL Server. Let’s create a very basic trigger now (I am using Microsoft SQL Server 7.0 on a Windows 2000 machine).

    Start by opening Enterprise Manager (Start -> Programs -> Microsoft SQL Server 7.0 -> Enterprise Manager). In this example we will create our trigger against the “authors” table of the "pubs" database, so drill down through the tree view in the left pane until you can see the "“authors" table of the "pubs" database in the right pane, like this:

    Selecting the authors table of the pubs database

    Next, right click on the "authors" table and choose All Tasks -> Manage Triggers... this will open the trigger properties window, which allows us to create a new trigger:

    The trigger properties window

    Delete all the text in the text box; we won’t need it because we’re creating our trigger from absolute scratch. All triggers are created using the "CREATE TRIGGER" command. The syntax of the “"REATE TRIGGER" command is shown below:

    CREATE TRIGGER trigger_name

    ON { table | view }

    [ WITH ENCRYPTION ]

    {

    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

    [ WITH APPEND ]

    [ NOT FOR REPLICATION ]

    AS

    [ { IF UPDATE ( column )

    [ { AND | OR } UPDATE ( column ) ]

    [ ...n ]

    | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )

    { comparison_operator } column_bitmask [ ...n ]

    } ]

    sql_statement [ ...n ]

    }

    }


    It looks really confusing, but it’s actually quite simple. I won’t go into detail about it, but you can visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_create2_7eeq.asp for the full explanation. Enter the following SQL code into the text box:

    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.'


    Click on the "OK" button. We have just created a new trigger named "trig_addAuthor", which is attached to the "authors" table of the "pubs" database. Whenever a new record is added to the "authors" table, SQL Server will automatically execute our trigger. Let’s discuss the actual SQL code that makes up the trigger:

    CREATE TRIGGER trig_addAuthor

    ON authors


    These two lines tell SQL server that we want to create a new trigger object named "trig_addAuthor", which will be attached to the "authors" table.

    FOR INSERT

    Here, we have specified that our trigger will be executed whenever an "INSERT" command is executed against the "authors" table. Other possible options include "UPDATE" and "DELETE", which would be triggered when one/more rows in the "authors" table were either updated or deleted.

    If we wanted, we could handle more than one type of query in one trigger. For example, to handle both "INSERT" and "UPDATE", we would use "FOR INSERT, UPDATE".

    AS

    DECLARE @newName VARCHAR(100)

    SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted)


    Any code after the "AS" keyword is actually executed when the trigger is called. It’s important to note that this part of the trigger can contain any code that a standard stored procedure could contain. You can also call stored procedures using the "EXEC" command from within the body of the trigger.

    We have created a new variable named "newName". "newName" is a variable length character value that can hold a maximum of one hundred characters. On the next line, we assign the value of an SQL query to the "newName" variable.

    SELECT au_fName + ' ' + au_lName FROM Inserted

    We can see that this SQL command retrieves the au_fName and au_lName fields from the "Inserted" table. The "Inserted" table is a virtual table which contains all of the fields and values from the actual "INSERT" command that made SQL Server call the trigger in the first place.

    To understand what I mean, let's take a look at the design of the actual "authors" table in the "pubs" database. Right click on it and choose Design Table:

    The schema of the authors table

    A typical "INSERT" query to add a record to the "authors" table might look like this:

    INSERT INTO authors(au_id, au_lname, au_fname, phone, address, city, state, zip, contract) VALUES('172-85-4534', 'Doe', 'John', '123456', '1 Black Street', 'Doeville', 'CA', '90210', 0)

    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. The table is named "Inserted" because it contains all of the newly added fields and values from our "INSERT" command.

    If we created a trigger that was activated when we deleted a record from the "authors table (using the "FOR DELETE" syntax), then the virtual table would contain all of the fields and values from the deleted record(s), and would be named "Deleted".

    Likewise, if we created a trigger for when an authors details were updated (using the "FOR UPDATE" syntax), then both the "Inserted" and "Deleted" virtual tables would be created and available from within the trigger. The "Deleted" table would contain all of the fields and values for the row(s) before they were updated, and the "Updated" table would contain the new row(s) with the updated fields and values.

    When dealing with triggers, you must understand how they actually operate on the data contained within their virtual tables. Let’s say that we run an "UPDATE" command on the "authors" table, which has a trigger attached to it. The "UPDATE" command might affect more than one row.

    When this is the case, the "UPDATE" trigger is called for each row that was affected by the update command. So, at any one time, each trigger only deals with one row.

    PRINT 'New author "' + @newName + '" added.'

    Lastly, we print the "newName" variable, which now contains the full name of the new author that has just been added.

    To test our new trigger, start Query Analyzer (Start -> Programs -> Microsoft SQL Server 7.0 -> Query Analyzer) and connect to your database server. Enter the following code into the SQL query pane:

    USE pubs

    GO

    SET NOCOUNT ON

    INSERT INTO authors(au_id, au_lname, au_fname, phone, address, city, state, zip, contract)

    VALUES('172-85-4534', 'Doe', 'John', '123456', '1 Black Street', 'Doeville', 'CA', '90210', 0)


    Click the "Play" button, or press the F5 function key to execute our "INSERT" statement. SQL Server will add the new record to the "authors" table, automatically calling our "trig_addAuthor" trigger once it's done. This is shown in the example below:

    The results of adding a new record to the authors table

    More SQL Server Articles
    More By David Rusik


       · >> When this is the case, the "UPDATE" trigger is called for each row that was>>...
       · Its really very helpfull for the beginners to learn it
       · >> When this is the case, the "UPDATE" trigger is called for each row that was>>...
       · >> When this is the case, the "UPDATE" trigger is called for each row that was >>...
       · i have faced the same problem where i get an error which says multiple rows selected...
       · its very helpful
       · Very helpful for new ppl learning sql serverThanks,
       · A)once triggers are called after specific times of insert command executions of...
     

    SQL SERVER ARTICLES

    - Executing SQL Server Stored Procedure from P...
    - How to Search for Date and Time Values Using...
    - Replication: SQL Server 2000 - Part 2
    - Replication: SQL Server 2000 - Part 1
    - SQL Sever: Storing Code in Binary or Text Fi...
    - Execute SQL on Multiple Tables/Columns - New...
    - How to Connect to a SQL Server from Visual F...
    - SQL Server Hardware Tuning and Performance M...
    - Primary Key on Multiple Tables – New RDBMS C...
    - Migrating from Sybase to SQL Server
    - What's Best for DBAs? GUI or T-SQL Comma...
    - How to Perform a SQL Server Performance Audit
    - An Introduction To The Bulk Copy Utility
    - SQL Server Stored Procedures 101
    - Building Your First SQL Server 2000 Database







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek