您正在为线程讨论板创建数据库模式的图像。有没有一种有效的方法来为给定的线程选择正确排序的列表?我编写的代码虽然不符合我喜欢的方式。递归SQL CTE和自定义排序顺序
比方说,你有这样的数据:
ID | ParentID ----------------- 1 | null 2 | 1 3 | 2 4 | 1 5 | 3
所以结构应该是这样的:
1 |- 2 | |- 3 | | |- 5 |- 4
理想的情况下,在代码中,我们希望结果集中出现在下面的命令:1,2,3,5,4
问题:随着CTE我写它实际上被返回为:1,2,4,3,5
我知道这很容易通过使用LINQ进行分组/排序,但我不愿意在内存中执行此操作。这似乎是在这一点上,虽然最好的解决办法...
这里是CTE我目前正在使用:
with Replies as (
select c.CommentID, c.ParentCommentID 1 as Level
from Comment c
where ParentCommentID is null and CommentID = @ParentCommentID
union all
select c.CommentID, c.ParentCommentID, r.Level + 1 as Level
from Comment c
inner join Replies r on c.ParentCommentID = r.CommentID
)
select * from Replies
任何帮助,将不胜感激;谢谢!
我是新来的SQL,并没有听说过有关hierarchyid数据类型。从 this comment阅读后,我决定将其纳入我的设计。如果我取得了成功,我将在今晚尝试这个实验并发布更多信息。
更新
从我的样本数据,采用dance2die的建议 返回的结果:
ID | ParentID | Level | DenseRank ------------------------------------- 15 NULL 1 1 20 15 2 1 21 20 3 1 17 22 3 1 22 15 2 2 31 15 2 3 32 15 2 4 33 15 2 5 34 15 2 6 35 15 2 7 36 15 2 8
sql gods从你的声明中发出愤慨 – Shawn 2009-02-19 16:44:38