将子节点的文本串联到单个列中

Phi*_*per 2 xml sql xpath xquery sql-server-2008

我正在使用一个返回属性信息的API。一些文本信息存储在子节点之间,我想将其连接为单个字符串(VARCHAR)。

我的过程是,我通过Web服务获取xml,然后将其传递给proc,该proc提取xml值并将其插入到视图中,这是我返回的xml的代码段:

<properties>
    <property propertyid="1234">
        <bullets>
            <bullet>nice garden</bullet>
            <bullet>it smells a bit</bullet>
            <bullet>body under the patio</bullet>
        </bullets>
    </property>
    ...
</properties>
Run Code Online (Sandbox Code Playgroud)

这是对如何查询xml以从中提取值的一瞥:

INSERT        
INTO          VProperty
(             PropertyId,
              Description
)
SELECT        P.value('@propertyid', 'INT'),
              NULL -- extract all the bullet text values into a single string
FROM          @xml.nodes('/properties/property')
Run Code Online (Sandbox Code Playgroud)

在此示例中,我希望能够从xml中提取信息,因此最终结果如下:

PropertyId    Description
1234          'nice garden\r\nit smells a bit\r\nbody under the patio
Run Code Online (Sandbox Code Playgroud)

在纯sql / xml中这是否可行?还是在我进入SQL领域之前我需要对xml进行一些预处理?

任何帮助表示赞赏(一如既往)。

Seb*_*ine 5

这对您有用吗?

DECLARE @XML XML = 
('<properties>
    <property propertyid="1234">
        <bullets>
            <bullet>nice garden</bullet>
            <bullet>it smells a bit</bullet>
            <bullet>body under the patio</bullet>
        </bullets>
    </property>
    <property propertyid="2345">
        <bullets>
            <bullet>bullet 2345_1</bullet>
            <bullet>bullet 2345_2</bullet>
            <bullet>bullet 2345_3</bullet>
        </bullets>
    </property>
</properties>');

SELECT  X.node.value('@propertyid', 'INT'),
        STUFF((SELECT '\r\n' + B.bullet.value('.', 'NVARCHAR(MAX)')
               FROM   X.node.nodes('./bullets/bullet') B ( bullet )
               FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),
              1, 4, '') AS Description
FROM    @xml.nodes('/properties/property') X ( node );
Run Code Online (Sandbox Code Playgroud)