|
|
YOUR FEEDBACK
|
TOP MICROSOFT .NET LINKS Feature
Using XML with Stored Procedures Effectively in SQL Server 2005
How things changed
Jul. 30, 2007 04:45 PM
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.
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 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.
MICROSOFT .NET LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK BREAKING NEWS FROM THE WIRES
|
||||||||||||||||||||||||||||||||||||||