2017-08-15 98 views
0

我在SQL表中的下列XML:查詢檢索的XML值在SQL

<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> 

什麼我想查詢的是,我想在/應答的值,其中/ QuestionGUID = 61和62

我嘗試使用這樣的:

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

,但它只是返回第一個QuestionGUID。
我如何編寫查詢以便它返回QuestionGUID 61和62的答案?

或者我只想爲QuestionGuid = 61得到答案。
它並不總是第一個元素,是否可以編寫查詢以便返回QuestionGuid = 61的值?

+0

您可能需要使用遊標。這是一個示例https://stackoverflow.com/questions/19034382/sql-2012-iterate-through-an-xml-list-better-alternative-to-a-while-loop – Si8

+0

如果我只想要所有的與問題= 61返回?它不一定總是第一個。 – user2665372

回答

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表達式尋找SurveyQuestionAnswersQuestionGUID孩子的61或62.

+0

n從哪裏來? n.v.value? – user2665372

+0

@ user2665372當您使用返回節點的函數交叉應用時,您需要分配一個表別名和列別名。這就是節點功能之後的'AS n(v)'。 'n'是tabe別名,'v'是列別名。然後,由於'v'列是一個節點,所以你需要使用'value'函數從中提取一個值。因此'n.v.value(...)'將值函數應用於列「n.v」中的節點。 –