此示例说明了 ELEMENT 和 XML 指令之间的差异。
ELEMENT 指令将实体化数据,但 XML 指令不会。 在 <查询中为 Summary> 元素分配了 XML <Summary>This is summary description</Summary>。
请看下面的查询:
USE AdventureWorks2012;
GO
SELECT 1 as Tag,
0 as Parent,
ProductModelID as [ProductModel!1!ProdModelID],
Name as [ProductModel!1!Name],
NULL as [Summary!2!SummaryDescription!ELEMENT]
FROM Production.ProductModel
WHERE ProductModelID=19
UNION ALL
SELECT 2 as Tag,
1 as Parent,
ProductModelID,
NULL,
'<Summary>This is summary description</Summary>'
FROM Production.ProductModel
WHERE ProductModelID=19
FOR XML EXPLICIT
结果如下: 结果中将实体化摘要说明。
<ProductModel ProdModelID="19" Name="Mountain-100">
<Summary>
<SummaryDescription><Summary>This is summary description</Summary></SummaryDescription>
</Summary>
</ProductModel>
现在,如果在列名称中指定 XML 指令,而不是 ELEMENT 指令,您将收到未进行实体化处理的摘要说明。
<ProductModel ProdModelID="19" Name="Mountain-100">
<Summary>
<SummaryDescription>
<Summary>This is summary description</Summary>
</SummaryDescription>
</Summary>
</ProductModel>
以下查询使用 xml 类型的 query() 方法从 xml 类型的 CatalogDescription 列检索产品模型摘要说明,而不是分配静态 XML 值。 由于结果已知为 xml 类型,因此不会应用任何实体化。
SELECT 1 as Tag,
0 as Parent,
ProductModelID as [ProductModel!1!ProdModelID],
Name as [ProductModel!1!Name],
NULL as [Summary!2!SummaryDescription]
FROM Production.ProductModel
WHERE CatalogDescription is not null
UNION ALL
SELECT 2 as Tag,
1 as Parent,
ProductModelID,
Name,
(SELECT CatalogDescription.query('
declare namespace pd="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";
/pd:ProductDescription/pd:Summary'))
FROM Production.ProductModel
WHERE CatalogDescription is not null
ORDER BY [ProductModel!1!ProdModelID],Tag
FOR XML EXPLICIT