1

我在 SQL Server 2008R2 的表中有一个 XML 列。XML 看起来像这样(简化示例):

<root>
   ...
   <Filters>
       <Filter type="a">
          <Patterns>
              <Pattern>bla bla bla</Pattern>
              <Pattern>kuku</Pattern>
          </Patterns>
       </Filter>
       <Filter type="b">
           <Name>Cookie</Name>
       </Filter>
       <Filter type="c">
          <FileTypes>
              <FileType>exe</FileType>
              <FileType>jpg</FileType>
          </FileTypes>
       </Filter>
   </Filters>
   ...
</root>

即可以定义很多过滤器类型,并且每种类型都有唯一的子元素。我想编写一个返回以下字符串的查询:

Filter Type: a
Configuration:
    <Patterns>
        <Pattern>bla bla bla</Pattern>
        <Pattern>kuku</Pattern>
    </Patterns>

Filter Type: b
Configuration:
    <Name>Cookie</Name>

Filter Type: c
Configuration:
    <FileTypes>
        <FileType>exe</FileType>
        <FileType>jpg</FileType>
    </FileTypes>

到目前为止,我所拥有的是:

SELECT
   xmlFiled.query(
     let $nl := "&#10;"
     let $space := "&#32;"
     let $tab := concat($space, $space, $space, $space)
     for $f in /root/.../Filters/Filter 
     return concat("Filter Type: ", $f/@type, $nl, "Configuration:", $nl, $tab, $f/node()[1], $nl)'
     ) AS Filters, 
FROM Table

问题是 $f/node()[1] 的字符串转换将节点的所有内部元素中的文本连接起来而不保留 XML 标签,所以我得到的结果是这样的:

Filter Type: a
Configuration:
    bla bla blakuku

Filter Type: b
Configuration:
    Cookie

Filter Type: c
Configuration:
    exejpg

有可能以这种方式实现我想要的吗?

4

1 回答 1

0

获得所需结果的另一种方法。

declare @T table(xmlFiled xml)

insert into @T values
('<root>
   <Filters>
       <Filter type="a">
          <Patterns>
              <Pattern>bla bla bla</Pattern>
              <Pattern>kuku</Pattern>
          </Patterns>
       </Filter>
       <Filter type="b">
           <Name>Cookie</Name>
       </Filter>
       <Filter type="c">
          <FileTypes>
              <FileType>exe</FileType>
              <FileType>jpg</FileType>
          </FileTypes>
       </Filter>
   </Filters>
</root>')

select stuff((
             select char(10)+char(10)+'Filter Type: '+F.N.value('@type', 'char(1)')+char(10)+
                    'Configuration:'+char(10)+space(4),
                    F.N.query('*')
             from T.xmlFiled.nodes('/root/Filters/Filter') as F(N)
             for xml path('')
             ), 1, 2, '')
from @T as T

结果:

Filter Type: a
Configuration:
    <Patterns><Pattern>bla bla bla</Pattern><Pattern>kuku</Pattern></Patterns>

Filter Type: b
Configuration:
    <Name>Cookie</Name>

Filter Type: c
Configuration:
    <FileTypes><FileType>exe</FileType><FileType>jpg</FileTyp
于 2012-08-06T16:23:47.377 回答