SRC:http://blog.joycode.com/mmkk/archive/2004/05/13/21428.aspx
樹形結構是應用中常用的資料結構,最簡單的設計類似:
id,name,parent_id
這種最簡單的設計通常需要結合遞迴來最終形成樹形UI,而且,對於要取得某一個節點的所有下級節點也不是很方便,
出於這種考慮,使用如下UDF來簡化這種操作:
--取得樹形結構中當前節點的所有下級節點
CREATE FUNCTION [dbo].[GetChildCategories] (@parent_id int)
RETURNS @work Table (num int IDENTITY(1,1),category_id int) AS
BEGIN
declare @childrenCount int,@currCategory_id int,@num int
set @num = 1
insert @work
select category_id
from Category_Classification
where parent_id = @parent_id
set @childrenCount = @@ROWCOUNT
while (@num <= @childrenCount)
Begin
select top 1 @currCategory_id = category_id
From @work
Where num = @num
insert @work
select category_id
From Category_Classification
where parent_id = @currCategory_id
set @childrenCount = @childrenCount + @@ROWCOUNT
set @num = @num + 1
End
Return
END
主要是將一個遞迴操作轉化為一個單一的迴圈操作,就這幾句代碼也不知道該怎麼寫注釋了,
未有大資料量測試.