IT tutorials
 
Database
 

SQL Server 2012 : The XML Data Type (part 2) - Typed versus Untyped XML, XML Schemas

2/10/2014 12:37:25 AM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

Typed versus Untyped XML

The difference between typed and untyped XML is simply the process to apply a schema to the XML. For example, you can create columns, variables, and parameters of type XML without applying a schema. These instances are untyped. Applying an XML schema makes the XML instances typed.

Now look at an example. In the following code, an XML data type variable called @var is declared, and an XML fragment is then assigned the variable. That variable is then used to insert the XML fragment into the ItemInfo table. The next statement assigns a different XML fragment to the XML data type variable and inserts it into the ItemInfo table.

DECLARE @var xml 

SET @var =
'<Root>
<Junk1>Some Junk</Junk1>
<Junk2>Some More Junk</Junk2>
<Junk3>Even More Junk</Junk3>
<Junk4>Too Much Junk</Junk4>
</Root>'

INSERT INTO ItemInfo (OrderID, ItemData)
VALUES (1, @var)

SET @var =
'<Vendor Name="Fast Freddys Five Finger Discount" Address="No Specific Location"
Phone="" Description="All conversations should start with pssssst, buddy...." />'

INSERT INTO ItemInfo (OrderID, ItemData)
VALUES (2, @var)
GO

Although this is doable, two important and critical questions should pop into mind:

  • How do you validate the XML?
  • How do you query the XML?

What this simple example illustrates is that allowing any format of XML into a column makes it difficult to validate and even more difficult to query it. For example, suppose you allow anyone to insert any format of XML into an XML column. This is unmanageable, and has a negative impact on performance.

Typing XML offers several benefits, the most important being that the validation constraints are always respected, and the content of the XML can always be valid as per the schema. Thus, SQL Servers' query optimizer will always know the structure of the XML, including data types, and can then generate a more optimized query plan to query the XML.

With that, now consider how to create and apply XML schemas and use them to validate XML.

XML Schemas

As mentioned earlier, XML validation is accomplished through the schemas, or XML Schema Definition language. The XSD language is a specific language used to validate XML documents (and fragments).

An XML schema “describes” the structure of an XML document and various constraints on the data in the document. An XML schema is itself an XML document using the XSD language to describe the XML document structure, and if you are not familiar with the XSD language, it can take some time to get used to.

The great thing is that you don't need to learn a new language because Microsoft has created a nifty little tool to generate the schema for you based on the XML you want to validate. Walk through an example.

Open up your favorite text editor (Notepad works just fine) and type in the following XML:

<Order OrderID="1">
<Item>
<ItemNumber>V001</ItemNumber>
<Quantity>1</Quantity>
<Price>299.99</Price>
</Item>
</Order>

Save the text file as orderxml.xml. With the XML document created, you can use a nifty little tool to create the schema based on the XML document you just created. The tool is called the XML Schema Definition Tool (XSD.exe go figure) and generates XML schema or even Common Language Runtime (CLR) classes from XDR, XML, and XML files. You can find this tool in the following location:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64

Open a command prompt, and navigate the preceding directory. The syntax for creating the schema is simple:

Xsd.exe filename.xml /outputdirectory /parameters

To create the schema, you need to pass the path to the file you previously created, and the path and name of the new XSD schema you want to create. You can optionally supply a number of parameters.

In your command prompt, type the following (assuming you saved your XML file in C:\Temp):

Xsd.exe c:\temp\orderxml.xml /outputdir:c:\temp

When specifying the output directory, you need to specify only the directory, as shown in the preceding code. If you leave off the actual name of the file, it uses the name of the XML file as the name of the XSD file.

Press the Enter key after you have typed it in, and quickly you notice a new file in the same directory as your XML file. Open the orderxml.xsd file to look at its contents. Intricate syntax isn't covered here, but what you see is the validation of your XML, and this is what you create your XML Schema Collection from.

So, copy all the contents of the orderxml.xsd file to the clipboard, and create a new query window in SQL Server Management Studio, pasting in the contents of the clipboard. To create the XML Schema Collection, you simply need to add the CREATE XML SCHEMA COLLECTION statement to the beginning of the schema, as shown here:

CREATE XML SCHEMA COLLECTION OrderInfoSchemaCollection AS
N'<?xml version="1.0" encoding="utf-16"?>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="Order">
<xs:complexType>
<xs:sequence>
<xs:element name="Item" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="ItemNumber" type="xs:string" minOccurs="0" />
<xs:element name="Quantity" type="xs:string" minOccurs="0" />
<xs:element name="Price" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="OrderID" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="NewDataSet" msdata:IsDataSet="true"
msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="Order" />
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>’ ;

Now execute the statement to create the schema collection. A schema is just like any other object in SQL Server, such as a table or stored procedure. It is an actual object. However, even though it is created, it still needs to be applied to the XML column of the ItemInfo table. So, type in the following syntax to alter the ItemData column of the ItemInfo table.

/* Apply it to the table/columns */
ALTER TABLE ItemInfo
ALTER COLUMN ItemData xml (OrderInfoSchemaCollection)
GO

It didn't work, and you received an error. The error you received is not because the schema is invalid but because the two XML fragments inserted earlier can't be validated by the schema. Remember that you built the schema from an XML document, and that document is much different from the XML fragments used earlier.

So, you need to delete the records in the ItemInfo table.

DELETE FROM ItemInfo
GO

Now go back and execute the ALTER statement again, and when applied successfully, try to insert some XML. First, try some bogus data.

/* Fail */
DECLARE @var xml

SET @var =
'<Root>
<Junk1>Some Junk</Junk1>
<Junk2>Some More Junk</Junk2>
<Junk3>Even More Junk</Junk3>
<Junk4>Too Much Junk</Junk4>
</Root>'

INSERT INTO ItemInfo (OrderID, ItemData)
VALUES (1, @var)

The preceding code will fail because the XML does not match, or fails to be validated against the XML schema. The XML is not valid. So try some valid XML.

/* Succeed */

DECLARE @var xml

SET @var =
'<Order OrderID="1">
<Item>
<ItemNumber>V001</ItemNumber>
<Quantity>1</Quantity>
<Price>299.99</Price>
</Item>
</Order>'

INSERT INTO ItemInfo (OrderID, ItemData)
VALUES (1, @var)

SET @var =
'<Order OrderID="2">
<Item>
<ItemNumber>A017</ItemNumber>
<Quantity>1</Quantity>
<Price>2999.99</Price>
</Item>
</Order>'

INSERT INTO ItemInfo (OrderID, ItemData)
VALUES (2, @var)

GO

The preceding statement executes successfully because the XML is successfully validated against the schema and therefore is inserted into the ItemData column.

 
Others
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us