示例:指定 ELEMENT 指令和实体编码

此示例说明了 ELEMENT 和 XML 指令之间的差异。ELEMENT 指令会实体化数据,但 XML 指令则不会。在查询中向 <Summary> 元素分配了 XML <Summary>This is summary description</Summary>。

请看下面的查询:

USE AdventureWorks2008R2;
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>&lt;Summary&gt;This is summary description&lt;/Summary&gt;</SummaryDescription>

</Summary>

</ProductModel>

现在,如果在列名 Summary!2!SummaryDescription!XML 中指定 XML 指令而不是 ELEMENT 指令,则您将收到未经实体化的摘要说明。

<ProductModel ProdModelID="19" Name="Mountain-100">

<Summary>

<SummaryDescription>

<Summary>This is summary description</Summary>

</SummaryDescription>

</Summary>

</ProductModel>

以下查询使用 xml 类型的 query() 方法(而不是分配一个静态 XML 值)从 xml 类型的 CatalogDescription 列中检索产品型号摘要说明。因为已经知道结果为 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;

请参阅

参考