递归 CTE 问题
我试图在 SQL Server 中使用递归 CTE 从包含底层树结构的表构建谓词公式。 例如,我的表格如下所示:
Id | Operator/Val | ParentId
--------------------------
1 | 'OR' | NULL
2 | 'AND' | 1
3 | 'AND' | 1
4 | '>' | 2
5 | 'a' | 4
6 | 'alpha' | 4
...
...表示 ((a > alpha) AND (b > beta)) OR ((c > gamma) AND (a < delta))。
ParentId是对父节点同表中Id的引用。
我想编写一个查询来从表中构建这个字符串。是否可以?
谢谢
I am trying to use a recursive CTE in SQL Server to build up a predicate formula from a table containing the underlying tree structure.
For example, my table looks like:
Id | Operator/Val | ParentId
--------------------------
1 | 'OR' | NULL
2 | 'AND' | 1
3 | 'AND' | 1
4 | '>' | 2
5 | 'a' | 4
6 | 'alpha' | 4
...
...which represents ((a > alpha) AND (b > beta)) OR ((c > gamma) AND (a < delta)).
ParentId is a reference to the Id in the same table of the parent node.
I want to write a query which will build up this string from the table. Is it possible?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于生产环境,如果性能和递归深度限制(32 级)不成问题,您可能希望使用递归函数来简化。
然而,这是一个非常干净且非常有效的 CTE 解决方案(请注意,它将接受任意数量的“树”,并为没有父项的每个项目返回一个结果):
For a production environment, you may want to go with a recursive function for simplicity if performance and recursion depth limits (32 levels) is not a problem.
However, here's a quite clean and pretty efficient solution with CTEs (note that it will accept any number of "trees" and return one result for each item which has no parent):
我发现了一些东西,但看起来很恶心。使用递归函数,您可以更轻松地完成此操作...
输出
如果您想查看递归函数,请给我留言,我们可以看一下。
编辑:递归函数
看看这有多容易
I found something, but it looks pretty nasty. You would be able to do this a lot easier using a recursive fundtion...
OUTPUT
If you would rather want to look at a recursive function, give me a shout and we can have a look.
EDIT: Recursive Function
Have a look at how much easier this is
是的,可以这样做,但问题不在于 CTE,请使用 PIVOT 检查
通过此链接了解更多信息
http://msdn.microsoft.com/en -us/library/ms177410.aspx
本文档中的一些示例与您的问题类似
Yes it is possible to do it but the problem is not the CTE, check it with PIVOT
read more about it from this link
http://msdn.microsoft.com/en-us/library/ms177410.aspx
some examples in this documentation is similar with your problem
我不知道如何进行双递归,但希望其中的中间 CTE 之一能让您走上正确的道路:
I couldn't figure out how to do the double-recursion, but hopefully one of the intermediate CTEs in this will set you on the right track: