Friday, March 9, 2012

for xml hierarchy

Hi

I have a table that looks like this

declare @.VC table ( V varchar(100), VC int, depth tinyint)
insert into @.VC values ( 'TN', 1, 1)
insert into @.VC values ( 'TN', 2, 2);

and I have for xml query

select
V as @.value,
(
select VC as '@.value' from @.VC pe where pe.V = n.V
for xml path ('Value'), root('Values'), type
) as ME
from ( select distinct VC from @.VC ) n
for xml path ('Value'), root('Values')

that gives me something like this

<Values>
<Value value="TN">
<ME>
<Values>
<Value value="1" />
<Value value="2" />
</Values>
</ME>
</Value>
</Values>

However I need to reorder the xml to look like this according to depth

<Values>
<Value value="TN">
<ME>
<Values depth = 1>
<Value value="1" />
</Values>
</ME>
<ME>
<Values depth =2>
<Value value="2" />
</Values>
</ME>
</Value>
</Values>

the problem I am having is that depth 2 is not below depth 1 node, is on the same depth with the depth attribute diff.

Is there some way to write the for xml to do this

thanks

P


select
V as "@.value",
(
select pe.depth as "Values/@.depth",
pe.VC as "Values/Value/@.value"
from @.VC pe where pe.V = n.V
for xml path('ME'),type
)
from ( select distinct V from @.VC ) n
for xml path ('Value'), root('Values')

No comments:

Post a Comment