从XML中选择所有匹配的字符串值

时间:2019-04-23 17:43:04

标签: sql xml tsql parsing sql-server-2012

我需要从XML列中检索所有以“ +”结尾的句子。我拥有的当前查询仅检索第一句话。

以下是XML内容:

<file>
  <row>Addendum and/or contract providing additional event details and conditions. +</row>
  <row />
  <row>Special duty officer(s) required for event. There are charges for these services.+</row>
  <row />
  <row>Notify Mall Crew of electrical needs for activities.+</row>
  <row />
  <row>8’ pedestrian pathway must be maintained on sidewalks throughout event area.~</row>
  <row />
  <row>Provide and maintain access to the Hotel during event.~</row>
  <row />
  <row>Event organizer/sponsor is responsible for cleanup of event area.|</row>
  <row />  
</file>

您会看到三行句子的结尾都带有“ +”。我运行此查询:

SELECT b.value('(./row/text())[1]','nvarchar(max)') as [row]
FROM @xmlstr.nodes('/file') AS a(b)
WHERE right(b.value('(./row/text())[1]','nvarchar(max)'), 1) = '+'

但是我只得到第一句话,而且我需要所有结尾都带有加号的句子。

如果有人可以帮助我解决这个问题,我将非常感激

谢谢。

2 个答案:

答案 0 :(得分:2)

John的解决方案很棒,只是提供一种替代方法,您可以调用XQuery来检查最后一个字符,如下所示:

DECLARE @xml XML=N'<file>
  <row>Addendum and/or contract providing additional event details and conditions. +</row>
  <row />
  <row>Special duty officer(s) required for event. There are charges for these services.+</row>
  <row />
  <row>Notify Mall Crew of electrical needs for activities.+</row>
  <row />
  <row>8’ pedestrian pathway must be maintained on sidewalks throughout event area.~</row>
  <row />
  <row>Provide and maintain access to the Hotel during event.~</row>
  <row />
  <row>Event organizer/sponsor is responsible for cleanup of event area.|</row>
  <row />  
</file>';

SELECT r.value('text()[1]','nvarchar(1000)')
FROM @xml.nodes('/file/row[substring(text()[1],string-length(text()[1]),1)="+"]') A(r);

结果

Addendum and/or contract providing additional event details and conditions. +
Special duty officer(s) required for event. There are charges for these services.+
Notify Mall Crew of electrical needs for activities.+

答案 1 :(得分:1)

也许是这样的

SELECT b.value('.','nvarchar(max)') as [row]
 FROM  @xmlstr.nodes('file/*') AS a(b)
WHERE  b.value('.','nvarchar(max)') like '%+'

返回

row
Addendum and/or contract providing additional event details and conditions. +
Special duty officer(s) required for event. There are charges for these services.+
Notify Mall Crew of electrical needs for activities.+