Not all SQL Server data types are created equal. Just look at the XML data type. On the surface, it might seem like your run-of-the-mill type, except, of course, being geared toward XML data; but the ways in which it’s used, how its data is queried, and when and how XML columns should be indexed quickly sets the type apart from the rest of the crowd. And those differences are what matter when working within the extensible world of XML.
The XML data type, in fact, lies at the heart of understanding how to store and query XML data in a SQL Server database. That’s not to suggest that all XML data should be stored with the XML type, but knowing how the type works will help you determine when to use it and how to effectively access its data.
In some cases, you shouldn’t use the XML data type, but instead use large object storage-VARCHAR(MAX), NVARCHAR(MAX),
or VARBINARY(MAX)
. For example, if you simply store your XML documents in the database and retrieve and update those documents as a whole-that is, if you never need to query or modify the individual XML components-you should consider using one of the large object data types. The same goes for XML files that you want to preserve in their original form, such as legal documents. If you need to retain an exact textual copy, use large object storage.
But the rest of the time, you should consider the XML data type. The type ensures that the data is well formed according to ISO standards, and it supports fine-grained queries and modifications to specific elements and attributes within the XML. You can also index an XML column and associate its data with an XML schema collection in order to preserve its content and structure. In addition, the XML data type lets you store data that follows a structure too fluid and complex to fit easily into a relational model.
However, when considering whether to use the XML data type, you should also be aware of its limitations. For instance, an XML column cannot be used as a key in an index, and a data value stored in an XML column cannot exceed 2 GB. You also cannot compare or sort data that uses the XML data type, nor can the data be used in a GROUP BY
clause. For a complete description of the limitations on the XML data type, as well as other details about XML, see the topic “Implementing XML in SQL Server” in SQL Server Books Online.
Creating XML Database Objects
SQL Server lets you assign the XML data type to columns, variables, or parameters and store in any of these objects either XML documents or fragments. The data is considered a document if it has a single top-level element. Otherwise it falls under the category of fragment.
NOTE: You can also assign the XML data type to values returned by a function. However, function return values usually require XML components more complex than what we’ll cover in this article. For this reason, functions will be covered in a later article, after those XML components have been discussed.
When you assign the XML data type to a column, variable, or parameter, you can optionally associate an XML schema collection with the object, thus ensuring that data within that object conforms to schema specifications. In such cases, the object is referred to as typed. An XML object with no associated schema collection is considered untyped.
Creating Untyped XML Objects
An untyped XML object still requires that the data be well formed according to ISO standards; however, the data is not bound to an XML schema collection. You should choose untyped XML (the default) if you don’t have a schema to associate with the data or you don’t want to adhere to the constraints imposed by a schema. For instance, you might have a workable schema but might also need to store nonconforming fragments temporarily in the XML column.
To create an XML object in your database, you simply specify the XML data type as you would any other type. For instance, the following Transact-SQL code creates the Resumes
tables, inserts data into the table, and then retrieves data from that table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
USE AdventureWorks2008R2; GO IF OBJECT_ID('dbo.Resumes') IS NOT NULL DROP TABLE dbo.Resumes; GO CREATE TABLE dbo.Resumes ( CandidateID INT IDENTITY PRIMARY KEY, CandidateResume XML ); INSERT INTO Resumes (CandidateResume) SELECT Resume FROM HumanResources.JobCandidate; SELECT * FROM Resumes; |
Notice that the table includes the CandidateResume
column, which is configured with the XML data type. Because this is an untyped column, you don’t have to specific any other parameters related to the XML. You can, of course, specify the nullability or other column properties, but XML is all you need to include to create an XML column.
NOTE: I created the examples in this article within the AdventureWorks2008R2 database on a local instance of SQL Server 2008 R2.
When I ran the example above, the INSERT
statement added 13 rows from the JobCandidate
table into the Resumes
table. I verified that the new rows had been added by running the SELECT statement, which also returned 13 rows. Each returned row included an XML value in the CandidateResume
column. (Note that, in SQL Server Management Studio, you can click an XML value to open a window that displays the entire XML document or fragment.)
Because the CandidateResume
column is untyped XML, the inserted data did not have to conform to a specific schema collection; however, the data still had to conform to the ISO standards that govern XML.
You can create an XML variable just as easily as you can create a column. In the following example, I declare the @Resume
variable and set its value equal to the XML data retrieved from the Resumes
table for candidate 1:
1 2 3 4 5 6 7 |
DECLARE @resume XML; SELECT @resume = CandidateResume FROM dbo.Resumes WHERE CandidateID = 1; SELECT @resume AS Resume; |
As with the column definition, I simply specified the XML data type when I declared the variable. Again, the XML is untyped, which means that the data does not have to conform to a schema collection. When I ran the SELECT
statement after declaring and setting the variable, it returned only a single value: the XML data I had inserted into the Resumes
table for that candidate.
As mentioned above, you can also assign the XML data type to a parameter. In the next example, I create a stored procedure that’s defined with an XML input parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'dbo.AddResume', 'P' ) IS NOT NULL DROP PROCEDURE dbo.AddResume; GO CREATE PROCEDURE AddResume @resume XML AS INSERT INTO Resumes (CandidateResume) VALUES (@Resume); GO |
Notice that the @Resume
parameter is untyped XML. The stored procedure uses that parameter to insert data into the Resumes
table. After I created the procedure, I declared an XML variable named @Resume2
and assigned XML data to the variable. (I retrieved the data from the JobCandidate
table.) I then called the @Resume2
variable when I executed the stored procedure, as shown in the following example:
1 2 3 4 5 6 7 8 9 |
DECLARE @resume2 XML; SELECT @resume2 = Resume FROM HumanResources.JobCandidate WHERE JobCandidateID = 4; EXEC AddResume @resume2; SELECT * FROM Resumes; |
The stored procedure adds another row to the Resumes
table. The row includes the XML data that I assigned to the @Resume2
variable. When I ran the SELECT
statement this time, it returned 14 rows and showed the new row that was added to the table.
Creating Typed XML Objects
If you have a schema collection available to associate with your XML data, you should consider using that collection. Typed XML has several advantages over untyped. To begin with, it provides another level of validation. Not only must the XML data be well formed (based on ISO standards), but it must also conform to the validation constraints and data type specifications defined by the schema. For example, the type information enforces more precise semantics on the XML values. In addition, storage and queries are better optimized than on an untyped column.
However, before you can associate an XML object with a particularly schema, that schema must be registered in the database in which you’ll be defining the object. Only then can you reference that schema when you create your XML object.
NOTE: Registering schema collections is beyond the scope of this article. You can find details about how to register a collection in SQL Server Books Online, in the topic “CREATE XML SCHEMA COLLECTION (Transact-SQL).”
Once you’ve registered your schema collection, you can define your XML column, variable, or parameter. To do so, you must include the name of the collection in parenthesis after the XML data type name. For example, the following Transact-SQL re-creates the Resumes
table with a typed XML column:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
USE AdventureWorks2008R2; GO IF OBJECT_ID('dbo.Resumes') IS NOT NULL DROP TABLE dbo.Resumes; GO CREATE TABLE dbo.Resumes ( CandidateID INT IDENTITY PRIMARY KEY, CandidateResume XML (HumanResources.HRResumeSchemaCollection) ); INSERT INTO Resumes (CandidateResume) SELECT Resume FROM HumanResources.JobCandidate; SELECT * FROM Resumes; |
Notice that the CandidateResume
column now includes a reference to the schema collection (in parentheses) after the data type name. In this case, I used HumanResources.HRResumeSchemaCollection
, which is included in the AdventureWorks2008R2
database. This is the same collection associated with the Resume column in the JobCandidate
table.
As you can see, the process for creating a typed XML object is fairly straightforward. As long as the schema collection is registered and you get the name right, you should have no problem. Something worth noting, though. By default, SQL Server permits typed XML objects to store data as either an XML document or fragment. You can override the default behavior and specify that the object be limited to only XML documents. To do so, precede the schema collection name with the DOCUMENT
keyword. For example, the following column definition restricts the values to XML documents:
1 |
CandidateResume XML (DOCUMENT HumanResources.HRResumeSchemaCollection) |
Regardless of whether you limit the XML to documents only, the process for creating a typed XML object is the same for columns, variables, and parameters. For instance, in the following example, I declare a typed XML variable and assign an XML value to the variable:
1 2 3 4 5 6 7 |
DECLARE @resume XML (HumanResources.HRResumeSchemaCollection); SELECT @resume = CandidateResume FROM dbo.Resumes WHERE CandidateID = 1; SELECT @resume AS Resume; |
As you can see, this example is nearly identical to my earlier example in which I declared an untyped variable. All I’ve done is add the schema name. Now any XML document or fragment assigned to this variable must adhere to the structure defined in the schema collection. And just like before, if I were to run the SELECT
statement along with the other statements, one row with one value would be returned, and that value would be the XML data.
At this point, you can probably see how easy it is to create a typed object. But just in case, here’s what it would look like if you re-created the AddResume
stored procedure with a typed input parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'dbo.AddResume', 'P' ) IS NOT NULL DROP PROCEDURE dbo.AddResume; GO CREATE PROCEDURE AddResume @resume XML (HumanResources.HRResumeSchemaCollection) AS INSERT INTO Resumes (CandidateResume) VALUES (@Resume); GO DECLARE @resume2 XML; SELECT @resume2 = Resume FROM HumanResources.JobCandidate WHERE JobCandidateID = 4; EXEC AddResume @resume2; SELECT * FROM Resumes; |
Again, there should be no surprises here. After I re-created the table and then re-created the stored procedure, I declared a variable to supply the parameter value to the stored procedure. When I ran the store procedure, it inserted the new row into the Resumes
table, and the SELECT
statement returned 14 rows.
Indexing an XML Column
Data in an XML column is stored as large binary objects (BLOBs). When no XML index is defined on the column, the database engine shreds the BLOBs at runtime during the query evaluation stage. This process can be quite time-consuming if your XML values are relatively large compared to the values being retrieved. In such cases, if you’re planning to generate a lot of queries, you should consider indexing your column.
There are two types of XML indexes that you can create on an XML column:
- Primary: Indexes all tags, paths, and values, along with such details as node type and document order information.
- Secondary: One of three types of indexes (
PATH, VALUE
, andPROPERTY
) that target specific query types used to retrieve data from the XML column.
You must create a primary XML index before you can create any secondary XML indexes. In addition, the table that contains the XML column must be configured with a primary key and a clustered index based on that key. The database engine uses the primary key within the primary XML index to correlate rows.
NOTE: You can also create full-text indexes on XML columns. However, the indexes ignore the XML markup and include only element content.
Creating a Primary XML Index
The primary XML index provides a shredded and persisted representation of the data in an XML column. The query process uses the index for queries that target specific components within the XML data. Queries that retrieve the full XML instance-that is, the entire XML document or fragment-do not use the primary XML index, but instead retrieve the data directly from the XML column.
To create a primary XML index, you must specify the table and XML column where the index will be created, as shown in the following example:
1 2 |
CREATE PRIMARY XML INDEX idx_resumes_xml ON Resumes(CandidateResume); |
After you provide the CREATE PRIMARY XML INDEX
keywords, you must specify a name for the index (in this case, idx_resumes_xml
). Next, add the ON clause
, which includes the name of the table (Resumes
) and the name of the XML column (CandidateResume
).
That’s all there is to creating a primary XML index. Once you’ve done that, you can create one or more secondary XML indexes.
Creating a Secondary XML Index
As mentioned above, SQL Server lets you define three types of secondary XML indexes:
- PATH: Supports queries that use a significant number of path expressions.
- PROPERTY: Supports queries that use path expressions to retrieve multiple values from individual XML instances.
- VALUE: Supports queries that retrieve values without knowing the element or attribute names that contain those values.
You can define any combination of secondary XML indexes on your XML column, as long as a primary XML index has first been defined on that column. For instance, you can define PATH
and VALUE
indexes or PATH
and PROPERTY
indexes or only one index or all three.
NOTE: To fully understand the differences between the three types of secondary XML indexes, you need a basic understanding of how you query specific XML components (as opposed to querying the entire XML instance). In my next article on XML, I’ll cover the various methods used to access the individual components within an XML document or fragment.
Creating a secondary XML index is slightly more complicated than creating a primary one, but not too terribly difficult. As the following example illustrates, you must first specify an index name as well as the target table and column:
1 2 3 4 |
CREATE XML INDEX idx_resumes_xml_value ON Resumes(CandidateResume) USING XML INDEX idx_resumes_xml FOR VALUE; |
The first two lines of this statement should look similar to the statement you use to create a primary XML index. The only thing missing is the PRIMARY
keyword. In the CREATE XML INDEX
clause, you provide a name for the index (in this case, idx_resumes_xml_value
). In the ON
clause, you provide the name of the table (Resumes
) and the name of the XML column (CandidateResume
).
The next clause is USING XML INDEX
. This is where you specify the name of the column’s primary XML index (idx_resumes_xml
). Next, you define the FOR
clause, which specifies the type of secondary index you want to create. In the example above, I created a VALUE
secondary index.
That’s all there is to creating a secondary index. If you want to create a PROPERTY
or PATH
index on the same column, you simply change the index name and the value in the FOR
clause.
You can verify that the primary and secondary XML indexes have been created by using the sys.xml_indexes
catalog view to retrieve a list of indexes. For example, I used the following SELECT
statement to retrieve those indexes whose names contain ‘resume’:
1 2 3 |
SELECT name AS IndexName FROM sys.xml_indexes WHERE name LIKE '%resumes%'; |
The statement should return the following results:
1 2 3 |
IndexName idx_resumes_xml idx_resumes_xml_value |
You can remove these indexes from the database by using a DROP INDEX
statement, as shown in the following example:
1 |
DROP INDEX idx_resumes_xml ON Resumes; |
This statement drops the primary XML index from the XML column. When you drop a primary index, the secondary indexes are automatically removed. As a result, if I were to re-query the sys.xml_indexes
catalog view, I would not see any of the XML indexes I created on the Resumes
table.
Moving Forward with XML
As the examples have demonstrated, you can implement XML database objects and create XML indexes on columns with relative ease. And inserting data into those columns is little different from inserting data into other column types, assuming the data conforms to the type’s structure. The ingredient that’s missing from this mix is how you work with that data once you get it in there.
As it turns out, the XML data type supports several methods for querying and manipulating XML data. Unfortunately, that’s a discussion that must wait till my next article, in which I’ll cover each of these methods and show you how to use them to work with XML data. Until then, you should now have a basic overview of the XML data type and how to get started using it when creating columns, variables, and parameters. From this foundation, you’ll be ready to jump into the world of the XML methods in no time at all.
Load comments