What is the significance of [1] in Xquery

2019-05-10 17:05发布

问题:

I am new to xquery in SQL Server.

I have often come across xquery expressions using [1] with attributes.

Can somebody please explain what does it mean?

Here is a example

declare @aa xml
set @aa='<data>
  <row>
    <Value>1</Value>
    <Text>Masters</Text>
  </row>
  <row>
    <Value>2</Value>
    <Text>Transactions</Text>
  </row>
  <row>
    <Value>3</Value>
    <Text>Misch. Reports</Text>
  </row>
</data>'


select a.f.value('Value[1]','varchar(50)'),   --  why [1] here ?
   a.f.value('Text[1]','varchar(50)')         --  and here too..
 from @aa.nodes('/data/row') as a(f)

Thanks n Regards

回答1:

In this case you're saying you want the first Value element for the current /data/row and the first Text element for the same. If you put a [2] there it will mean the second one. By putting a [1] even where you know there will be only one row, you make it feel safe that only one element will enter the value function.



回答2:

In XPath the [expression] syntax denotes a predicate on the location path. [1] is the abbreviated syntax for [position()=1], which means 'the first element'. In SQL Server use of XPath the [1] (or any other predicate that deterministically filters to at most one element) is required because it transforms the XPath expression from one that returns any number of elements to one that deterministically returns 0 or 1 elements, thus transforming into a scalar expression, which is what .value() requires:

The XQuery must return at most one value.