最近在做一個圖書管理系統,涉及到圖書分類的問題。 類別表是book_Catalogs,結構如下 ( fId int, -- 類別編號 fName nvarchar(20), -- 類別名稱 fDescription nvarchar(50), -- 類別描述 fParentId int, -- 父級類別 fIsLeaf bit -- 是否葉子類(圖書只能歸屬于葉子類) ) 類別圖書關系表是book_CatalogBooks,結構如下 ( fCatalogId int, -- 類別編號 fBookId int, -- 圖書編號 )
現在我想通過book_CatalogBooks表查找某一個類別下的所有圖書。無論指定哪個類別,都能找到該類別下的所有圖書,如果該分類下有子分類,還有包括該類所有子類下的圖書。希望能用一個SELECT語句搞定。
|
? |
? |
|
happygong(高興)?于?2005-10-10 17:08:21
|
這種樹狀結構的實現方法不太好 應該使用NodeCode的方法 比如規定以4個字符為單位 0001(父節點) --00010001(子節點) ----000100010001(孫節點) ----000100010002 --00010002 --00010003 這樣記錄的樹狀結構可以使用where nodecode like '00010001%'獲得所有00010001下面的子節點 但是有缺點就是同一級最多有10000個,如果還需要更多,可以選擇已6個字符為單位
|
|
|
zxbyhcsdn(沙子)?于?2005-10-10 17:12:58
|
用動態Sql看看!!
|
|
|
libin_ftsafe(子陌紅塵)?于?2005-10-10 17:14:54
|
一條SQL恐怕有些困難,借助UDF: -------------------------------------------------------------------------------- --創建用戶定義函數 declare function f_getchlid(@fId int) returns @t table(fId int,fName nvarchar(20),fParentId int,fIsLeaf bit,level int) as begin declare @level int set @level = 1
insert into @t select fId,fName,fParentId,fIsLeaf,@level from book_Catalogs where fId=@fId
while @@rowcount!=0 and exists(select * from @t where level=@level and fIsLeaf=0) begin insert into @t select a.fId,a.fName,a.fParentId,a.fIsLeaf,@level+1 from book_Catalogs a,@t b where b.fId=a.fParentId and b.level=@level
set @level = @level+1 end
return end go
--執行查詢 declare @fid int set @fid = 1
select * from book_CatalogBooks where fCatalogId in(select a.fId from dbo.f_getchlid(@fid) a where a.fIsLeaf=1)
|
|
|
zxbyhcsdn(沙子)?于?2005-10-10 17:15:00
|
感覺這個有點的規的樣子!!
|
得到樹的深度存儲過程:
CREATE?PROCEDURE?dbo.SpBoardTreeDepth?
AS?
???declare?@level?int?
???declare?@t?table(boardid?int,pareid?int,boardname?varchar(50),level?int)?
???set?@level?=?1?
???insert?into?@t?select?boardid,pareid,boardname,@level?from?board?where?pareid?=?0?
???while(@@rowcount>0)?
??????begin?
????????set?@level=@level+1?
????????insert?into?@t?
??????????select?a.boardid,a.pareid,a.boardname,@level?from?board?a?
??????????join?@t?b?on?a.pareid?=?b.boardid?where?b.level=@level-1?
??????end?
??????select?boardid,pareid,boardname,level?from?@t?
??????RETURN?
GO?
posted on 2006-09-12 11:15
SIMONE 閱讀(702)
評論(0) 編輯 收藏