What is the significance of [1] in Xquery

混江龙づ霸主 提交于 2019-12-07 13:25:31

问题


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.



来源:https://stackoverflow.com/questions/10079628/what-is-the-significance-of-1-in-xquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!