Is there a way to number records extracted from a database?

I need to extract data from my relational database as XML, and I need to assign a number to each record that I extract. I wrote the following XQuery...

<myRecords> {
    let $i := 0
    for $Territories in collection("Northwind.dbo.Territories")/Territories
    let $i := $i + 1
    return
        <territory rec_count="{$i}">
            {$Territories/TerritoryDescription/text()}
        </territory>
} </myRecords>

... I don't get the result I expected:

<myRecords>
    <territory rec_count="1">Westboro</territory>
    <territory rec_count="1">Bedford</territory>
    <territory rec_count="1">Georgetown</territory>

The record number isn't incremented. Why?

XQuery is a functional language without side effects — you can't really create a notion of state in XQuery as you might in Java or C#, for example. In some cases, you can simulate state using a recursive function, but to solve this problem there is a much simpler solution: you can use a positional variable. Here's the XQuery:

<myRecords> {
    for $Territories at $i in collection("Northwind.dbo.Territories")/Territories
    return
        <territory rec_count="{$i}">
            {$Territories/TerritoryDescription/text()}
        </territory>
} </myRecords>

And here's the (hoped-for) result:

<myRecords>
    <territory rec_count="1">Westboro</territory>
    <territory rec_count="2">Bedford</territory>
    <territory rec_count="3">Georgetow</territory>


Next Question!

Can I use fn:collection() to retrieve the URL of a document in a folder?

Submit Your DataDirect XQuery Tip or Trick

Tell us your XQuery Tip or Trick – if it gets published on our site, you’ll receive a

$10.00 Amazon.com
Gift Certificate!

Submit your tip or trick today.