查询从XML中检索值在SQL中

时间:2017-08-15 17:00:29

标签: sql-server xml

我的SQL表中有以下XML:

<SiteSurveyData>
  <SurveyQuestionAnswers>
    <QuestionGUID>61</QuestionGUID>
    <Answer>XXXXXXX</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>62</QuestionGUID>
    <Answer>XXX</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>64</QuestionGUID>
    <Answer>Both</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>63</QuestionGUID>
    <Answer>aal5snap</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>81</QuestionGUID>
    <Answer>00</Answer>
  </SurveyQuestionAnswers>

我试图查询的是我想要/ AnswerGUID = 61和62中的值。

我试过用这个:

value('(/SiteSurveyData/SurveyQuestionAnswers/QuestionGUID)[1]'

但它只返回第一个QuestionGUID 如何编写查询以便它返回QuestionGUID 61和62的答案?

或者我只想得到/ AnswerGuid = 61的答案 它并不总是第一个元素,是否可以编写查询以便它返回QuestionGuid = 61的值?

1 个答案:

答案 0 :(得分:1)

DECLARE @t TABLE(id INT IDENTITY(1,1),x XML);
INSERT INTO @t(x)VALUES('<SiteSurveyData>
  <SurveyQuestionAnswers>
    <QuestionGUID>61</QuestionGUID>
    <Answer>XXXXXXX</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>62</QuestionGUID>
    <Answer>XXX</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>64</QuestionGUID>
    <Answer>Both</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>63</QuestionGUID>
    <Answer>aal5snap</Answer>
  </SurveyQuestionAnswers>
  <SurveyQuestionAnswers>
    <QuestionGUID>81</QuestionGUID>
    <Answer>00</Answer>
  </SurveyQuestionAnswers></SiteSurveyData>');

SELECT
    n.v.value('./QuestionGUID[1]','NVARCHAR(256)') AS QuestionGUID,
    n.v.value('./Answer[1]','NVARCHAR(256)') AS Answer
FROM
    @t AS t
    CROSS APPLY t.x.nodes('SiteSurveyData/SurveyQuestionAnswers[QuestionGUID="61" or QuestionGUID="62"]') AS n(v)

结果就是您想要的(两行XXXXXXXXXX作为答案)。这将使用XPath表达式查找SurveyQuestionAnswers,其中QuestionGUID子级为61或62。