含有 XPath 節點測試名稱的資料行

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體Microsoft Fabric 中的 SQL 資料庫

如果資料行名稱是 XPath 節點測試之一,內容會依下表所示進行對應。 如果資料行名稱是 XPath 節點測試,會將內容對應至對應的節點。 如果資料行的 SQL 類型是 xml,就會傳回錯誤。

資料行名稱 行為
text() 對於名稱為 text() 的資料行,該資料行中的字串值會作為文字節點加入。
comment() 對於名稱為 comment() 的資料行,該資料行中的字串值會作為 XML 註解加入。
node() 資料行若含有 node() 名稱,其結果與資料行名稱為萬用字元 (*) 的結果相同。
處理指令(name) 對於名稱為處理指示的資料行,該資料行中的字串值會作為該處理指示目標名稱的 PI 值加入。

下列查詢顯示如何將節點測試用作資料行名稱。 它會在產生的 XML 中加入文字節點和註解。

Note

在 Azure SQL Database 和 Microsoft Fabric 中的 SQL 資料庫中,USE語句都無法使用。 相反地,直接連接到預期的資料庫,執行剩餘的程式碼範例。

USE AdventureWorks2022;
GO
SELECT E.BusinessEntityID "@EmpID",
        'Example of using node tests such as text(), comment(), processing-instruction()'  as "comment()",
        'Some PI'                        as "processing-instruction(PI)",
        'Employee name and address data' as "text()",
        'middle name is optional'        as "EmpName/text()",
        FirstName                        as "EmpName/First",
        MiddleName                       as "EmpName/Middle",
        LastName                         as "EmpName/Last",
        AddressLine1                     as "Address/AddrLine1",
        AddressLine2                     as "Address/AddrLIne2",
        City                             as "Address/City"
FROM   HumanResources.Employee AS E
INNER JOIN Person.Person AS P
    ON P.BusinessEntityID = E.BusinessEntityID
INNER JOIN Person.BusinessEntityAddress AS BAE
    ON BAE.BusinessEntityID = E.BusinessEntityID
INNER JOIN Person.Address AS A
    ON BAE.AddressID = A.AddressID
WHERE  E.BusinessEntityID=1
FOR XML PATH;

以下是結果:


<row EmpID="1">
<!--Example of using node tests such as text(), comment(), processing-instruction() -->
<?PI Some PI?>
    Employee name and address data
    <EmpName>middle name is optional
        <First>Ken</First>
        <Last>Sánchez</Last>
    </EmpName>
    <Address>
        <AddrLine1>4350 Minute Dr.</AddrLine1>
        <City>Minneapolis</City>
    </Address>
</row>