Contoh: Tentukan direktif ELEMENT dan pengodean entitas
Berlaku untuk: SQL ServerAzure SQL Database Azure SQL Managed Instance
Contoh ini mengilustrasikan perbedaan antara arahan ELEMENT dan XML . Arahan ELEMENT berhak atas data, tetapi direktif XML tidak. Elemen <Summary>
ditetapkan XML, <Summary>This is summary description</Summary>
, dalam kueri.
Pertimbangkan kueri ini:
USE AdventureWorks2022;
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;
Ini adalah hasilnya. Deskripsi ringkasan berhak dalam hasilnya.
<ProductModel ProdModelID="19" Name="Mountain-100">
<Summary>
<SummaryDescription><Summary>This is summary description</Summary></SummaryDescription>
</Summary>
</ProductModel>
Sekarang, jika Anda menentukan direktif XML dalam nama kolom, Summary!2!SummaryDescription!XML
, alih-alih arahan ELEMENT , Anda akan menerima deskripsi ringkasan tanpa pemberian izin.
<ProductModel ProdModelID="19" Name="Mountain-100">
<Summary>
<SummaryDescription>
<Summary>This is summary description</Summary>
</SummaryDescription>
</Summary>
</ProductModel>
Alih-alih menetapkan nilai XML statis, kueri berikut menggunakan query()
metode jenis xml untuk mengambil deskripsi ringkasan model produk dari kolom CatalogDescription jenis xml. Karena hasilnya diketahui berjenis xml , tidak ada pemberian izin yang diterapkan.
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="http://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;