この例では、 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>
ここで、ELEMENT ディレクティブの代わりに、Summary!2!SummaryDescription!XML
列名に XML ディレクティブを指定すると、エンティティ化なしで概要の説明を受け取ります。
<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