When a SELECT statement with a FOR XML clause specifies a four-part name in the query, the server name is not returned in the resulting XML document when the query is executed on the local computer. However, the server name is returned as the four-part name when the query is executed on a network server.
For example, consider this query:
SELECT TOP 1 LastName
FROM ServerName.Northwind.dbo.Employees
FOR XML AUTO
When ServerName is a local server, the query returns:
<Northwind.dbo.Employees LastName="Buchanan"/>
When ServerName is a network server, the query returns:
<ServerName.Northwind.dbo.Employees LastName="Buchanan"/>
This can be avoided by specifying this alias:
SELECT TOP 1 LastName
FROM ServerName.Northwind.dbo.Employees x
FOR XML AUTO
This query returns:
<x ="Buchanan"/>
Using derived tables in a SELECT statement with FOR XML AUTO may not produce the nesting you want.
The FOR BROWSE mode is implemented when a query with the FOR XML AUTO mode is specified. The FOR XML AUTO mode uses the information provided by the FOR BROWSE mode in determining the hierarchy in the result set.
For example, consider the following query. A derived table P is created in the query.
SELECT c.CompanyName,
o.OrderID,
o.OrderDate,
p.ProductName,
p.Quantity,
p.UnitPrice,
p.Total
FROM Customers AS c
JOIN
Orders AS o
ON
c.CustomerID = o.CustomerID
JOIN
(
SELECT od.OrderID,
pr.ProductName,
od.Quantity,
od.UnitPrice,
od.Quantity * od.UnitPrice AS total
FROM Products AS pr
JOIN
[Order Details] AS od
ON
pr.ProductID = od.ProductID
) AS p
ON
o.OrderID = p.OrderID
FOR XML AUTO
This is the partial result:
<c CompanyName="Vins et alcools Chevalier">
<o OrderID="10248" OrderDate="1996-07-04T00:00:00">
<pr ProductName="Queso Cabrales">
<od Quantity="12" UnitPrice="14.0000" total="168.0000"/>
</pr>
<pr ProductName="Singaporean Hokkien Fried Mee">
<od Quantity="10" UnitPrice="9.8000" total="98.0000"/>
</pr>
</c>
In the resulting XML document, the <p> element is missing, and the <pr> and <od> elements are returned. This occurs because the query optimizer eliminates the P table in the result and returns a result set consisting of the od and pr tables.
This can be avoided by rewriting the query. For example, you can rewrite the query is to create a view and use it in the SELECT statement:
CREATE VIEW p AS
SELECT od.OrderID,
pr.ProductName,
od.Quantity,
od.UnitPrice,
od.Quantity * od.UnitPrice AS total
FROM Products AS pr
JOIN
[Order Details] AS od
ON
pr.ProductID = od.ProductID
And then write the SELECT statement:
SELECT c.CompanyName,
o.OrderID,
o.OrderDate,
p.ProductName,
p.Quantity,
p.UnitPrice,
p.total
FROM Customers AS c
JOIN
Orders AS o
ON
c.CustomerID = o.CustomerID
JOIN
p
ON
o.OrderID = p.OrderID
FOR XML AUTO
This is the partial result:
<c CompanyName="Vins et alcools Chevalier">
<o OrderID="10248" OrderDate="1996-07-04T00:00:00">
<p ProductName="Queso Cabrales"
Quantity="12"
UnitPrice="14.0000"
total="168.0000"/>
</o>
</c>