共用方式為


具有 XPath 節點測試名稱的數據行

如果欄位名稱是 XPath 節點測試之一,則內容會對應到如下表所示。 當數據行名稱是 XPath 節點測試時,內容會對應至對應的節點。 如果數據行的 SQL 類型為 xml,則會傳回錯誤。

欄位名稱 行為
text() 如果是具有 text() 名稱的數據行,該數據行中的字串值會新增為文字節點。
評論() 對於具有 comment() 名稱的數據行,該數據行中的字串值會新增為 XML 批注。
node() 如果是名稱為 node() 的數據行,結果會與當數據行名稱為通配符 *時相同。
processing-instruction(name) 對於具有處理指令名稱的數據行,該數據行中的字串值會新增為處理指令目標名稱的 PI 值。

下列查詢顯示節點測試名稱作為欄名稱的用法。 它會在產生的 XML 中新增文字節點和批注。

USE AdventureWorks2012;  
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>

另請參閱

使用 PATH 模式搭配 FOR XML