SQL匹配嵌套XML节点的内容

时间:2015-09-03 22:34:05

标签: sql-server xml

我有一个包含XML嵌套的数据库字段:

<configuration>
   <modules>
    <genericMailer>
      <moduleContent>
        <data>
          <sendMethod>Email</sendMethod>

我的XML可以包含<genericMailer>元素(及其子节点)的许多实例。我想找到<genericMailer>包含<sendMethod>包含邮件的任何sendMethod个实例的所有行。

我可以像这样获得SELECT a.ApplicationId, x.XmlCol.value('(moduleContent/data/sendMethod)[1]','VARCHAR(100)') AS SendMethod FROM Applications a CROSS APPLY a.AppConfig.nodes('/configuration/modules/genericMailer') x(XmlCol); 的所有值:

jv.local

然而,我不知道如何只搜索匹配的值。我需要什么WHERE子句?

1 个答案:

答案 0 :(得分:2)

以下是一些可能的方法:

一个。使用value()方法提取sendMethod值,然后检查WHERE子句中的值LIKE '%mail%'

SELECT  a.ApplicationId,
        x.XmlCol.value('(moduleContent/data/sendMethod)[1]','VARCHAR(100)') AS SendMethod
FROM    Applications a
CROSS APPLY a.AppConfig.nodes('/configuration/modules/genericMailer') x(XmlCol)
WHERE  x.XmlCol.value('(moduleContent/data/sendMethod)[1]','VARCHAR(100)') LIKE '%mail%'

湾使用XPath方法contains()检查sendMethod值是否包含子字符串"mail"和SQL Server方法exist()以过滤通过检查的行:

SELECT  a.ApplicationId,
        x.XmlCol.value('(moduleContent/data/sendMethod)[1]','VARCHAR(100)') AS SendMethod
FROM    Applications a
CROSS APPLY a.AppConfig.nodes('/configuration/modules/genericMailer') x(XmlCol)
WHERE x.XmlCol.exist('moduleContent/data/sendMethod[contains(.,"mail")]') = 1