订购链接列表,结构在SQL或LINQ查询? [英] Ordering a Linked List-Structure in a SQL or LINQ Query?

查看:119
本文介绍了订购链接列表,结构在SQL或LINQ查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,基本上是这样一个数据库:

I have a database that essentially looks like this:

id uniqueidentifier NOT NULL
data nvarchar
nextid uniqueidentifier NULL

这是一个链表,因为每个nextid联结到一个id该表中,除了最后一个,这里nextid为NULL。我知道的第一个节点的ID。

This is a Linked List, as each nextid links to an id in that table, except for the last one, here nextid is NULL. I do know the id of the first node.

我要选择他们都以正确的顺序,因为一开始的ID。

I want to SELECT them all in the correct order, given a start id.

有没有办法这样可以在T-SQL的来完成(编辑:SQL 2008)的或LINQ?

Is there a way this can be done in T-SQL ( SQL 2008) or LINQ?

我知道我可以写code,以做手工在C#中,只是想知道如果我可以在订单已经查询?

I know I can write code to do it manually in C#, just wondering if I can already query in that order?

推荐答案

不知道的[SortOrder的]有什么差别,因为我没有足够的数据来测试它。它可以让你在两个方向进行排序​​。

Not sure of [SortOrder] makes any difference as I don't have enough data to test it. It allows you to sort in both directions.

with cteList as
(
    select id, data, nextid, 1 as [SortOrder]
    from #TableTemp
    where id = 'E8ADAA52-54F8-4FE3-BE59-9852E52B33F5' --id of the 1st item

    union all

    select #TableTemp.id, #TableTemp.data, #TableTemp.nextid, (cteList.[SortOrder] + 1) as [SortOrder]
    from #TableTemp
    join cteList on #TableTemp.id = cteList.nextid
)
select * from cteList
order by [SortOrder] asc

这篇关于订购链接列表,结构在SQL或LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆