共用方式為


範例:指定 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">

<摘要>

<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 值,而是使用 xml 類型的 query() 方法,擷取 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;

請參閱

參考