Welcome!

Microsoft Cloud Authors: Pat Romanski, Andreas Grabner, Nick Basinger, Kevin Benedict, Liz McMillan

Related Topics: Microsoft Cloud, Industrial IoT

Microsoft Cloud: Article

Using XML with Stored Procedures Effectively in SQL Server 2005

How things changed

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

More Stories By 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.

Comments (4)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.