2015-06-02 152 views
0

我無法找到解決方案來解決我的問題,我希望對別人來說很容易。XML值frm基於另一個節點值的少數節點

下面是我的XML的一部分:

<Income>  
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test1</Description> 
    </IncomeItem> 
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test2</Description> 
    </IncomeItem> 
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test3</Description> 
    </IncomeItem> 
</Income> 

我需要一個像輸出:test1 test2 test3

會有更多類型的TypeId所以Description值必須基於TypeId

僞代碼是這樣:

Select Decsription From XML where TypeId = 29 
+0

請不要只問我們要解決的問題爲您服務。告訴我們你是如何試圖自己解決問題的,然後向我們展示結果是什麼,並告訴我們爲什麼你覺得它不起作用。請參閱「[您嘗試過什麼?](http://whathaveyoutried.com/)」,以獲得一篇您最近需要閱讀的優秀文章。 –

+0

@John Saunders,謝謝你的建議,下次再做。 – PawelCz

回答

1

這是一種可能的方式:

declare @xml XML = '<Income>  
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test1</Description> 
    </IncomeItem> 
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test2</Description> 
    </IncomeItem> 
    <IncomeItem> 
     <TypeId>29</TypeId> 
     <Description>test3</Description> 
    </IncomeItem> 
</Income>' 

SELECT x.value('Description[1]','varchar(max)') as 'description' 
FROM @xml.nodes('//IncomeItem[TypeId=29]') i(x) 

如果你想Description要連接的值作爲一個排,一個可能的方式是使用XQuery for循環(如果需要,concat()函數在值之間添加空格):

SELECT @xml.query('for $d in //IncomeItem[TypeId=29]/Description return concat($d, " ")') 
      .value('.','varchar(max)') as 'description' 

SQL Fiddle

參考:[MSDN] FLWOR Statement and Iteration (XQuery)

+0

謝謝@ har07。但是這會返回多個值。我需要把它作爲一個值來設置其他值等於這個值。有什麼建議麼? – PawelCz

+0

@richardpawel你可以使用xquery循環將所有相關的'Description'連接成一個值,檢查我的更新是否有詳細的查詢 – har07

+0

它的工作原理,非常感謝你@ har07 – PawelCz

相關問題