What is the meaning of [1] in Xquery

I am new to xquery in SQL Server.

I often see xquery expressions using [1] with attributes.

Can someone please explain what this means?

Here's an 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)

      

Thank you n Regards

+3


source to share


2 answers


In this case, you are saying that you want to use the first element Value

for the current /data/row

and for the first element Text

. If you put it [2]

, it will mean the second. By putting [1], even if you know there will be only one line, you make sure that only one element will go into the function Value

.



+3


source


In XPath, syntax [expression]

denotes a predicate in a location path. [1]

is a shorthand syntax for [position()=1]

which means "first element". In SQL Server, using XPath for [1]

(or any other predicate that filters at most one element deterministically) is required because it converts an XPath expression from a number that returns any number of elements to a number that deterministically returns 0 or 1 element, converting it to scalar expression, which means .value()

:



XQuery must return at most one value.

+8


source







All Articles