MS SQL Server
  Home arrow MS SQL Server arrow Page 4 - Using Triggers
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
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? 
MS SQL SERVER

Using Triggers
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2006-09-28

    Table of Contents:
  • Using Triggers
  • Cascading Deletes
  • Aggregates
  • Enforce Schema Integrity Among Objects on Different Servers or Databases

  • 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 - Enforce Schema Integrity Among Objects on Different Servers or Databases


    (Page 4 of 4 )

    I showed you earlier how DDL triggers can be used to audit and prevent changes on database objects. They could also be used to maintain a database schema. In the following example, a large table is horizontally partitioned into quarterly tables (to make management easier). Each table should store sales information about sales in one quarter. Therefore, there are four tables that should be maintained identically:

    Create database Quarterly
    Go
    Use Quarterly
    Go
    Create table Sales1(
      PartId int,
      CustomerId int,
      SalesDate smallint,
      Sales float)
    Go
    Create table Sales2(
      PartId int,
      CustomerId int,
      SalesDate smallint,
      Sales float)
    Go
    Create table Sales3(
      PartId int,
      CustomerId int,
      SalesDate smallint,
      Sales float)
    Go
    Create table Sales4(
      PartId int,
      CustomerId int,
      SalesDate smallint,
      Sales float)
    Go

    After the set of tables is created, we could create a DDL trigger to capture database changes on the Sales1 table and propagate it to other tables. The trigger is based on the Transact-SQL command captured using EventData():

    CREATE TRIGGER trdReplicateSalesTableChanges
    ON DATABASE
    AFTER DDL_TABLE_EVENTS
    AS
    Print 'trdReplicateSalesTableChanges started.'
    declare @event xml
    declare @Object sysname,
          @ObjectType sysname,
          @TSQLCommand nvarchar(max),
          @TSQLCommand2 nvarchar(max),
          @i int

    set @event = EVENTDATA()
    set @Object = @event.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)') 1234567890123456789012345678901234567890 123456789012345678901234567890
    set @ObjectType = @event.value('(/EVENT_INSTANCE/ObjectType)[1]', 'nvarchar(100)')
    set @TSQLCommand = @event.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(max)')

    if (@ObjectType = 'TABLE')
    begin
      if (@Object = 'Sales1')
      begin
        -- replace Sales1 string with 2-4
        Set @i = 2
        While @i <= 4
        Begin
          Set @TSQLCommand2 = REPLACE(@TSQLCommand,'Sales1',
           'Sales' + Cast(@i as varchar))
          --execute
          print @TSQLCommand2
          Exec Sp_executeSql @TSQLCommand2
         
    set @i = @i + 1
        end
      end
    end
    GO

    To test the trigger, we will add a column to the table:

    alter table Sales1
       add StoreId int null

    The trigger will replicate the change to other tables and print the debug information:

    trdReplicateSalesTableChanges started. alter table Sales2
       add StoreId int null
    alter table Sales3
       add StoreId int null
    alter table Sales4
       add StoreId int null

    It is justified to leave the print statement in this trigger, since the trigger is designed to be used only during the administrative tasks on table schemas.

    NOTE


    There may be changes that are too complex and that cannot be propagated correctly this way. You should test results in development and test environment before you use this method in production.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the book "Microsoft SQL Server 2005 Stored Procedure...
     

    Buy this book now. This article is excerpted from chapter nine of the book Microsoft SQL Server 2005 Stored Procedure Programming in T-SQL and .NET, written by Dejan Sunderic (McGraw-Hill/Osborne, 2006; ISBN: 0072262281). Check it out today at your favorite bookstore. Buy this book now.

    MS SQL SERVER ARTICLES

    - Completing the Introduction to Transact-SQL
    - A Brief Introduction to Transact-SQL
    - Lookups and Blocking Bad Data
    - Field Validation Rules for Blocking Bad Data
    - Using Masks to Block Bad Data
    - Blocking Bad Data
    - Using @@ROWCOUNT and TABLE Variables for Dat...
    - How to Use Variables, IF and CASE in Databas...
    - Creating Important Aspects of Notification S...
    - Working wth Variables in Database Interactio...
    - Delving Deeper into Notification Services
    - Notification Services
    - Building a Multi-table Report with SQL 2005 ...
    - A Secure Way of Building Connection Strings
    - Transferring a Database Using the SSIS Desig...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway