developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Online Shopping
Condos For Sale
Imprinted Gifts
Promotional Golf
Disney World Tickets
GPS
Promotional Products
Memory
Compare Prices
Shop
Server Racks
Desktop Computers
KVM over IP
Car Donations

 


Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.
Related Article -
Consider Database Triggers in Your .NET Enterprise Application Design
Implement User-defined Functions in SQL Server 2005 with Managed Code
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Using DDL Triggers to Manage SQL Server 2005
By Jeffrey Juday

Go to page: 1  2  Next  

SQL Server 2005 has extended the trigger functionality you normally use with Data Manipulation Language (DML) commands such as INSERT, UPDATE, and DELETE to incorporate Data Definition Language (DDL) commands like CREATE DATABASE, DROP TABLE, and ALTER TABLE. The new technology, called DDL triggers, comes in two flavors: database-level triggers that respond to changes to the database and server-level triggers that respond to changes on the server.

This article uses the sample AdventureWorks database and the SQL Server 2005 CTP to introduce DDL triggers and provide scenarios for using them.

Introducing DDL Triggers

Before delving into DDL triggers, learning what DDL triggers have in common with DML triggers may be helpful. First, DDL triggers are created, changed, and removed by using statements such as CREATE TRIGGER, ALTER TRIGGER, and DROP TRIGGER. The following is a typical DDL CREATE TRIGGER statement:

CREATE TRIGGER ddl_trig_loginAW
ON ALL SERVER
FOR DDL_LOGIN_EVENTS
AS
   PRINT 'Added trigger event to DDLServerTriggerData'
   INSERT INTO [AdventureWorks].[dbo].[dbo.DDLServerTriggerData]
               (DDLServerEvent) VALUES ( EVENTDATA())

Also, like DML triggers, DDL triggers run in the same transaction as the DML statement. So for instance, when a DDL TSQL statement has completed, you can rollback a transaction whenever appropriate.

Finally, both DDL and DML triggers can use the new CLR functionality in SQL Server 2005 for running a managed code assembly uploaded to SQL Server.

Unlike DML triggers, DDL triggers respond to completely different events. As previously stated, DDL triggers respond to changes to a database or a server. Each time DDL statements make changes using commands such as CREATE TABLE, an event is fired. DDL triggers can subscribe to those events and execute other TSQL instructions in response to the events.

Some other differences between DDL and DML triggers include the following:

  • DDL triggers do not support the INSTEAD of functionality in the CREATE TRIGGER statement.
  • DDL triggers are missing the inserted and deleted tables common to DML triggers.

Now that you're familiar with what DDL triggers do, you can set up a DDL trigger of your own.

Designing a DDL Trigger

When you define a DDL trigger, you must decide on the scope of your trigger. Scope determines whether the trigger executes at the database or the server level. (A forthcoming section discusses scope in more detail later in the article.)

After determining scope, you must decide whether the DDL trigger responds to a single DDL statement or a group of related statements. For example, the DDL trigger can respond to the DROP TABLE statement or all table operations (DROP, CREATE, ALTER). Typically, single events are named by using the TSQL statement and separating each word in the statement with an underscore (for example, CREATE_DATABASE). (Refer to the SQL Server 2005 Books Online for a complete list of events a DDL trigger can subscribe to.)

Once you've determined scope and events, you are ready to code the proper response. You will find the EVENTDATA() TSQL function most helpful for coding your response.

The EVENTDATA() Function

The EVENTDATA() function returns XML data with information such as event time, System Process ID (SPID), and type of event firing the trigger. A DDL trigger uses the EVENTDATA() function to determine how it must respond.

To retrieve information from XML data, you must use XQuery. A complete discussion of XQuery and the new XML Datatype is beyond the scope of this article. You can find an introduction of the XML Datatype on Developer.com at "The Fundamentals of the SQL Server 2005 XML 3Datatype".

The following is a sample of XML data returned by the EVENTDATA() function:

<EVENT_INSTANCE>
   <EventType>CREATE_TABLE</EventType>
   <PostTime>2005-07-30T10:48:52.537</PostTime>
   <SPID>55</SPID>
   <ServerName>PSE-TEST-JON1</ServerName>
   <LoginName>PSE-TEST-JON1\Administrator</LoginName>
   <UserName>dbo</UserName>
   <DatabaseName>AdventureWorks</DatabaseName>
   <SchemaName>Person</SchemaName>
   <ObjectName>Address</ObjectName>
   <ObjectType>TABLE</ObjectType>
   <TSQLCommand>
      <SetOptions ANSI_NULLS="ON"
                  ANSI_NULL_DEFAULT="ON"
                  ANSI_PADDING="ON"
                  QUOTED_IDENTIFIER="ON"
                  ENCRYPTED="FALSE" />
      <CommandText>CREATE TABLE [Person].[Address](
                                [AddressID] [int]
                                IDENTITY (1, 1)
                                NOT FOR REPLICATION NOT NULL,
      [AddressLine1] [nvarchar](60) NOT NULL,
      [AddressLine2] [nvarchar](60) NULL,
      [City] [nvarchar](30) NOT NULL,
      [StateProvinceID] [int] NOT NULL,
      [PostalCode] [nvarchar](15) NOT NULL,
      [rowguid] uniqueidentifier ROWGUIDCOL NOT NULL CONSTRAINT
         [DF_Address_rowguid] DEFAULT (NEWID()),
      [ModifiedDate] [datetime] NOT NULL CONSTRAINT
         [DF_Address_ModifiedDate] DEFAULT (GETDATE())
      ) ON [PRIMARY];</CommandText>
   </TSQLCommand>
</EVENT_INSTANCE>

As you can see, there are other pieces of information that depend on the DDL statement firing the trigger. (See the SQL Server 2005 Books Online for a complete list of XML Schemas.) The following sample code illustrates how you will access the XML returned by the EVENTDATA() function:

DECLARE @data XML;
DECLARE @schema sysname;
DECLARE @object sysname;
DECLARE @eventType sysname;
SET @data = EVENTDATA();
SET @eventType = @data.value('(/EVENT_INSTANCE/EventType)[1]',
                             'sysname');
SET @schema    = @data.value('(/EVENT_INSTANCE/SchemaName)[1]',
                             'sysname');
SET @object    = @data.value('(/EVENT_INSTANCE/ObjectName)[1]',
                             'sysname')

One important point concerning XQuery: If you're going to retrieve single values from the EVENTDATA() XML, use the "value" statement rather than the "query" statement. You will have better results with the formatting of the XML data.

DDL triggers can fire for changes in either the database or server. Now, the discussion turns to trigger scope in more detail.

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Database Archives

Whitepaper: Embeddable Content Platform for OEM's
Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.

Access FREE HP High-Availability Solutions for Exchange 2007 Tools:
Whitepaper:
Backup and Recovery Best Practices for SQL Server 2005, Including HP Data Protector
Whitepaper:
Configuration Best Practices for Microsoft SQL Server 2005 with HP EVA4000 and HP Blade Servers
Whitepaper:
Best Practices for Microsoft Exchange 2007 with HP Server and Storage in Mid-range


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES