Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

346


Part III: Advanced T-SQL Data Types and Querying Techniques


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 diffi cult to validate and even more diffi cult 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 benefi ts, 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 Defi nition language. The XSD language is a specifi c 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.
c14.indd 346c14.indd 346 7/30/2012 4:49:00 PM7/30/2012 4:49:00 PM
http://www.it-ebooks.info

Free download pdf