Sql server 中的 FLWOR 计数命中数

编程入门 行业动态 更新时间:2024-10-10 07:24:20
本文介绍了Sql server 中的 FLWOR 计数命中数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SQL Server 2008 R2.我的问题是我想计算使用 FLWOR 从 XQuery 查询中收到的命中数.对于每个命中,我想要一个连续的数字,例如:0,1,2,3,4...

I am using SQL Server 2008 R2. My problem is that I want to count number of hits that i receive from XQuery query using FLWOR. For each hit, I want a consecutive number, like: 0,1,2,3,4...

我的查询:

select @xml.query('for $s at $count in /Root/Persons/Person
return <Person ID="{$count}">{$s}</Person>')

这里唯一的问题是 SQL Server 不支持此功能,我收到错误消息:

The only problem here is this is not supported in SQL Server and I receive an error:

Msg 9335, Level 16, State 1, Line 16
XQuery [query()]: The XQuery syntax 'at' is not supported.

我也尝试过使用 let 关键字并定义新变量,但我不知道如何在每次迭代中增加该变量的值?

I've also tried with let keyword and define new variable but I don't know how to increase value of that variable with each iteration?

感谢您的所有回答,Frenky

Thanks for all the answers, Frenky

推荐答案

XQuery 是一种声明性语言,你不能使用 let 增加一个计数器.

XQuery is a declarative language, you cannot use let to increment a counter.

对于缺少的 at 功能,一个相当老套的解决方法是计算前面的兄弟 <person/> 标签:

A rather hackish workaround to the missing at feature would be to count the preceding sibling <person/> tags:

for $person in /Root/Persons/Person
let $count := count($person/preceding-sibling::Person) + 1
return <Person ID="{$count}">{$person}</Person>

请注意,如果执行引擎没有优化(它可能不会这样做),由于重复的前面的兄弟扫描,此代码将具有 O(n^2) 运行时.

Be aware that this code will have O(n^2) runtime if not optimized by the execution engine (which it will probably not do) because of the repeated preceding sibling scans.

编辑:如评论中所述,MS SQL 甚至不支持 preceding-sibling 轴.他们确实支持 << 节点顺序比较运算符,不过.应该完全支持此查询:

Edit: As stated in the comments, MS SQL doesn't even support the preceding-sibling axis. They do support the << node order comparison operator, though. This query should be fully supported:

for $person in /Root/Persons/Person
let $count := count($person/parent::Persons/Person[. << $person]) + 1
return <Person ID="{$count}">{$person}</Person>

顺便说一句,你可能只想粘贴人名,所以最好使用

By the way, you possibly only want to paste the person's name, so better use

(: snip :)
return <Person ID="{$count}">{data($person)}</Person>

这篇关于Sql server 中的 FLWOR 计数命中数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-19 00:07:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Sql   server   FLWOR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!