One of the more common uses of triggers is to create data manipulation language (DML) logging functionality. Essentially you can intercept and log inserts, updates, and deletes to tables. In the simplest case it's enough to know that one of these operations has occurred on a table, the date/time that it occurred, and some sort of identifying information for the user that performed the operation. At the other end of the requirements spectrum is the need to identify all information, including data indicating what exactly has changed.
What you usually find is that people who need to log DML operations will write one trigger and modify the same basic code for every other table that needs to be logged. I know one person who even wrote a client-side utility to automatically generate custom trigger code for hundreds of tables that he had to log. One problem with this method, apart from the sheer boredom of modifying the same trigger, again and again, is maintenance. If the underlying table structure changes your trigger is suddenly shot. In this post we're going to use FOR XML and SQL Server catalog views to create a dynamic trigger that will work on just about any table, and will automatically adjust it's output if the table structure changes.
CREATE
Next we’ll create a dynamic trigger. By dynamic I mean that you can run this script against any table and it will create a trigger that automatically detects its parent table and schema and logs all DML actions against the table properly, regardless of table structure. The example below creates the dynamic trigger on the AdventureWorks HumanResources.Shift table.
-- Change the schema and table name to match any-- existing table in your database
INSERT
Each entry has information like the schema name, table name, date/time, user name, etc. The Changes column is an XML data type column with the contents of the inserted and deleted virtual tables in XML format. The image below shows the results of the sample UPDATE statement above.
This type of dynamic logging is especially useful when you have to log DML activity for several tables in a transactional system. A couple of caveats: This trigger may require some changes if your table contains LOB data type columns. Also always take care when using triggers on high-DML activity tables, as triggers of any kind can affect performance.
SQL Server Standard magazine will be publishing more of these tips for getting the most out of SQL Server XML in a future issue.
I've decided to kick this blog off with a double-feature. In the last post I gave an example of shredding XML query plans with the nodes() method. In this one we'll discuss the nodes() method in a little more detail.
In a previous post on the Pseudo-Random blog, I recommended that everyone who's still using OPENXML should switch over to the xml data type's nodes() method. The problems I mentioned included:
I don't want to use up this entire blog entry complaining about OPENXML, so I'll cut it short here. From the above you get the idea that OPENXML is an inferior method of shredding XML data. So what's the alternative? Glad you asked. The xml data type includes several built-in methods, including one method designed just for shredding XML data: the nodes() method. Basically this method works like this:
The sample query below demonstrates the nodes() method. In the sample we shred the XML document into relational rows, and query the context node ('.') to return each relational row.
DECLARE @xml XML;-- Character representation of the XMLSET @xml = '<capitals> <state name="Alabama" abbreviation="AL" capital="Montgomery" /> <state name="Alaska" abbreviation="AK" capital="Juneau" /> <state name="Arizona" abbreviation="AZ" capital="Phoenix" /></capitals>';-- Retrieve each individual node from the relational result setSELECT Node.query('.')FROM @xml.nodes('/capitals/state') TempXML (Node);
Once the xml data type instance is shredded into relational rows of the xml data type, you can use the other xml data type methods like query() and value() to extract nodes and scalar values from the rows. As I previously said, the xml rows returned by the nodes() method are restricted in their functionality. You can't cast them to other data types; you can only use the xml data type methods on them to extract their contents. We can use the value() method in our example to extract each state's name, abbreviation, and capital from the nodes() result set, as shown below.
DECLARE @xml XML;-- Character representation of the XMLSET @xml = '<capitals> <state name="Alabama" abbreviation="AL" capital="Montgomery" /> <state name="Alaska" abbreviation="AK" capital="Juneau" /> <state name="Arizona" abbreviation="AZ" capital="Phoenix" /></capitals>';-- Retrieve scalar values from the relational result setSELECT Node.value('@name', 'varchar(100)') AS Name, Node.value('@abbreviation', 'varchar(2)') AS Abbreviation, Node.value('@capital', 'varchar(100)') AS CapitalFROM @xml.nodes('/capitals/state') TempXML (Node);
As you can see, this syntax is fairly intuitive, especially when compared to the equivalent OPENXML syntax. The results are shown below.
In the next post we'll talk about loading XML data from files from the file system directly into SQL Server.
Hi everyone, in this blog I plan to discuss the new SQL Server 2005 and SQL Server 2008 XML features. While I have several topics I plan to cover already, if you have specific SQL Server + XML related questions, feel free to contact me via this blog and I'll try to answer, or at least help you get a little closer to the answer.
I decided to kick this off with a simple example to demonstrate the utility of XML in SQL Server. SQL Server 2008 and 2005 store cached XML query plans that are accessible via the sys.dm_exec_query_plan dynamic management function. This function takes a query plan handle as an argument and returns the XML query plan, along with some other metadata.
While I was at the PASS Conference in Denver, I threw together a quick example to demonstrate shredding the cached XML query plans on SQL 2005. I expanded it a little bit to include some other information from the sys.dm_exec_sql_text dynamic management function and the sys.dm_exec_cached_plans dynamic management view.
This sample query uses a few of the new features available starting with SQL 2005: the CROSS APPLY operator, Common Table Expressions (CTEs), dynamic management views/functions, and the ROW_NUMBER() windowing function.
The most important feature we're using here is the xml data type and its nodes() and value() methods. Since the XML query plans are stored as xml data type data, we are using the nodes() method to shred the XML data nodes into rows. Then we apply the value() method to each of these new rows to extract individual query plan operators and operator information from the plan. In this case we pull the physical operator name ("Nested Loops", "Filter", etc.) and the estimated subtree cost for each operator. As a bonus we are grabbing the initial SQL statement that is the basis for the plan from the sys.dm_exec_sql_text dynamic management view. That way we can easily relate the query plan, and its individual operators, back to the source SQL statement.
This is just one example of the capabilities of the xml data type. In upcoming posts I'll describe more precisely how the xml data type methods and XQuery work.