範例:指定 ELEMENTXSINIL 指示詞
適用於:SQL Server Azure SQL 資料庫 Azure SQL 受控執行個體
當您指定 ELEMENT 指示詞來擷取項目中心的 XML 時,如果資料行有 NULL 值,EXPLICIT 模式就不會產生與其對應的項目。 您可以在 xsi:nil 屬性設為值 TRUE 之處,選擇性地指定 ELEMENTXSINIL 指示詞,要求產生 NULL 值的元素。
以下查詢會建構包括員工地址在內的 XML。 對於 AddressLine2
及 City
資料行,資料行名稱會指定 ELEMENTXSINIL
指示詞。 這會在資料列集中,為 AddressLine2
及 City
資料行中的 NULL 值產生元素。
USE AdventureWorks2022;
GO
SELECT 1 as Tag,
NULL as Parent,
E.BusinessEntityID as [Employee!1!EmpID],
BEA.AddressID as [Employee!1!AddressID],
NULL as [Address!2!AddressID],
NULL as [Address!2!AddressLine1!ELEMENT],
NULL as [Address!2!AddressLine2!ELEMENTXSINIL],
NULL as [Address!2!City!ELEMENTXSINIL]
FROM HumanResources.Employee AS E
INNER JOIN Person.BusinessEntityAddress AS BEA
ON E.BusinessEntityID = BEA.BusinessEntityID
UNION ALL
SELECT 2 as Tag,
1 as Parent,
E.BusinessEntityID,
BEA.AddressID,
A.AddressID,
AddressLine1,
AddressLine2,
City
FROM HumanResources.Employee AS E
INNER JOIN Person.BusinessEntityAddress AS BEA
ON E.BusinessEntityID = BEA.BusinessEntityID
INNER JOIN Person.Address AS A
ON BEA.AddressID = A.AddressID
ORDER BY [Employee!1!EmpID],[Address!2!AddressID]
FOR XML EXPLICIT;
以下是部份結果:
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
EmpID="1"
AddressID="249">
<Address AddressID="249">
<AddressLine1>4350 Minute Dr.</AddressLine1>
<AddressLine2 xsi:nil="true" />
<City>Minneapolis</City>
</Address>
</Employee>
...