如果条件在SQL中选择XML节点

时间:2015-07-23 23:50:37

标签: sql-server xml xquery-sql

我正在尝试读取xml并将其存储在SQL server中。

DECLARE @xml XML
SET @xml = 
 '<report>
    <personal>
       <search>
           <subject>
               <name>SearchName</name>
           </subject>
       </search>    
    </personal>
    <personal>
       <search>
           <subject>
               <name>SearchName</name>
           </subject>
       </search>
       <result>
           <history>
              <name>HistoryName</name>
           </history>
       </result>
    </personal>
  </report>
'

我在这里尝试的是 - 选择名称,但这里的条件是 如果<personal>包含<result>,请选择name下的history/name

如果<personal>不包含<result>,请选择name下的subject/name

目前我正在从个人/主题中选择姓名,如下所示:

Select 
A.Search.value('(subject/name)[1]','varchar(max)')
FROM  @xml.nodes('/report/personal/search') as A(Search)

期待结果:

SearchName
HistoryName

如何在两者之间添加条件?

我们有什么方法可以在这里添加存在条件

 SELECT @xml.exist('//report//personal//search//subject//name')

2 个答案:

答案 0 :(得分:1)

Select coalesce(A.Search.value('(result/history/name)[1]', 'varchar(max)'), A.Search.value('(search/subject/name)[1]','varchar(max)'))
FROM @xml.nodes('/report/personal') as A(Search)

答案 1 :(得分:0)

此:

SELECT 
    COALESCE(
       A.Search.value('(result/history/name)[1]','varchar(max)'),
       A.Search.value('(search/subject/name)[1]','varchar(max)')
    ) AS Name
FROM @xml.nodes('/report/personal') as A(Search)

将返回:

Name
------------
SearchName
HistoryName