0

I cannot find solution to my problem, I hope it will be easy to somebody.

Below is part of my 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>

I need output like: test1 test2 test3

There will be more types of TypeId so value of Description has to be based on TypeId.

Pseudo code would look like :

Select Decsription From XML where TypeId = 29
2
  • Please don't just ask us to solve the problem for you. Show us how you tried to solve the problem yourself, then show us exactly what the result was, and tell us why you feel it didn't work. See "What Have You Tried?" for an excellent article that you really need to read. Commented Jun 2, 2015 at 14:26
  • @John Saunders, thanks for an advice, will do next time. Commented Jun 2, 2015 at 14:50

1 Answer 1

1

This is one possible way :

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)

If you want Description values to be concatenated as one row, one possible way is using xquery for loop (and concat() function to append space between values, if needed) :

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

SQL Fiddle

For reference : [MSDN] FLWOR Statement and Iteration (XQuery)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @har07. But this returns more than one value. I need to have this as one value to set other value equal this value. Any suggestions?
@richardpawel you can use xquery loop to concatenate all relevant Description into one value, check my update for detailed query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.