<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sqlserver and XML</title>
	<atom:link href="http://sqlserverandxml.com/feed" rel="self" type="application/rss+xml" />
	<link>http://sqlserverandxml.com</link>
	<description>www.sqlserverandxml.com</description>
	<lastBuildDate>Wed, 05 Jan 2011 07:47:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Find row count of one or more tables</title>
		<link>http://sqlserverandxml.com/2008/01/find-row-count-of-one-or-more-tables.html</link>
		<comments>http://sqlserverandxml.com/2008/01/find-row-count-of-one-or-more-tables.html#comments</comments>
		<pubDate>Sat, 05 Jan 2008 05:38:27 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=29</guid>
		<description><![CDATA[Find row count of one or more tables The following code can be used to retrieve the rowcount of each tables in the database. Let us create a function (TABLE VALUED) which returns the row count of all the tables. CREATE FUNCTION dbo.GetRowCount() RETURNS TABLE RETURN SELECT st.Name, SUM( CASE WHEN (p.index_id < 2) AND [...]]]></description>
			<content:encoded><![CDATA[<p>Find row count of one or more tables</p>
<p>The following code can be used to retrieve the rowcount of each tables in the database. Let us create a function (TABLE VALUED) which returns the row count of all the tables.</p>
<p>CREATE FUNCTION dbo.GetRowCount()</p>
<p>RETURNS TABLE</p>
<p>RETURN</p>
<p>    SELECT</p>
<p>    st.Name,</p>
<p>    SUM( </p>
<p>        CASE</p>
<p>            WHEN (p.index_id < 2) AND (a.type = 1) THEN p.rows </p>
<p>            ELSE 0 </p>
<p>        END</p>
<p>       ) AS Rows</p>
<p>    FROM sys.partitions p</p>
<p>    INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id</p>
<p>    INNER JOIN sys.tables st ON st.object_id = p.Object_ID</p>
<p>    GROUP BY st.name </p>
<p> Execute the function as follows:</p>
<p>&#8211; list all tables and the number of rows</p>
<p>SELECT * FROM dbo.GetRowCount()</p>
<p>&#8211; find the rowcount of a single table</p>
<p>SELECT * FROM dbo.GetRowCount()</p>
<p>WHERE Name = &#8216;Invoices&#8217;</p>
<p>&#8211; find the rowcount of more than one table</p>
<p>SELECT * FROM dbo.GetRowCount()</p>
<p>WHERE Name IN (&#8216;Invoices&#8217;,'Orders&#8217;)</p>
<p> If you have organized your tables into multiple schemas then you might need a different version of the function. Here is a modified version which retrieves the schema information too.</p>
<p>CREATE FUNCTION dbo.GetRowCount()</p>
<p>RETURNS TABLE</p>
<p>RETURN</p>
<p>    SELECT</p>
<p>    sch.name AS SchemaName,</p>
<p>    st.Name AS TableName,</p>
<p>    sch.name + &#8216;.&#8217; + st.name AS QualifiedName,</p>
<p>    SUM( </p>
<p>        CASE</p>
<p>            WHEN (p.index_id < 2) AND (a.type = 1) THEN p.rows </p>
<p>            ELSE 0 </p>
<p>        END</p>
<p>       ) AS Rows</p>
<p>    FROM sys.partitions p</p>
<p>    INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id</p>
<p>    INNER JOIN sys.tables st ON st.object_id = p.Object_ID</p>
<p>    INNER JOIN sys.schemas sch ON sch.schema_id = st.schema_id</p>
<p>    GROUP BY st.name, sch.name</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/find-row-count-of-one-or-more-tables.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Online DTD Validators</title>
		<link>http://sqlserverandxml.com/2008/01/online-dtd-validators.html</link>
		<comments>http://sqlserverandxml.com/2008/01/online-dtd-validators.html#comments</comments>
		<pubDate>Sat, 05 Jan 2008 05:35:35 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=18</guid>
		<description><![CDATA[I had been creating some DTDs for a book that I am currently writing. The book is not about DTD. The title of the book is &#8220;XSD For SQL Server 2005 Developers&#8221; and it aims at helping SQL Server 2005 developers to make effective use of XML SCHEMA COLLECTIONS and TYPED XML. Though the book [...]]]></description>
			<content:encoded><![CDATA[<p>I had been creating some DTDs for a book that I am currently  writing. The book is not about DTD. The title of the book is &#8220;XSD For  SQL Server 2005 Developers&#8221; and it aims at helping SQL Server 2005  developers to make effective use of XML SCHEMA COLLECTIONS and TYPED  XML. Though the book is on XSD, I have a few paragraphs that talk about  DTDs. I had been creating some code samples to demonstrate in the book  and wanted to have a quick way to validate the DTDs that I created.</p>
<p>After  searching for a while, I came up with over a dozen web pages which  validates an XML document against a DTD. Unfortunately, most of them  were taking a URL as input and validates the doucument pointed by the  URL. My case was different. I wanted to have a page that validates  direct input text. I found a few validators that do this.</p>
<p><a title="http://www.stg.brown.edu/service/xmlvalid/" href="http://www.stg.brown.edu/service/xmlvalid/">http://www.stg.brown.edu/service/xmlvalid/</a></p>
<p><a title="http://www.xml.com/pub/a/tools/ruwf/check.html" href="http://www.xml.com/pub/a/tools/ruwf/check.html">http://www.xml.com/pub/a/tools/ruwf/check.html</a></p>
<p><a title="http://validator.w3.org/#validate_by_input" href="http://validator.w3.org/#validate_by_input">http://validator.w3.org/#validate_by_input</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/online-dtd-validators.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>VARCHAR/NVARCHAR (N) vs (MAX)</title>
		<link>http://sqlserverandxml.com/2008/01/varcharnvarchar-n-vs-max.html</link>
		<comments>http://sqlserverandxml.com/2008/01/varcharnvarchar-n-vs-max.html#comments</comments>
		<pubDate>Sat, 05 Jan 2008 05:11:07 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=14</guid>
		<description><![CDATA[Prior to SQL Server 2005, it was hard dealing with large string values. NVARCHAR and VARCHAR data types had a limitation of 8000 bytes (VARCHAR(8000) and NVARCHAR(4000)). To store large values, most people used TEXT columns and others broke the value into multiple rows. Dealing with TEXT columns  was not easy. You cannot declare a [...]]]></description>
			<content:encoded><![CDATA[<p>Prior to SQL Server 2005, it was hard dealing with large  string values. NVARCHAR and VARCHAR data types had a limitation of 8000  bytes (VARCHAR(8000) and NVARCHAR(4000)). To store large values, most  people used TEXT columns and others broke the value into multiple rows.  Dealing with TEXT columns  was not easy. You cannot declare a variable  of type TEXT. So reading information from a TEXT column was hard.  Further, most of the string functions that we use regularly, do not  support TEXT data type.</p>
<p>Life became easier with SQL Server 2005,  when it introduced VARCHAR(MAX) and NVARCHAR(MAX) data types.  VARCHAR(MAX) and NVARCHAR(MAX) can now store values up to 2 GB.</p>
<p>What does that mean? Can I declare a variable or column as VARCHAR(9000)?</p>
<p>The  answer is NO. You can either declare a variable as VARCHAR(8000) or  VARCHAR(MAX). But none in between. This leads to the question: &#8220;How do  we restrict the length of the field then&#8221;?  This can be achieved by  adding a CHECK constraint.</p>
<div>
<p>&#8211; let us create a table</p>
<p>CREATE TABLE Customers (</p>
<p>CustomerID INT,</p>
<p>&#8211; Other fields,</p>
<p>Notes VARCHAR(MAX))</p>
<p>GO</p>
<p>&#8211; let us add the check constraint</p>
<p>ALTER TABLE Customers</p>
<p>ADD CONSTRAINT CustomerNoteLength</p>
<p>CHECK (DATALENGTH(Notes) &lt;= 9000)</p>
<p>GO</p>
<p>&#8211; expect an error</p>
<p>INSERT INTO Customers( CustomerID, Notes )</p>
<p>SELECT 1, REPLICATE( &#8216;a&#8217;, 9001 )</p>
<p>/*</p>
<p>TOSHIBA-USER\SQL2005(TOSHIBA-USER\Jacob Sebastian): (1 row(s) affected)</p>
<p><span style="color: #ff0000;">!!!!!! NO ERROR !!!!!!!!</span></p>
<p>*/</p>
</div>
<p>Well,  we expected an error. But the insert statement did not produce an  error. Why? Did SQL Server make a mistake? Why did it accept a value  which is longer than 9000 characters?</p>
<p>Let us check the length of the data we just stored:</p>
<div>
<p>SELECT LEN(Notes) FROM Customers</p>
<p>/*</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>8000</p>
<p>*/</p>
</div>
<p>Oh&#8230;NO! Am I getting crazy?</p>
<p>The  column has a restriction of 9000 characters. Our insert statement with  9001 characters successfully ran. The column has 8000 characters stored  in it. All the statements conflict with each other.</p>
<p>Here is what  happened. The REPLICATE function was expected to produce 9001  characters. But it returned only 8000 characters. All string functions  that takes VARCHAR data type assumes the variable to be VARCHAR(8000)  unless one of the parameters is VARCHAR(MAX). (in case of NVARCHAR, it  is 4000). So, here is how we could generate a string of 9001 characters.</p>
<div>
<p>INSERT INTO Customers( CustomerID, Notes )</p>
<p>SELECT 3, REPLICATE( CAST(&#8216;a&#8217; AS VARCHAR(MAX)), 9000 )</p>
<p>SELECT LEN(Notes) FROM Customers WHERE CustomerID = 3</p>
<p>/*</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>9000</p>
<p>*/</p>
</div>
<p>Let us see if the CHECK constraint we created works or not.</p>
<div>
<p>INSERT INTO Customers( CustomerID, Notes )</p>
<p>SELECT 1, REPLICATE( CAST(&#8216;a&#8217; AS VARCHAR(MAX)), 9001 )</p>
<p>/*</p>
<p>TOSHIBA-USER\SQL2005(TOSHIBA-USER\Jacob Sebastian): Msg 547, Level 16, State 0, Line 1</p>
<p><span style="color: #ff0000;">The  INSERT statement conflicted with the CHECK constraint  &#8220;CustomerNoteLength&#8221;. The conflict occurred in database &#8220;master&#8221;, table  &#8220;dbo.Customers&#8221;, column &#8216;Notes&#8217;.</span></p>
<p>TOSHIBA-USER\SQL2005(TOSHIBA-USER\Jacob Sebastian):</p>
<p>The statement has been terminated.</p>
<p>*/</p>
</div>
<p><span style="font-size: small;">Yes, it is working!</span></p>
<h2><span style="font-size: small;"><strong>Storage of NVARCHAR(MAX)/VARCHAR (MAX) values</strong></span></h2>
<p>VARCHAR(MAX), NVARCHAR(MAX), VARBINARY(MAX)  and XML data types are called <em>Large Value Types</em>. SQL Server stores each record in a storage location called a &#8216;data row&#8217;. The size of a row is 8060 bytes. When you store a <em>Large Value Type</em> to a column, if the total size of the row (including your <em>Large Value Type)</em> value  is less than 8060 bytes, the value is stored &#8220;in row&#8221;. That means the  value is stored in the same data row where other values of the same  record are stored. If the <em>Large Value Type</em> is larger, it is  stored &#8220;out of row&#8221; which means that the data is stored in another  location and a pointer to the stored location will be added in the data  row. Reading or writing values &#8220;out of the row&#8221; will need some  additional processing and hence is not as fast as &#8220;in row&#8221; operations.</p>
<p><em>VARCHAR(MAX)/NVARCHAR(MAX)</em> columns  are internally handled as TEXT columns. Though we can work with them as  regular strings, under the covers there is some TEXT processing  happening. Another important point to note about  VARCHAR(MAX)/NVARCHAR(MAX) columns is that, you cannot create an index  on those columns.</p>
<h3>Additional reading on VARCHAR(MAX)/NVARCHAR(MAX)</h3>
<p><a title="http://msdn2.microsoft.com/en-us/library/ms189087.aspx" href="http://msdn2.microsoft.com/en-us/library/ms189087.aspx">http://msdn2.microsoft.com/en-us/library/ms189087.aspx</a></p>
<p><a title="http://www.informit.com/articles/article.aspx?p=327394&amp;seqNum=6&amp;rl=1" href="http://www.informit.com/articles/article.aspx?p=327394&amp;seqNum=6&amp;rl=1">http://www.informit.com/articles/article.aspx?p=327394&amp;seqNum=6&amp;rl=1</a></p>
<p><a title="http://blogs.conchango.com/christianwade/archive/2004/11/06/199.aspx" href="http://blogs.conchango.com/christianwade/archive/2004/11/06/199.aspx">http://blogs.conchango.com/christianwade/archive/2004/11/06/199.aspx</a></p>
<p><a title="http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx" href="http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx">http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx</a></p>
<p><a title="http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx" href="http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx">http://www.fotia.co.uk/fotia/DY.13.VarCharMax.aspx</a></p>
<p><a title="http://www.sql-server-helper.com/faq/sql-server-2005-varchar-max-p01.aspx" href="http://www.sql-server-helper.com/faq/sql-server-2005-varchar-max-p01.aspx">http://www.sql-server-helper.com/faq/sql-server-2005-varchar-max-p01.aspx</a></p>
<p><a title="http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1098157,00.html" href="http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1098157,00.html">http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1098157,00.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/varcharnvarchar-n-vs-max.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Application Roles in SQL Server</title>
		<link>http://sqlserverandxml.com/2008/01/application-roles-in-sql-server.html</link>
		<comments>http://sqlserverandxml.com/2008/01/application-roles-in-sql-server.html#comments</comments>
		<pubDate>Sat, 05 Jan 2008 05:08:13 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=12</guid>
		<description><![CDATA[Application roles are set of permissions that you can group together for a specific application. When a user connects to the database through the specific application, he or she will be able to perform the actions permitted under the specific application role. I have not used application roles in any of my applications yet. I [...]]]></description>
			<content:encoded><![CDATA[<p>Application roles are set of permissions that you can group  together for a specific application. When a user connects to the  database through the specific application, he or she will be able to  perform the actions permitted under the specific application role.</p>
<p>I  have not used application roles in any of my applications yet. I am not  sure if I will ever use it in any of my applications. But a little bit  of reading on application roles will be good. I recently found a good  introductory article about application roles at <a href="http://www.sqlservercentral.com/">www.sqlservercentral.com</a>. You can find the article <a href="http://www.sqlservercentral.com/articles/Security/sqlserversecurityprosandconsofapplicationroles/1116/">here</a>.</p>
<h3>How to find the application role that is currently active?</h3>
<p>I recently found this question in one of the MSDN forums and did some search to find an ansser. I <span style="color: #000000;">found  that when an application role is activated, USER_NAME() will return the  name of the application role. Here is a piece of code which  demonstrates this. Part of this example is taken from this MSDN <a href="http://web.archive.org/web/20080312163822/http://msdn2.microsoft.com/en-us/library/ms188908.aspx">article</a>.</span></p>
<p>&#8211; create an app role</p>
<div>
<p>EXEC sp_addapprole &#8216;JacobsApplication&#8217;, &#8216;jacob$$&#8217;</p>
<p>GO</p>
<p>DECLARE @cookie varbinary(8000);</p>
<p>EXEC sp_setapprole &#8216;JacobsApplication&#8217;, &#8216;jacob$$&#8217;</p>
<p>, @fCreateCookie = true, @cookie = @cookie OUTPUT;</p>
<p>&#8211; The application role is now active.</p>
<p><strong>SELECT USER_NAME();</strong></p>
<p>&#8211; This will return the name of the application role, JacobsApplication.</p>
<p>EXEC sp_unsetapprole @cookie;</p>
<p>&#8211; The application role is no longer active.</p>
<p>&#8211; The original context has now been restored.</p>
<p>GO</p>
<p>SELECT USER_NAME();</p>
<p>&#8211; This will return the name of the original user.</p>
<p>GO</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/application-roles-in-sql-server.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to find all stored procedures used by Report Server?</title>
		<link>http://sqlserverandxml.com/2008/01/how-to-find-all-stored-procedures-used-by-report-server.html</link>
		<comments>http://sqlserverandxml.com/2008/01/how-to-find-all-stored-procedures-used-by-report-server.html#comments</comments>
		<pubDate>Sat, 05 Jan 2008 05:06:38 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=8</guid>
		<description><![CDATA[Report definitions [RDL files] are stored in the &#8220;catalog&#8221; table of ReportServer database. This table has a field &#8220;content&#8221; which stores the report definition as an image/text value. The following query will extract a list of all reports and the stored procedures used by them, by querying the catalog table of report server. ;WITH XMLNAMESPACES [...]]]></description>
			<content:encoded><![CDATA[<p>Report definitions [RDL files] are stored in the &#8220;catalog&#8221;  table of ReportServer database. This table has a field &#8220;content&#8221; which  stores the report definition as an image/text value.</p>
<p>The  following query will extract a list of all reports and the stored  procedures used by them, by querying the catalog table of report server.</p>
<p>;WITH XMLNAMESPACES (</p>
<div>DEFAULT<br />
&#8216;<a href="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition%27">http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition&#8217;</a>,<br />
&#8216;<a href="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner%27">http://schemas.microsoft.com/SQLServer/reporting/reportdesigner&#8217;</a> AS rd</div>
<p>)<br />
SELECT</p>
<div>name,<br />
x.value(&#8216;CommandType[1]&#8216;, &#8216;VARCHAR(50)&#8217;) AS CommandType,<br />
x.value(&#8216;CommandText[1]&#8216;,&#8217;VARCHAR(50)&#8217;) AS CommandText</div>
<p>FROM (</p>
<div>select name,<br />
CAST(CAST(content AS VARBINARY(MAX)) AS XML) AS reportXML<br />
from ReportServer.dbo.Catalog</div>
<p>) a<br />
CROSS APPLY reportXML.nodes(&#8216;/Report/DataSets/DataSet/Query&#8217;) r(x)<br />
WHERE x.value(&#8216;CommandType[1]&#8216;, &#8216;VARCHAR(50)&#8217;) = &#8216;StoredProcedure&#8217;</p>
<p>Note  that I have applied a filter for &#8216;StoredProcedure&#8217;. If you want to get  all the information (including queries etc) you should remove this  filter. you should also increase the size of the field to VARCHAR(MAX)  to make sure that the text is not truncated.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/how-to-find-all-stored-procedures-used-by-report-server.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Insert an XML variable into another</title>
		<link>http://sqlserverandxml.com/2008/01/insert-xml-variable-to-another.html</link>
		<comments>http://sqlserverandxml.com/2008/01/insert-xml-variable-to-another.html#comments</comments>
		<pubDate>Fri, 04 Jan 2008 22:39:33 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=1</guid>
		<description><![CDATA[If you are using SQL Server 2008 November CTP, you can insert one XML variable into anther using the XQuery insert operator. Here is an example: &#8211; declare an XML variable DECLARE @x XML SET @x = &#8216;&#60;Root&#62;&#60;/Root&#62;&#8217; &#8211; create another XML variable DECLARE @t XML SELECT @t = (SELECT TOP 3 name FROM sys.tables [...]]]></description>
			<content:encoded><![CDATA[<p>If you are using SQL Server 2008 November CTP, you can insert one XML  variable into anther using the XQuery insert operator. Here is an  example:</p>
<p>&#8211; declare an XML variable</p>
<p>DECLARE @x XML</p>
<p>SET @x = &#8216;&lt;Root&gt;&lt;/Root&gt;&#8217;</p>
<p>&#8211; create another XML variable</p>
<p>DECLARE @t XML</p>
<p>SELECT @t = (SELECT TOP 3 name FROM sys.tables FOR XML AUTO)</p>
<p>&#8211; insert the second XML variable to the first one</p>
<p>SET @x.modify( &#8216;</p>
<p>insert sql:variable(&#8220;@t&#8221;)</p>
<p>as last into (/Root)[1] &#8216; )</p>
<p>&#8211; Let us check the results</p>
<p>SELECT @x</p>
<p>/*</p>
<p>&lt;Root&gt;</p>
<p>&lt;sys.tables name=&#8221;spt_fallback_db&#8221;/&gt;</p>
<p>&lt;sys.tables name=&#8221;spt_fallback_dev&#8221;/&gt;</p>
<p>&lt;sys.tables name=&#8221;spt_fallback_usg&#8221; /&gt;</p>
<p>&lt;/Root&gt;</p>
<p>*/</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2008/01/insert-xml-variable-to-another.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>FOR XML EXPLICIT – Part 3</title>
		<link>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-3.html</link>
		<comments>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-3.html#comments</comments>
		<pubDate>Wed, 05 Dec 2007 07:14:44 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=75</guid>
		<description><![CDATA[Part 1 Part 2 Having fixed the problem with the sort order, let us go ahead with the rest of the code. Let us add Addresses under the AddressCollection node and come up with the final version of the code. We need to add a new level, Tag 4. Note that I used AgentID * [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.sqlserverandxml.com/2007/12/for-xml-explicit-part-1.html">Part 1</a></p>
<p><a href="http://www.sqlserverandxml.com/2007/12/for-xml-explicit-part-2.html">Part 2</a></p>
<p>Having fixed the problem with the sort order, let us go ahead with the rest of the code. Let us add <em>Addresses</em> under the <em>AddressCollection</em> node and come up with the final version of the code. We need to add a new level, <em>Tag 4</em>. Note that I used <em>AgentID * 102</em> to make sure that this record will come right below the <em>AddressCollection</em> row of each <em>Agent</em>.</p>
<div>
<p>SELECT Tag, Parent,</p>
<p>[Agents!1!],</p>
<p>[Agent!2!AgentID],</p>
<p>[Agent!2!Fname!Element],</p>
<p>[Agent!2!SSN!Element],</p>
<p>[AddressCollection!3!Element],</p>
<p>[Address!4!AddressType!Element],</p>
<p>[Address!4!Address1!Element],</p>
<p>[Address!4!Address2!Element],</p>
<p>[Address!4!City!Element]</p>
<p>FROM (</p>
<p>SELECT</p>
<p>1 AS Tag,</p>
<p>NULL AS Parent,</p>
<p>0 AS Sort,</p>
<p>NULL AS &#8216;Agents!1!&#8217;,</p>
<p>NULL AS &#8216;Agent!2!AgentID&#8217;,</p>
<p>NULL AS &#8216;Agent!2!Fname!Element&#8217;,</p>
<p>NULL AS &#8216;Agent!2!SSN!Element&#8217;,</p>
<p>NULL AS &#8216;AddressCollection!3!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!AddressType!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!Address1!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!Address2!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!City!Element&#8217;</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>2 AS Tag,</p>
<p>1 AS Parent,</p>
<p>AgentID * 100,</p>
<p>NULL, AgentID, Fname, SSN,</p>
<p>NULL,NULL, NULL, NULL, NULL</p>
<p>FROM @Agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>3 AS Tag,</p>
<p>2 AS Parent,</p>
<p>AgentID * 100 + 1,</p>
<p>NULL,NULL,NULL, NULL,</p>
<p>NULL, NULL, NULL, NULL, NULL</p>
<p>FROM @Agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>4 AS Tag,</p>
<p>3 AS Parent,</p>
<p>AgentID * 100 + 2,</p>
<p>NULL,NULL,NULL,NULL,NULL,</p>
<p>AddressType, Address1, Address2, City</p>
<p>FROM @Address</p>
<p>) A</p>
<p>ORDER BY Sort</p>
<p>FOR XML EXPLICIT</p>
</div>
<p>Here is the complete listing of the code.</p>
<div>
<p>/*</p>
<p>Borrowed from Kent&#8217;s code</p>
<p>*/</p>
<p>declare @agent table</p>
<p>(</p>
<p>AgentID int,</p>
<p>Fname varchar(5),</p>
<p>SSN varchar(11)</p>
<p>)</p>
<p>insert into @agent</p>
<p>select 1, &#8216;Vimal&#8217;, &#8217;123-23-4521&#8242; union all</p>
<p>select 2, &#8216;Jacob&#8217;, &#8217;321-52-4562&#8242; union all</p>
<p>select 3, &#8216;Tom&#8217;, &#8217;252-52-4563&#8242;</p>
<p>declare @address table</p>
<p>(</p>
<p>AddressID int,</p>
<p>AddressType varchar(12),</p>
<p>Address1 varchar(20),</p>
<p>Address2 varchar(20),</p>
<p>City varchar(25),</p>
<p>AgentID int</p>
<p>)</p>
<p>insert into @address</p>
<p>select 1, &#8216;Home&#8217;, &#8216;abc&#8217;, &#8216;xyz road&#8217;, &#8216;RJ&#8217;, 1 union all</p>
<p>select 2, &#8216;Office&#8217;, &#8216;temp&#8217;, &#8216;ppp road&#8217;, &#8216;RJ&#8217;, 1 union all</p>
<p>select 3, &#8216;Home&#8217;, &#8216;xxx&#8217;, &#8216;aaa road&#8217;, &#8216;NY&#8217;, 2 union all</p>
<p>select 4, &#8216;Office&#8217;, &#8216;ccc&#8217;, &#8216;oli Com&#8217;, &#8216;CL&#8217;, 2 union all</p>
<p>select 5, &#8216;Temp&#8217;, &#8216;eee&#8217;, &#8216;olkiu road&#8217;, &#8216;CL&#8217;, 2 union all</p>
<p>select 6, &#8216;Home&#8217;, &#8216;ttt&#8217;, &#8216;loik road&#8217;, &#8216;NY&#8217;, 3</p>
<p>/*</p>
<p>End Borrow</p>
<p>*/</p>
<p>SELECT Tag, Parent,</p>
<p>[Agents!1!],</p>
<p>[Agent!2!AgentID],</p>
<p>[Agent!2!Fname!Element],</p>
<p>[Agent!2!SSN!Element],</p>
<p>[AddressCollection!3!Element],</p>
<p>[Address!4!AddressType!Element],</p>
<p>[Address!4!Address1!Element],</p>
<p>[Address!4!Address2!Element],</p>
<p>[Address!4!City!Element]</p>
<p>FROM (</p>
<p>SELECT</p>
<p>1 AS Tag,</p>
<p>NULL AS Parent,</p>
<p>0 AS Sort,</p>
<p>NULL AS &#8216;Agents!1!&#8217;,</p>
<p>NULL AS &#8216;Agent!2!AgentID&#8217;,</p>
<p>NULL AS &#8216;Agent!2!Fname!Element&#8217;,</p>
<p>NULL AS &#8216;Agent!2!SSN!Element&#8217;,</p>
<p>NULL AS &#8216;AddressCollection!3!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!AddressType!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!Address1!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!Address2!Element&#8217;,</p>
<p>NULL AS &#8216;Address!4!City!Element&#8217;</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>2 AS Tag,</p>
<p>1 AS Parent,</p>
<p>AgentID * 100,</p>
<p>NULL, AgentID, Fname, SSN,</p>
<p>NULL,NULL, NULL, NULL, NULL</p>
<p>FROM @Agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>3 AS Tag,</p>
<p>2 AS Parent,</p>
<p>AgentID * 100 + 1,</p>
<p>NULL,NULL,NULL, NULL,</p>
<p>NULL, NULL, NULL, NULL, NULL</p>
<p>FROM @Agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>4 AS Tag,</p>
<p>3 AS Parent,</p>
<p>AgentID * 100 + 2,</p>
<p>NULL,NULL,NULL,NULL,NULL,</p>
<p>AddressType, Address1, Address2, City</p>
<p>FROM @Address</p>
<p>) A</p>
<p>ORDER BY Sort</p>
<p>FOR XML EXPLICIT</p>
<p>/*</p>
<p>OUTPUT:</p>
<p>&lt;Agents&gt;</p>
<p>&lt;Agent AgentID=&#8221;1&#8243;&gt;</p>
<p>&lt;Fname&gt;Vimal&lt;/Fname&gt;</p>
<p>&lt;SSN&gt;123-23-4521&lt;/SSN&gt;</p>
<p>&lt;AddressCollection&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Home&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;abc&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;xyz road&lt;/Address2&gt;</p>
<p>&lt;City&gt;RJ&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Office&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;temp&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;ppp road&lt;/Address2&gt;</p>
<p>&lt;City&gt;RJ&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;/AddressCollection&gt;</p>
<p>&lt;/Agent&gt;</p>
<p>&lt;Agent AgentID=&#8221;2&#8243;&gt;</p>
<p>&lt;Fname&gt;Jacob&lt;/Fname&gt;</p>
<p>&lt;SSN&gt;321-52-4562&lt;/SSN&gt;</p>
<p>&lt;AddressCollection&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Home&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;xxx&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;aaa road&lt;/Address2&gt;</p>
<p>&lt;City&gt;NY&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Office&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;ccc&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;oli Com&lt;/Address2&gt;</p>
<p>&lt;City&gt;CL&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Temp&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;eee&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;olkiu road&lt;/Address2&gt;</p>
<p>&lt;City&gt;CL&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;/AddressCollection&gt;</p>
<p>&lt;/Agent&gt;</p>
<p>&lt;Agent AgentID=&#8221;3&#8243;&gt;</p>
<p>&lt;Fname&gt;Tom&lt;/Fname&gt;</p>
<p>&lt;SSN&gt;252-52-4563&lt;/SSN&gt;</p>
<p>&lt;AddressCollection&gt;</p>
<p>&lt;Address&gt;</p>
<p>&lt;AddressType&gt;Home&lt;/AddressType&gt;</p>
<p>&lt;Address1&gt;ttt&lt;/Address1&gt;</p>
<p>&lt;Address2&gt;loik road&lt;/Address2&gt;</p>
<p>&lt;City&gt;NY&lt;/City&gt;</p>
<p>&lt;/Address&gt;</p>
<p>&lt;/AddressCollection&gt;</p>
<p>&lt;/Agent&gt;</p>
<p>&lt;/Agents&gt;</p>
<p>*/</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-3.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Workshop XII &#8211; Parsing a delimited string</title>
		<link>http://sqlserverandxml.com/2007/12/xml-workshop-xii-parsing-a-delimited-string.html</link>
		<comments>http://sqlserverandxml.com/2007/12/xml-workshop-xii-parsing-a-delimited-string.html#comments</comments>
		<pubDate>Wed, 05 Dec 2007 06:34:03 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=62</guid>
		<description><![CDATA[I am pretty sure that parsing a delimited string is one of the basic string operation that all of us do. Any programmer must have used it at least once in his or her programming career. Based on the programming language he or she uses, there might be different methods or ways to do this. [...]]]></description>
			<content:encoded><![CDATA[<p>I am pretty sure that parsing a delimited string is one of the  basic string operation that all of us do. Any programmer must have used  it at least once in his or her programming career. Based on the  programming language he or she uses, there might be different methods or  ways to do this.</p>
<p>Let us look a second at TSQL. There are  many ways to parse a delimited string. There are many ways widely used  and discussed and you can find several articles on Internet which  explains those methods. The most common approach that I have seen is  using a PATINDEX in a WHILE loop. I have recently written an article at <a href="http://www.sqlservercentral.com/articles/XML/61618/">SQLServerCentral</a> which shows yet another way of parsing a delimited string. The approach I presented at <a href="http://www.sqlservercentral.com/articles/XML/61618/">SQLServerCentral</a> uses an XML based approach for parsing the string.</p>
<p>You can find the article <a href="http://www.sqlservercentral.com/articles/XML/61618/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2007/12/xml-workshop-xii-parsing-a-delimited-string.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Passing a Data Table to a SQL Server 2005 Stored Procedure</title>
		<link>http://sqlserverandxml.com/2007/12/passing-a-data-table-to-a-sql-server-2005-stored-procedure.html</link>
		<comments>http://sqlserverandxml.com/2007/12/passing-a-data-table-to-a-sql-server-2005-stored-procedure.html#comments</comments>
		<pubDate>Wed, 05 Dec 2007 06:30:02 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=60</guid>
		<description><![CDATA[One of the readers at SQLServerCentral forum asked me about passing a DataTable to a stored procedure. He wanted to get an XML representation of the DataTable and then pass it to the stored procedure. I tried to answer the question and came up with a complete sample code, which I think would be useful [...]]]></description>
			<content:encoded><![CDATA[<p>One of the readers at SQLServerCentral forum asked me about  passing a DataTable to a stored procedure. He wanted to get an XML  representation of the DataTable and then pass it to the stored  procedure. I tried to answer the question and came up with a complete  sample code, which I think would be useful to others too.</p>
<p>Here is what the sample code does.</p>
<ol>
<li>Opens a connection to a database</li>
<li>Executes a stored procedure which returns a DataSet with 2 DataTables</li>
<li>Get the XML out of the first table</li>
<li>Pass the XML to a stored procedure</li>
</ol>
<p>Before  we have a look at the code, we need to create a database and create a  couple of tables. Then we need to populate the tables with some sample  data. Here is the code.</p>
<div>
<p>&#8211; Create a Database</p>
<p>CREATE DATABASE DataTableTest</p>
<p>USE DataTableTest</p>
<p>GO</p>
<p>&#8211;Create the sample tables</p>
<p>CREATE TABLE Employees (</p>
<p>EmployeeID BIGINT IDENTITY(1,1),</p>
<p>EmployeeName VARCHAR(50),</p>
<p>DepartmentID BIGINT )</p>
<p>CREATE TABLE Departments (</p>
<p>DepartmentID BIGINT IDENTITY(1,1),</p>
<p>DepartmentName VARCHAR(50) )</p>
<p>GO</p>
<p>&#8211; Populate the Sample Tables</p>
<p>INSERT INTO Departments ( DepartmentName)</p>
<p>SELECT &#8216;Software&#8217;</p>
<p>INSERT INTO Employees (EmployeeName, DepartmentID )</p>
<p>SELECT &#8216;Jacob&#8217;, 1</p>
<p>GO</p>
</div>
<p>Now let us create a stored procedure which returns two result sets.</p>
<div>
<p>CREATE PROCEDURE GetEmployeeInfo</p>
<p>AS</p>
<p>SET NOCOUNT ON</p>
<p>SELECT EmployeeName, DepartmentID</p>
<p>FROM Employees</p>
<p>WHERE EmployeeID = 1</p>
<p>SELECT DepartmentName FROM Departments</p>
<p>WHERE DepartmentID = 1</p>
<p>GO</p>
</div>
<p>Let  us create the next stored procedure which accepts an XML parameter.  This procedure will insert the data from the XML parameter, into the  Employee Table.</p>
<div>
<p>CREATE PROCEDURE ProcessXml</p>
<p>(</p>
<p>@data XML</p>
<p>)</p>
<p>AS</p>
<p>INSERT INTO Employees(EmployeeName, DepartmentID)</p>
<p>SELECT</p>
<p>x.d.value(&#8216;EmployeeName[1]&#8216;,&#8217;VARCHAR(50)&#8217;) AS EmployeeName,</p>
<p>x.d.value(&#8216;DepartmentID[1]&#8216;,&#8217;INT&#8217;) AS DepartmentID</p>
<p>FROM @data.nodes(&#8216;/NewDataSet/Table&#8217;) x(d)</p>
<p>GO</p>
</div>
<p>Now Let us see the VB.NET code. I have created a VB.NET console application which performs the 4 steps mentioned above.</p>
<p>Note: <span style="color: #ff0000;">The  VB.NET code presented here may not be the best possible code. The  intension of writing this code is to present the best code to perform  the given operation. The idea is to present a basic code which WORKS! </span></p>
<div>
<p>Imports System.Data</p>
<p>Imports System.Data.SqlClient</p>
<p>Imports System.IO</p>
<p>Module Module1</p>
<p>Sub Main()</p>
<p>&#8216;Define a connection string</p>
<p>Dim conStr As String</p>
<p>conStr = &#8220;Data Source=TOSHIBA-USER\SQL2005;Initial Catalog=DataTableTest;Integrated Security=True&#8221;</p>
<p>&#8216;Create and open a new connection</p>
<p>Dim cn As New SqlConnection(conStr)</p>
<p>cn.Open()</p>
<p>&#8216;Create a command to retrieve data from SP</p>
<p>Dim cmd As New SqlCommand(&#8220;GetEmployeeInfo&#8221;, cn)</p>
<p>cmd.CommandType = CommandType.StoredProcedure</p>
<p>&#8216;Fill the DataSet</p>
<p>Dim da As New SqlDataAdapter(cmd)</p>
<p>Dim ds As New DataSet()</p>
<p>da.Fill(ds)</p>
<p>da.Dispose()</p>
<p>cmd.Dispose()</p>
<p>&#8216;Access the first table</p>
<p>Dim dt As DataTable</p>
<p>dt = ds.Tables(0)</p>
<p>&#8216;Create a stream object and Write the content of the DataTable</p>
<p>&#8216;to it.</p>
<p>Dim s As New MemoryStream()</p>
<p>dt.WriteXml(s, True)</p>
<p>&#8216;Retrieve the text from the stream</p>
<p>s.Seek(0, SeekOrigin.Begin)</p>
<p>Dim sr As New StreamReader(s)</p>
<p>Dim xmlString As String</p>
<p>xmlString = sr.ReadToEnd()</p>
<p>&#8216;close</p>
<p>sr.Close()</p>
<p>sr.Dispose()</p>
<p>&#8216;pass the XML data to sqlserver</p>
<p>cmd = New SqlCommand(&#8220;ProcessXml&#8221;, cn)</p>
<p>cmd.CommandType = CommandType.StoredProcedure</p>
<p>Dim p As SqlParameter</p>
<p>p = cmd.Parameters.AddWithValue(&#8220;@data&#8221;, xmlString)</p>
<p>p.SqlDbType = SqlDbType.Xml</p>
<p>cmd.ExecuteNonQuery()</p>
<p>cmd.Dispose()</p>
<p>&#8216;Close connection</p>
<p>cn.Close()</p>
<p>cn.Dispose()</p>
<p>End Sub</p>
<p>End Module</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2007/12/passing-a-data-table-to-a-sql-server-2005-stored-procedure.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FOR XML EXPLICIT &#8211; Part 2</title>
		<link>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-2.html</link>
		<comments>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-2.html#comments</comments>
		<pubDate>Wed, 05 Dec 2007 06:09:48 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sqlserverandxml.com/?p=53</guid>
		<description><![CDATA[Continued from Part 1 Let us move ahead. Under each agent, we need a node named AddressCollection. Let us add the code for that. SELECT 1 AS Tag, NULL AS Parent, NULL AS &#8216;Agents!1!&#8217;, NULL AS &#8216;Agent!2!AgentID&#8217;, NULL AS &#8216;Agent!2!Fname!Element&#8217;, NULL AS &#8216;Agent!2!SSN!Element&#8217;, NULL AS &#8216;AddressCollection!3!Element&#8217; UNION ALL SELECT 2 AS Tag, 1 AS Parent, [...]]]></description>
			<content:encoded><![CDATA[<p>Continued from Part 1<br />
Let us move ahead. Under each agent, we need a node named AddressCollection. Let us add the code for that.</p>
<p>SELECT</p>
<p>1 AS Tag,</p>
<p>NULL AS Parent,</p>
<p>NULL AS &#8216;Agents!1!&#8217;,</p>
<p>NULL AS &#8216;Agent!2!AgentID&#8217;,</p>
<p>NULL AS &#8216;Agent!2!Fname!Element&#8217;,</p>
<p>NULL AS &#8216;Agent!2!SSN!Element&#8217;,</p>
<p>NULL AS &#8216;AddressCollection!3!Element&#8217;</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>2 AS Tag, 1 AS Parent,</p>
<p>NULL, AgentID, Fname, SSN,</p>
<p>NULL</p>
<p>FROM @agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>3 AS Tag, 2 AS Parent,</p>
<p>NULL, NULL, NULL, NULL,</p>
<p>NULL</p>
<p>FROM @agent</p>
<p>FOR XML EXPLICIT</p>
<p>We added a new level for AddressCollection element. I used FROM @agent because we need an AddressCollection element for each agent record. Here is the output.</p>
<p>Vimal</p>
<p>123-23-4521</p>
<p>Jacob</p>
<p>321-52-4562</p>
<p>Tom</p>
<p>252-52-4563</p>
<p>Wait a second! we have a problem. Note that the 3 AddressCollection elements were created as part of the last node. Why does this happen? To understand that we need to look at the query results that we passed to FOR XML EXPLICIT. Let us run the query without FOR XML EXPLICIT.</p>
<div class="post-body entry-content">
<p><a href="http://web.archive.org/web/20080405033852/http://www.sqlserverandxml.com/2007/12/for-xml-explicit-part-1.html">Continued from Part 1</a></p>
<p>Let us move ahead. Under each agent, we need a node named <em>AddressCollection</em>. Let us add the code for that.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span><span style="background-color: yellow;">,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN<span style="background-color: yellow;">, </span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span></span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue; background-color: yellow;">SELECT</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> 3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, </span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FROM </span>@agent</span></p>
<p style="margin: 0px;"><span style="color: blue;">FOR </span>XML EXPLICIT</p>
</div>
<p>We added a new level for <em>AddressCollection</em> element. I used <em>FROM @agent</em> because we need an <em>AddressCollection</em> element for each <em>agent</em> record. Here is the output.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">1</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Vimal<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>123-23-4521<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">2</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Jacob<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>321-52-4562<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">3</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Tom<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>252-52-4563<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> <span style="background-color: yellow;">&lt;</span></span><span style="background-color: yellow;"><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
</div>
<p>Wait a second! we have a problem. Note that the 3 <em>AddressCollection</em> elements were created as part of the last node. Why does this happen? To understand that we need to look at the query results that we passed to FOR XML EXPLICIT. Let us run the query without <em>FOR XML EXPLICIT</em>.</p>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>Note the rows in yellow . These are the records with tag 3. Note that they appear at the bottom of the result set. That is the reason why they appear at the bottom of the XML result. So to fix this, we need to change the order of the rows. So to get the correct XML we need to have the query results in the following order.</p>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>So at this stage, we need to write some kind of code to alter the sort order of the records. There might be different ways to do that. What I did was to add a calculated column for the sort order based on the AgentID. Here is the new code.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">0 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">ORDER BY </span>Sort</span></p>
</div>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="49">Sort</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>0</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>100</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>101</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>200</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>201</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>300</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>301</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>Well, that worked. Note that the sort order holds correct values so that we get the records in the desired order. There might be different ways to generate the sort order column. For the purpose of this example, I made it by multiplying the AgentID with 100, 101 etc. This approach may not work in a different situation. It worked for the example. The KEY here is to sort the records in the correct order (exactly in the order that we need them in the XML results). You can apply your own logic that you feel right, to achieve this.</p>
<p>Let us generate the XML now.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;">0 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">ORDER BY </span>Sort</p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FOR </span>XML EXPLICIT</span></p>
</div>
<p>unfortunately, this code will not work. If you try to run this, you will get the following error.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: #ff0000;">TOSHIBA-USER\SQL2005(TOSHIBA-USER\Jacob Sebastian): Msg 6802, Level 16, State 1, Line 33</span></p>
<p style="margin: 0px;"><span style="color: #ff0000;">FOR XML EXPLICIT query contains the invalid column name &#8216;Sort&#8217;. Use the TAGNAME!TAGID!ATTRIBUTENAME[!..] format where TAGID is a positive integer.</span></p>
</div>
<p>The error is caused by the &#8220;Sort&#8221; column that we just added. When we use FOR XML EXPLICIT, all columns other than <em>&#8220;Tag&#8221;</em> and <em>&#8220;Parent&#8221;</em> should be in the form of <em>&#8220;[TAG]![TAGID]!ATTRIBUTE&#8230;&#8221;</em>. We need to hide the <em>&#8220;Sort&#8221;</em> column. Lets create an outer query to do this.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">SELECT </span>Tag, Parent,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agents!1!],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!AgentID],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!Fname!Element],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!SSN!Element],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [AddressCollection!3!Element]</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FROM </span>(</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;">0 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="background-color: yellow;">) A</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">ORDER BY </span>Sort</span></p>
<p style="margin: 0px;"><span style="color: blue;">FOR </span>XML EXPLICIT</p>
</div>
<p>Here is the result.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">1</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Vimal<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>123-23-4521<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">2</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Jacob<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>321-52-4562<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">3</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Tom<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>252-52-4563<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
</div>
<p><a href="http://web.archive.org/web/20080405033852/http://www.sqlserverandxml.com/2007/12/for-xml-explicit-part-3.html">Continued to part 3</a></p>
</div>
<p>Note the rows in yellow . These are the records with tag 3. Note that they appear at the bottom of the result set. That is the reason why they appear at the bottom of the XML result. So to fix this, we need to change the order of the rows. So to get the correct XML we need to have the query results in the following order.</p>
<p>Tag Parent Agents!1! Agent!2!AgentID Agent!2!Fname Agent!2!ssn AddressCollection!3   1 NULL NULL NULL NULL NULL NULL   2 1 NULL 1 Vimal 123-23-4521 NULL   3 2 NULL NULL NULL NULL NULL   2 1 NULL 2 Jacob 321-52-4562 NULL   3 2 NULL NULL NULL NULL NULL   2 1 NULL 3 Tom 252-52-4563 NULL   3 2 NULL NULL NULL NULL NULL</p>
<p>So at this stage, we need to write some kind of code to alter the sort order of the records. There might be different ways to do that. What I did was to add a calculated column for the sort order based on the AgentID. Here is the new code.</p>
<p>SELECT</p>
<p>1 AS Tag,</p>
<p>NULL AS Parent,</p>
<p>0 AS Sort,</p>
<p>NULL AS &#8216;Agents!1!&#8217;,</p>
<p>NULL AS &#8216;Agent!2!AgentID&#8217;,</p>
<p>NULL AS &#8216;Agent!2!Fname!Element&#8217;,</p>
<p>NULL AS &#8216;Agent!2!SSN!Element&#8217;,</p>
<p>NULL AS &#8216;AddressCollection!3!Element&#8217;</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>2 AS Tag, 1 AS Parent,</p>
<p>AgentID * 100 AS Sort,</p>
<p>NULL, AgentID, Fname, SSN,</p>
<p>NULL</p>
<p>FROM @agent</p>
<p>UNION ALL</p>
<p>SELECT</p>
<p>3 AS Tag, 2 AS Parent,</p>
<p>AgentID * 100 + 1 AS Sort,</p>
<p>NULL, NULL, NULL, NULL,</p>
<p>NULL</p>
<p>FROM @agent</p>
<p>ORDER BY Sort</p>
<div class="post-body entry-content">
<p><a href="http://web.archive.org/web/20080405033852/http://www.sqlserverandxml.com/2007/12/for-xml-explicit-part-1.html">Continued from Part 1</a></p>
<p>Let us move ahead. Under each agent, we need a node named <em>AddressCollection</em>. Let us add the code for that.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span><span style="background-color: yellow;">,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN<span style="background-color: yellow;">, </span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span></span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue; background-color: yellow;">SELECT</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> 3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, </span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> <span style="color: blue;">NULL</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FROM </span>@agent</span></p>
<p style="margin: 0px;"><span style="color: blue;">FOR </span>XML EXPLICIT</p>
</div>
<p>We added a new level for <em>AddressCollection</em> element. I used <em>FROM @agent</em> because we need an <em>AddressCollection</em> element for each <em>agent</em> record. Here is the output.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">1</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Vimal<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>123-23-4521<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">2</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Jacob<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>321-52-4562<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">3</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Tom<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>252-52-4563<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> <span style="background-color: yellow;">&lt;</span></span><span style="background-color: yellow;"><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
</div>
<p>Wait a second! we have a problem. Note that the 3 <em>AddressCollection</em> elements were created as part of the last node. Why does this happen? To understand that we need to look at the query results that we passed to FOR XML EXPLICIT. Let us run the query without <em>FOR XML EXPLICIT</em>.</p>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>Note the rows in yellow . These are the records with tag 3. Note that they appear at the bottom of the result set. That is the reason why they appear at the bottom of the XML result. So to fix this, we need to change the order of the rows. So to get the correct XML we need to have the query results in the following order.</p>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>So at this stage, we need to write some kind of code to alter the sort order of the records. There might be different ways to do that. What I did was to add a calculated column for the sort order based on the AgentID. Here is the new code.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">0 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;"><span style="background-color: yellow;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</span></p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">ORDER BY </span>Sort</span></p>
</div>
<table border="1">
<tbody>
<tr>
<td width="31">Tag</td>
<td width="49">Parent</td>
<td width="49">Sort</td>
<td width="65">Agents!1!</td>
<td width="110">Agent!2!AgentID</td>
<td width="104">Agent!2!Fname</td>
<td width="79">Agent!2!ssn</td>
<td width="134">AddressCollection!3</td>
</tr>
<tr>
<td>1</td>
<td>NULL</td>
<td>0</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>100</td>
<td>NULL</td>
<td>1</td>
<td>Vimal</td>
<td>123-23-4521</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>101</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>200</td>
<td>NULL</td>
<td>2</td>
<td>Jacob</td>
<td>321-52-4562</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>201</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>300</td>
<td>NULL</td>
<td>3</td>
<td>Tom</td>
<td>252-52-4563</td>
<td>NULL</td>
</tr>
<tr style="background-color: yellow;">
<td>3</td>
<td>2</td>
<td>301</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</tbody>
</table>
<p>Well, that worked. Note that the sort order holds correct values so that we get the records in the desired order. There might be different ways to generate the sort order column. For the purpose of this example, I made it by multiplying the AgentID with 100, 101 etc. This approach may not work in a different situation. It worked for the example. The KEY here is to sort the records in the correct order (exactly in the order that we need them in the XML results). You can apply your own logic that you feel right, to achieve this.</p>
<p>Let us generate the XML now.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;">0 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">ORDER BY </span>Sort</p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FOR </span>XML EXPLICIT</span></p>
</div>
<p>unfortunately, this code will not work. If you try to run this, you will get the following error.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: #ff0000;">TOSHIBA-USER\SQL2005(TOSHIBA-USER\Jacob Sebastian): Msg 6802, Level 16, State 1, Line 33</span></p>
<p style="margin: 0px;"><span style="color: #ff0000;">FOR XML EXPLICIT query contains the invalid column name &#8216;Sort&#8217;. Use the TAGNAME!TAGID!ATTRIBUTENAME[!..] format where TAGID is a positive integer.</span></p>
</div>
<p>The error is caused by the &#8220;Sort&#8221; column that we just added. When we use FOR XML EXPLICIT, all columns other than <em>&#8220;Tag&#8221;</em> and <em>&#8220;Parent&#8221;</em> should be in the form of <em>&#8220;[TAG]![TAGID]!ATTRIBUTE&#8230;&#8221;</em>. We need to hide the <em>&#8220;Sort&#8221;</em> column. Lets create an outer query to do this.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">SELECT </span>Tag, Parent,</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agents!1!],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!AgentID],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!Fname!Element],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [Agent!2!SSN!Element],</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"> [AddressCollection!3!Element]</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">FROM </span>(</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">1 <span style="color: blue;">AS </span>Tag,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span>Parent,</p>
<p style="margin: 0px;">0 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agents!1!&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!AgentID&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!Fname!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;Agent!2!SSN!Element&#8217;</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL AS </span><span style="color: #a31515;">&#8216;AddressCollection!3!Element&#8217;</span></p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">2 <span style="color: blue;">AS </span>Tag, 1 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, AgentID, Fname, SSN,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="color: blue;">UNION ALL</span></p>
<p style="margin: 0px;"><span style="color: blue;">SELECT</span></p>
<p style="margin: 0px;">3 <span style="color: blue;">AS </span>Tag, 2 <span style="color: blue;">AS </span>Parent,</p>
<p style="margin: 0px;">AgentID * 100 + 1 <span style="color: blue;">AS </span>Sort,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>, <span style="color: blue;">NULL</span>,</p>
<p style="margin: 0px;"><span style="color: blue;">NULL</span></p>
<p style="margin: 0px;"><span style="color: blue;">FROM </span>@agent</p>
<p style="margin: 0px;"><span style="background-color: yellow;">) A</span></p>
<p style="margin: 0px;"><span style="background-color: yellow;"><span style="color: blue;">ORDER BY </span>Sort</span></p>
<p style="margin: 0px;"><span style="color: blue;">FOR </span>XML EXPLICIT</p>
</div>
<p>Here is the result.</p>
<div style="font-size: 10pt; background: none repeat scroll 0% 0% white; color: black; font-family: courier new;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">1</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Vimal<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>123-23-4521<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">2</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Jacob<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>321-52-4562<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Agent</span><span style="color: blue;"> </span><span style="color: red;">AgentID</span><span style="color: blue;">=</span>&#8220;<span style="color: blue;">3</span>&#8220;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span>Tom<span style="color: blue;">&lt;/</span><span style="color: #a31515;">Fname</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span>252-52-4563<span style="color: blue;">&lt;/</span><span style="color: #a31515;">SSN</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">AddressCollection</span><span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;"> &lt;/</span><span style="color: #a31515;">Agent</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">Agents</span><span style="color: blue;">&gt;</span></p>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://sqlserverandxml.com/2007/12/for-xml-explicit-part-2.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

