CatID parID catName
1 -1 A
2 1 B
3 2 C
4 3 D
我想寫一個查詢,返回字符串格式的父子關係。請幫我用遍歷查詢
在上表中,catName具有parentId -1,這意味着它沒有父項。 B有parentID 1,這意味着A是它的父代。
所以finaly字符串是這樣
A=>B=>c=>D
這是我要生成一個查詢的方式。
我會通過CatID,它會遍歷,直到它得到-1。
CatID parID catName
1 -1 A
2 1 B
3 2 C
4 3 D
我想寫一個查詢,返回字符串格式的父子關係。請幫我用遍歷查詢
在上表中,catName具有parentId -1,這意味着它沒有父項。 B有parentID 1,這意味着A是它的父代。
所以finaly字符串是這樣
A=>B=>c=>D
這是我要生成一個查詢的方式。
我會通過CatID,它會遍歷,直到它得到-1。
declare @CatID int;
set @CatID = 4;
with C as
(
select parID,
cast(catName as varchar(max)) as catName
from YourTable
where CatID = @CatID
union all
select T.parID,
T.catName + '=>' + C.catName
from YourTable as T
inner join C
on T.CatID = C.parID
)
select catName
from C
where parID = -1
作爲部分答案,它聽起來像你需要一個遞歸查詢。 Here是一個StackOverflow線程,其中包含有關遞歸查詢的一些很好的信息。至於如何使用查詢將其轉換爲單個字符串,我不知道...該部分可能更適合編程語言。
您需要定義函數,然後在遞歸循環中調用它。
您可以使用MPTT (Modified Preorder Tree Traversal)來存儲嵌套樹或分層數據。
this article描述瞭如何在單個查詢中獲得層級「breadcrumb」。
是否使用實體框架?還是直接ADO.NET? – McGarnagle
直ADO.net – NoviceToDotNet