本文給大家介紹有關(guān)數(shù)據(jù)庫SQL遞歸查詢?cè)诓煌瑪?shù)據(jù)庫中的實(shí)現(xiàn)方法,具體內(nèi)容請(qǐng)看下文。
比如表結(jié)構(gòu)數(shù)據(jù)如下:
Table:Tree
ID Name ParentId
1 一級(jí) 0
2 二級(jí) 1
3 三級(jí) 2
4 四級(jí) 3
SQL SERVER 2005查詢方法:
- //上查
- with tmpTree
- as
- (
- select * from Tree where Id=2
- union all
- select p.* from tmpTree inner join Tree p on p.Id=tmpTree.ParentId
- )
- select * from tmpTree
- //下查
- with tmpTree
- as
- (
- select * from Tree where Id=2
- union all
- select s.* from tmpTree inner join Tree s on s.ParentId=tmpTree.Id
- )
- select * from tmpTree
新聞熱點(diǎn)
疑難解答
圖片精選