0

I have below xml and want to fetch all records as rows. My xml is like below..

<category ccode="ct8">
  <columns>
    <col colcode="cl_prodn" displaytext="Prodname" responsetype="textbox" tooltip="testts" isrequired="" displayorder="1" />
    <col colcode="cl_descs" displaytext="Descs" responsetype="textarea" tooltip="atser" isrequired="on" displayorder="2" />
  </columns>
</category>

I want two rows for category ccode = ct8. Those two rows will show all attributes. I am trying with below query but it returns only one and first.

select CatConfig.value('(category/columns/col/@colcode)[1]', 'varchar(50)') from categories where CategoryId = 8

1 Answer 1

1

There are many ways to shred xml but I believe this may help you out giving some more concepts to the mix:

declare @xml xml = 
'<category ccode="ct8">
  <columns>
    <col colcode="cl_prodn" displaytext="Prodname" responsetype="textbox" tooltip="testts" isrequired="" displayorder="1" />
    <col colcode="cl_descs" displaytext="Descs" responsetype="textarea" tooltip="atser" isrequired="on" displayorder="2" />
  </columns>
</category>'

-- get them one at a time by hunting for specific identifier
select @xml.query('(category/columns/col[@displaytext = "Prodname"])')  -- queries for node
select @xml.value('(category/columns/col[@displaytext = "Prodname"]/@colcode)[1]', 'varchar(max)')  -- gives value of node by description
select @xml.value('(category/columns/col[@displaytext = "Descs"]/@colcode)[1]', 'varchar(max)')


-- get them all at once with the (reference).(column).nodes method applied to an xml value in a table.
declare @X table ( x xml);

insert into @X values (@xml)

select 
    t.query('.')
,   t.value('(@colcode)[1]', 'varchar(max)')
from @X a
 cross apply a.x.nodes('//category/columns/col') as n(t)
Sign up to request clarification or add additional context in comments.

Comments

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.