【问题标题】:select rownumber in xquery and convert it to sql rows在 xquery 中选择 rownumber 并将其转换为 sql 行
【发布时间】:2013-01-02 07:16:12
【问题描述】:

我有一个表格,我以 xml 格式保存用户的搜索结果行,如下所示:

<row id="5083" />
<row id="5085" />
<row id="5087" />
<row id="5090" />
<row id="5094" />
... (about 500,000 rows)

其中每个行元素包含将显示在结果页面中的结果记录的 id。 现在我需要选择一个特定页面的 ID,例如第 2 页(第 10 个元素到第 20 个元素)

第一个问题是如何在 xquery 中获得该结果? 我尝试使用 position() 函数,但它没有用...

select @results.query('for $x in (row)
where $x/position() > 10
return ($x)')

第二个问题是如何将我的结果 id 作为 sql 行而不是 xmlnodelist ?

【问题讨论】:

    标签: sql sql-server xml sql-server-2008 xquery


    【解决方案1】:

    您可以使用nodes() method 分解您的XML,并使用value() method 提取属性id 的值。

    SQL Fiddle

    查询 1

    declare @results xml = '
    <row id="5083" />
    <row id="5085" />
    <row id="5087" />
    <row id="5090" />
    <row id="5094" />'
    
    select T.N.value('@id', 'int') as id
    from @results.nodes('row[position() >= 2 and position() < 4]') as T(N)
    

    Results

    |   ID |
    --------
    | 5085 |
    | 5087 |
    

    【讨论】:

      【解决方案2】:

      for $x in (row) where $x/position() > 10 return ($x)
      

      $x 遍历第 10 个之后的所有行子代,但每个子代都返回一个长度为 1 且只有一个行元素的序列,因此 $x/position() 始终为 1。

      你可以使用

      row[position() >=10 and position() < 20]
      

      这将返回位置 10 到 19 中的元素。如果您只想要 id 而不是元素节点,那么

      row[position() >=10 and position() < 20]/string(@id)
      

      【讨论】:

      • 感谢您的回答...帮助很大...但字符串函数出现异常:XQuery [query()]: The XQuery syntax '/function()' is not supported。
      • 那么你必须使用非标准或损坏的 xquery 引擎,但在这种情况下你可能可以省略 string() 函数并在最后使用/@id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2018-03-11
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      相关资源
      最近更新 更多