ALL IN ONE : 利用存儲過程實現BBS樹形結構的存儲及有回復email通知(不必借助任何組件發Email)功能
發表于:2007-06-30來源:作者:點擊數:
標簽:
BBS的樹形結構一直是大家討論的話題,以前我做都是利用命名規則來實現,這樣的好處是表的冗余字段少,結構清楚,容易理解,但其局限性也很明顯。感謝廖家遠提供算法(實話說,當年算法就沒有學好),我決定采用一下這種算法來實現bbs的樹形結構?;舅悸啡缦?
BBS的樹形結構一直是大家討論的話題,以前我做都是利用命名規則來實現,這樣的好處是表的冗余字段少,結構清楚,容易理解,但其局限性也很明顯。感謝廖家遠提供算法(實話說,當年算法就沒有學好),我決定采用一下這種算法來實現bbs的樹形結構?;舅悸啡缦拢?br>
bbs文章表中有這樣幾個字段:
RootID : 根ID , 新發貼子及其所有子貼都相同。
FatherID: 父ID , 父貼子ID
Layer: 層數 , 貼子在樹中的深度。
OrderNum: 排序基數,關鍵所在,根據它來排序。
基本算法舉例如下:
根16(拿個小的舉例)
id ordernum Layer
1 16 0
2 16+16/2 1 回復第1貼
3 16+16/(2^2) 1 回復第1貼
4 16+16/2+16/(2^3) 2 回復第2貼
5 16+16/(2^2)+16/(2^4) 2 回復第3貼
然后,根據排序的結果是(加上回復的深度,就成了樹狀結構)
id ordernum 深度
1 16 0
3 16+16/(2^2) 1
5 16+16/(2^2)+16/(2^4) 2
2 16+16/2 1
4 16+16/2+16/(2^3) 2
成了這樣的樹:
1
3
5
2
4
根據以上思路,我們設計表如下:
/*BBS文章表*/
if exists (select * from sysobjects where ID = object_id("BBS"))
drop table BBS
go
create table BBS
(
ID int primary key identity not null ,
RootID int default 0 not null ,
FatherID int default 0 not null ,
Layer tinyint default 0 not null ,
ForumID int default 0 not null ,
UserID int default 0 not null ,
Title varchar(255) default "" not null ,
Content text default "" ,
PostTime datetime default ge
tdate() not null ,
FaceID tinyint default 0 not null ,
TotalChilds int default 0 not null ,
OrderNum float default power(2,30) not null ,
Hits int default 0 not null ,
selected bit default 0 not null ,
closed bit default 0 not null ,
IfEmail bit default 0 not null ,
IfSignature bit default 0 not null
)
go
/*BBS注冊用戶表*/
if exists(select * from sysobjects where ID = object_id("BBSUser"))
drop table BBSUser
go
create table BBSUser
(
ID int Primary key identity not null ,
UserName varchar(20) default "" not null ,
Password varchar(10) default "" not null ,
UserType tinyint default 0 not null , --用戶類型,1為斑竹
Email varchar(100) default "" not null ,
HomePage varchar(100) default "" not null ,
I
CQ varchar(20) default "" not null ,
Signature varchar(255) default "" not null , --簽名
Point int default 0 not null , --用戶積分
)
go
表結構定了,剩下的就是怎樣實現。我把所有相關的功能集成在一個存儲過程中,包括貼子本身的存儲,其關鍵是排序基數的生成;父貼子相關字段的更新 ; 根貼相關字段的更新,這些都放到一個事務中,以保持數據的一致性,另外如果父貼要求有回復用email通知,在存儲過程中實現發回復email的功能,而不必借助任何asp或其他的組件。這樣就使所有任務在一個存儲過程中實現。
原文轉自:http://www.kjueaiud.com