列名为 XPath 节点测试的列

如果列名称是 XPath 节点测试中的一个,则内容将进行映射,如下表所示。 当列名称为 XPath 节点测试时,内容将映射到相应的节点。 如果列的 SQL 类型为 xml,则返回错误。

列名 行为
text() 对于名称为 text 的列(),该列中的字符串值将添加为文本节点。
comment() 对于具有 comment 名称的列(),该列中的字符串值将添加为 XML 注释。
node() 对于名称为node()节点名的列,结果与列名称为通配符字符(*)时的结果相同。
处理指令(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 配合使用