YOUR FEEDBACK
Adobe Flex 2 - Answering Tough Questions About Enterprise Development
A Correct Person wrote: Denis Roebrt commented on the 21 Aug 2006 "Tough Que...

SYS-CON.TV
TOP MICROSOFT .NET LINKS


Using XML with Stored Procedures Effectively in SQL Server 2005
How things changed

Digg This!

.NET lets us easily serialize an object into XML and deserialize XML into its corresponding object. This functionality has been available since .NET 1.0. The introduction of new data type called XML in SQL Server 2005 gives us even more advantages that come in handy with Stored Procedures that attempt to insert/update records in multiple but related tables.

Usually this involves passing a huge number of parameters that make up the individual objects to the Stored Procedure; but with SQL Server 2005 we could potentially serialize the object(s) into an XML string and pass it as the input parameter, leaving us with cleaner code that's easy to read and maintain.

Consider the case of having a Person object with list of Address and Phone objects. The corresponding database schema would have tables for Person, Address, and Phone. When a new Person is inserted into the database (along with the corresponding address and phone number), generally we'd have to pass all the member variables of the Person object to a Stored Procedure and, if successful, call other Stored Procedures to insert the records into the Address and Phone tables.

I propose an alternate way of doing the same thing that's a lot simpler. Suppose we serialize the Person object along with its list of Address and Phone objects into XML; this XML parameter would then be passed to the Stored Procedure which could handle the inserts to the Person, Address, and Phone tables all by itself; and within the Stored Procedure, we'd use XQuery against the passed XML to extract the desired data. This eliminates multiple parameters to the Stored Procedure and minimizes the Stored Procedure calls to the database.

XML Serialization Primer
XML Serialization is the process of converting an object's public Properties and Fields (the current state of the object) into an XML stream; likewise, XML deserialization is the process of creating an object from an XML to a state as specified by the XML stream.

XML serialization comes in two flavors - when an object is serialized, its properties could either be expressed as 'Xml-Elements' (default) or as 'Xml-Attributes' in the XML output. Consider a simple class called "Book" as shown in Listing 1. Code to serialize an instance of "Book" into XML and deserialize the XML into another instance of "Book" is shown in Listing 2. Serialized XML for an instance of Book is shown in both formats in Listing 3.

Note that you would need a default constructor for the class for the XmlSerializer to serialize and deserialize. Also note that for an instance of an object, only those properties are serialized that have a non-null value.

The XmlSerializer class (defined in the namespace System.Xml.Serialization) is used for serialization and deserialization processes. As you can see, Xml-Element model is verbose when compared to the XmlAttribute model. In this article we'll consider the XmlAttribute model. As you've seen, to get the output in Xml-Element format, we don't have to do anything since it's the default behavior; on the other hand, for the XmlAttribute model, we have to annotate the public properties and public fields with XmlAttributes. To control the generated XML, we could apply special XML Attributes to the class or the public fields and public properties. Attributes provide additional information to the XmlSerializer class on how the data appears in XML. Here are a few important attributes to consider:

XmlAttributeAttribute: XmlAttributeAttribute (or just XmlAttribute) should be applied to the public properties and fields of the class that you want to be serialized as attributes (as opposed to elements). This article recommends using attributes model for XML serialization. Listing 1 below already offers an idea of how one model compares to the other. It shows how XmlAttribute is declared for properties. The name given for the attribute is the same as we see in the XML output. Generally we'd have the same name as the Property itself. However, if desired, we could change this as shown in Listing 5 for the class "Patient" for the property "MRN" that would be serialized as "Medical_Record_Number." Note: When specifying an Attribute, the phrase 'Attribute' could be omitted from the name of the attribute since .NET would recognize the attribute. This is true for all Attributes and not just XML attributes. This is the reason why XmlAttributeAttribute can be specified as simply XmlAttribute.

XmlRootAttribute: XmlRootAttribute (or just XmlRoot) decorates the class itself. It specifies how the root element would be displayed in XML. If this isn't specified, the name of the class would appear as-is, as the root element. Usually we don't have to set this attribute. However, there may be a case where the class name may not be suitable as the root name in the serialized XML. This can happen when the class name differs from the name used in business parlance. For instance, let's say we have a class called "Doctor"; by default, this would appear as the root in the serialized XML. But, if users like to see the root name as "Physician" instead of "Doctor" we need to set the XmlRoot attribute for the class as "Physician." This is shown in Listing 4.

XmlArrayItemAttribute: When we have to serialize a collection XmlArrayItemAttribute comes in handy. Consider the case of a "Doctor" having a list of patients as a Property. Listing 5 shows the Patient class and a property in the Doctor class called "Patients," which is decorated with the attribute XmlArrayItemAttribute. Note the XML output that lists the XML node as "Patients" (the same name as that of the property) and each patient is listed with the XML node "Patient" that is the same as the class name for the Patient class.

We've seen the snippet of code that does serialization and deserialization in Listing 3. However this code snippet is specific to the "Book" class. To generalize the code for serialization and deserialization, we could define these functions in a common base class. Let's define a class called "BusinessBase" that could serve as a base class to all business objects. This class could then have two functions - ToXML() for serialization and FromXML() for deserialization. This way, any business object like Person, Doctor, Patient, Phone, Address, etc. could automatically leverage this functionality.

Code for BusinessBase is shown in Listing 6.

Notice the Copy() function that serves as a Copy Constructor (deep copy). This is needed since the Deserialize() function of XmlSerializer returns an object that has to be copied into 'this' again. Use of these functions is shown in Listing 7, assuming that we've derived the class "Book" from "BusinessBase."

We've already defined the "Person" class. Let's add collections to this class, one for the address list and the other for the phone list. To do this, we need two classes called "Address" and "Phone." Listing 8 below shows the "Address" and "Phone" classes along with the part of the "Person" class that reflects the change.

Note that we have defined enums "AddressType" and "PhoneType" to enumerate different types of addresses and phones respectively. These enums have to be kept in synch with the data defined in the database tables "AddressType" and "PhoneType."

XmlIgnoreAttribute: We've already said that by default, all public properties and fields of a class are serialized; if any of these have to be omitted, we need to annotate the desired properties/fields with the attribute XmlIgnoreAttribute or in short, XmlIgnore.

Omitting certain data from serialization could prove handy if you want to serialize only a select set of properties. As seen in Listing 8, we have two properties for the field _addrType: AddrType and AddressTypeId; the former an 'AddressType' type and latter of 'int' type. In the XML output, we need the property to be expressed as 'int' since that's how it's expressed in the database (AddressType table). The other property need not be serialized to XML, which is why it's annotated with the attribute XmlIgnore.

The corresponding database schema for these classes would be as shown in Figure 1.

Now, to insert a Person record along with its Address records and Phone records in one Stored Procedure all we have to do is serialize the Person object and pass the XML to the Stored Procedure. In the Stored Procedure, we'd use XQuery to parse the XML and extract the data as needed.

Listing 9 shows the code snippet that instantiates a Person object along with its Address and Phone collections, and the corresponding XML representation of the Person instance.

The Stored Procedure "CreatePerson" could be seen in Listing 10.

Notice the use of TRY-CATCH blocks in the Stored Procedure. From SQL Server 2005 onwards, this is the preferred way to catch any errors during the execution of a Stored Procedure; in earlier versions, global parameter @@ERROR was used to retrieve the code of the last error when executing a SQL statement, and "GO TO" statements had to be used to modify the control flow. Using TRY-CATCH block eliminates this to write cleaner code; if an exception does get raised in a TRY block during the execution, control automatically jumps to the CATCH block where the appropriate error-handling code could be placed. If Stored Procedure executes without any exceptions then control doesn't enter the CATCH block at all. As seen in Listing 10, at the end of the TRY block, we commit the transaction and return the error code (0=success) and the ID of the inserted "Person" record; whereas, in the CATCH block, we roll back the transaction and return the error code and error message.

XQuery or XML Query Language is a W3C specification on how XML could be queried. XQuery specification document could be found at www.w3.org/TR/xquery/.

The value() and nodes() are the XML data type methods in SQL Server 2005. Other methods available, but not used in this article are query(), exist(), and modify().

The nodes() method returns an unnamed rowset, which is why it's aliased in CreatePerson SP as seen in Listing 10. The value() method extracts the value of the node from the rowset with the type specified. Note that it can extract multiple values if the rowset returned by the nodes() method contains multiple values. This is how multiple address or phone records could be inserted with just one INSERT statement.

As you've seen in this article, using XML saves us from passing multiple parameters to the Stored Procedure, and it facilitates inserting records into multiple/linked tables cleanly. Later, if the object properties change or tables get modified, the input to the Stored Procedure doesn't have to change, and could continue to be XML; the Stored Procedure itself would have to be changed to reflect the changes, but the caller wouldn't have to modify the input parameters to the Stored Procedure. So code maintenance is easier since minimal changes have to be made.

About Srinivas K. Surampalli
Srinivas K. Surampalli alias Kal is a senior consultant at Magenic Technologies. He has over a decade of experience in delivering innovative technology solutions to businesses using Microsoft Technologies. He is a MCSD for Microsoft.NET and Microsoft Visual Studio 6.0. When not working, Kal enjoys playing with his two children Avyay and Anagha.

Steve Jones wrote: Works great until you want to serialize a class that inherits from another class. That's when starts to breaks down.
read & respond »
Amy Pham wrote: Can you also provide an example of updating using XML? Thanks, Amy
read & respond »
Amy Pham wrote: Thanks so much for this example. It's so easy to follow and it works. The only thing that I would like to change is to replace @@Identity with SCOPE_IDENTITY(). Contributors like you make life a lot easier :-)
read & respond »
munkeecoder wrote: Great idea! Good article, thanks for taking the time to share with us. Are there performance issues using an XML parser to do this instead of the old trusty parameter way? We still are looking for the best performance despite advances in memory and disk access.
read & respond »
MICROSOFT .NET LATEST STORIES
Icahn Moves To Force Microsoft & Yahoo Together
Corporate raider Carl Icahn started his proxy fight for control of Yahoo this morning, beginning with the classic Icahn opening, the letter of reproach to the Yahoo board telling them they have acted 'irrationally and lost the faith of shareholders and Microsoft.'
IBM, Microsoft & Google Eras of Computing
By now it is conventional wisdom to say that there was an IBM Era of computing, then a Microsoft Era, and now we are in the Google Era. In this post, I will explain why Microsoft was not the 'next IBM' and why Google is not the 'next Microsoft' - there are significant qualitative diffe
Book Review: ASP.NET 2.0
ASP.NET developers are bored with traditional books that outline concepts in a lengthy way. These books are good if you like to learn the features in a detailed manner. However, by the time the book is read, a new version will be released. Hence, many learners including myself prefer s
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
"RIA" vs "Rich Client Platform": The Term Is Now Up for Debate
'RIA' is slowly fading in terms of its definition. When I first started the RIA Evangelism role in Microsoft, I had this nagging feeling that the term RIA was just all over the place. Depending on which technology you are backing and which stream of alliance you uphold, the truth is th
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING NEWS FROM THE WIRES
Strangeloop Networks Selected for Red Herring 100 North America 2008
Strangeloop Networks (TM) Inc., a leading provider of solutions that accelerate dynamic web