我在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 := " "
let $space := " "
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
是否有可能以这种方式实现我想要的目标?
答案 0 :(得分: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