2012-03-14 86 views
6

我在SQL Server中有一個表,其中一列是XML數據類型。表中還有其他列不是XML。這裏是存儲在列中的XML的例子:XML數據類型在SQL Server 2008中查詢

<AdultAsthma> 
    <Group> 
    <Question text="Act Score:" ForeColor="Green" /> 
    <Controls> 
     <Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" /> 
     <Control type="TextBox" id="txtActScore" Answer="" /> 
    </Controls> 
    </Group> 
</AdultAsthma> 

我想的是,上表中的其它列和匹配這些列匹配某些值的查詢,我想要得到的來自問題節點的文本屬性和來自控制節點的應答屬性。有人可以幫我弄這個嗎?

編輯

有什麼需要改變,如果我有一個以上的組節點?在這個場景中,我希望每個問題的文本和答案都與每個問題一致。請看下圖:

<AdultAsthma> 
    <Group> 
    <Question text="Act Score:" ForeColor="Green" /> 
    <Controls> 
     <Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" /> 
     <Control type="TextBox" id="txtActScore" Answer="" /> 
    </Controls> 
    </Group> 
    <Group> 
    <Question text="Do You Have Asthma?:" ForeColor="Black" /> 
    <Controls> 
     <Control type="RadioButton" id="rbHaveAsthmaYes" text="Yes" GroupName="Diagnosed" ForeColor="Black" Answer="False" /> 
     <Control type="RadioButton" id="rbHaveAsthmaNo" text="No" GroupName="Diagnosed" ForeColor="Black" Answer="False" /> 
    </Controls> 
    </Group> 
</AdultAsthma> 
+2

給這個好看:http://msdn.microsoft.com/en-us/library/ms178030.aspx – RThomas 2012-03-14 19:16:02

回答

6
declare @T table 
(
    XMLCol xml 
) 

insert into @T values 
('<AdultAsthma> 
    <Group> 
    <Question text="Act Score:" ForeColor="Green" /> 
    <Controls> 
     <Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black"/> 
     <Control type="TextBox" id="txtActScore" Answer="Answer" /> 
    </Controls> 
    </Group> 
</AdultAsthma> 
') 

select XMLCol.value(N'(/AdultAsthma/Group/Question/@text)[1]', 'nvarchar(max)'), 
     XMLCol.value(N'(/AdultAsthma/Group/Controls/Control/@Answer)[1]', 'nvarchar(max)') 
from @T 

更新:

當你需要粉碎的XML,以便多行,你可以在cross apply使用.nodes()

declare @T table 
(
    XMLCol xml 
) 

insert into @T values 
('<AdultAsthma> 
    <Group> 
    <Question text="Act Score:" ForeColor="Green" /> 
    <Controls> 
     <Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" /> 
     <Control type="TextBox" id="txtActScore" Answer="" /> 
    </Controls> 
    </Group> 
    <Group> 
    <Question text="Do You Have Asthma?:" ForeColor="Black" /> 
    <Controls> 
     <Control type="RadioButton" id="rbHaveAsthmaYes" text="Yes" GroupName="Diagnosed" ForeColor="Black" Answer="False" /> 
     <Control type="RadioButton" id="rbHaveAsthmaNo" text="No" GroupName="Diagnosed" ForeColor="Black" Answer="False" /> 
    </Controls> 
    </Group> 
</AdultAsthma> 
') 

select X.N.value(N'(Question/@text)[1]', 'nvarchar(max)'), 
     X.N.value(N'(Controls/Control/@Answer)[1]', 'nvarchar(max)') 
from @T as T 
    cross apply T.XMLCol.nodes(N'/AdultAsthma/Group') as X(N) 
+0

這個很好用!如果我在AdultAsthma節點下有多個組節點,應該更改哪些內容?看我的編輯。 – 2012-03-14 19:43:33

+0

這太酷了!謝謝你,這正是我需要的! – 2012-03-14 20:31:33