0

Let's say I have a table in SQL Server which contains the results of a query with an inner join.

The following XQuery:

select @code.query
(
'for $s in /root/row
return 
<Foo Language="{data($s/@lang)}" Method="{data($s/@method)}" Returns="{data($s/@returnType)}">
<Bar ReferencedBy="{data($s/@callers)}" Static="{data($s/@static)}" />
</Foo>'
)

And its result:

<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Baz" Static="true" />
</Foo>
<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Bar" Static="false" />
</Foo>

What I would like in fact is the following:

<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Baz" Static="true" />
  <Bar ReferencedBy="Bar" Static="false" />
</Foo>

What's the best way to do this using XQuery in order to avoid resorting to LINQ and a hash table?

1
  • Looks like you need a for loop inside the FOO tag to iterate over the BAR values you want to populate.
    – OMG Ponies
    Jan 28, 2010 at 22:01

1 Answer 1

1

You need to enumerate over all nodes with each language, method and return value before constructing the results

for $lang in distinct-values(/root/row/@lang)
let $nodes := /root/row[@lang=$lang]
for $method in distinct-values($nodes/@method)
let $nodes := $nodes[@method=$method]
for $return in distinct-values($nodes/@returnType)
let $nodes := $nodes[@returnType=$returnType]
return
  <Foo Language="{$lang}"
       Method="{$method}"
       Returns="{$returnType}">
  {
    for $bar in $nodes
    return 
    <Bar ReferencedBy="{data($node/@callers)}"
         Static="{data($node/@static)}" />
  }
  </Foo>

I do not use SQL Server myself, so I can't guarantee that this will work, but it is a valid XQuery solution.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.