TSQL-通过XML序列订购交叉序列
在SQL Server中,当使用 Cross Applion
中时,我如何保证返回数据是由XML列中节点的顺序排序的?
SELECT MC.Id, MC.Name
FROM MyParent MP
CROSS APPLY MP.ChildrenXml.nodes('/d/i') AS CX(CX)
INNER JOIN MyChildren MC
ON MC.Id = CX.value('text()[1]','int')
-- MyParent table...
ChildrenXML
<d><i>1</i><i>3></i><i>2</i></d>
-- MyChildren table...
Id Name
1 Tom
2 Richard
3 Harry
-- Expected output...
Id Name
1 Tom
3 Harry
2 Richard
我能想到的最好的(但感觉不好的解决方案)是...
; WITH ChildIds AS (
SELECT CX.value('text()[1]','int') AS Id,
ROW_NUMBER() OVER (ORDER BY CX.CX) AS RowNum
FROM MyParent MP
CROSS APPLY MP.ChildrenXml.nodes('/d/i') AS CX(CX)
)
SELECT MC.Id, MC.Name
FROM ChildIds CI
INNER JOIN MyChildren MC
ON MC.Id = CI.Id
ORDER BY CI.RowNum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
预先计算元素的位置
而
&lt; i&gt;
- 元素的行计数,sql:column()
One more approach: Pre-Computing the element's position
The idea in short:
CROSS APPLY
to create a tally for each row separatelyTOP()
-clause using the row's count of<i>
-elementstheIndex
to fetch the element's value by its position usingsql:column()
不幸的是,SQL Server不允许您在
.value
调用中使用position()
。相反,您可以通过计算节点来入侵它。
您可以通过将
.value
放入db&lt;&gt;&gt; fiddle
另外
> db&lt;
”
$ i
..
来计数其所有i
儿童节点$ i
节点Unfortunately, SQL Server does not allow you to use
position()
in a.value
call.Instead you can hack it by counting nodes.
You can do it without a CTE, by putting
.value
into theORDER BY
db<>fiddle
Alternatively leave it in the
SELECT
and you can stillORDER BY
that valuedb<>fiddle
The way this works is as follows:
.
to$i
..
and count all itsi
child nodes which...<<
before the$i
node@Charlieface向我指出了我真正想要的答案...尽管我真的很感谢他们的回答时间/努力。
我从未考虑过使用
row_number
作为订单
本身...db&lt;&gt; fiddle
@Charlieface pointed me to the answer I really wanted... although I really appreciate their time/effort with their answer.
I never considered using
ROW_NUMBER
as theORDER BY
itself...db<>fiddle