2011-03-30 69 views
3

所有遞歸結果我有一個表categories如何顯示與HIERARCHYID SQL

ID | NAME     | PARENT ID | POSITION | LEVEL  | ORDER 
---------------------------------------------------------------------------- 
1 | root     | -1   | 0x   | 0   | 255 
2 | cars     | 1   | 0x58  | 1   | 10 
5 | trucks    | 1   | 0x68  | 1   | 10 
13 | city cars    | 2   | 0x5AC0  | 2   | 255 
14 | offroad cars   | 2   | 0x5B40  | 2   | 255 

其中:

ID int ident 
NAME nvarchar(255) 
PARENT ID int 
POSITION hierarchyid 
LEVEL hierarchyid GetLevel() 
ORDER tinyint 

此表model指定型號名稱和它所屬的類別。例如:

ID | NAME  | CATEGORY 
----------------------------- 
1 | Civic  | 13 
2 | Pajero | 14 
3 | 815  | 5 
4 | Avensis | 13 

其中:

ID int ident 
NAME nvarchar(255) 
CATEGORY int link to ID category table 

我所試圖做的是能夠顯示:

  1. 所有型號 - 將會顯示所有車型,從根遞歸,
  2. 類別cars(包括汽車)
  3. 模型城市汽車(或其兒童如果有的話)

如何使用hierarchyid進行這種過濾以及如何使用模型連接結果表格?這是一個快速的方法,如何顯示特定級別的所有模型結果?

回答

4

我相信這會給你你正在尋找:

declare @id hierarchyid 

select @id = Position from Categories where Name = 'root' -- or 'cars', 'city cars', etc. 

select m.* 
from Models m 
    join Categories c on m.Category = c.ID 
where c.Position.IsDescendantOf(@id) = 1 

有關IsDescendantOf方法等詳細信息hierarchyid方法,檢查method reference