在做考題的的時候,涉及到分類,雖然不是無限級的,但是,為了以後擴展用,想做成無限級,在網上找找了,一個用存儲過程作的,雖然添加,編輯,移動,用的是存儲過程,可是在讀出來的時候只用了一條Select 語句,感覺挺爽的,下面我把存儲過程列出來,我只用到了添加,編輯,沒有用到移動。
1,表結構
===================================================
表結構:
表名:Tb_Column
表結構(所有字段非空):
Column_ID int 主鍵(注:非標識)
Column_Name nvarchar(50)分類名稱
Parent_ID int 父分類ID(默認值0)
Column_Path nvarchar(1000) 分類路徑
Column_Depth int分類深度(默認值0)
Column_Order int排序(默認值0)
Column_Intro nvarchar(1000)分類說明
================================================
2.添加的存儲過程
CREATE PROCEDURE sp_Column_Insert
(
@Parent_ID int,
@Column_Name nvarchar(50),
@Column_Intro nvarchar(1000)
)
AS
Declare @Err As int
Set @Err=0
Begin Tran
--通過現有記錄獲取欄目ID
Declare @Column_ID As int
Declare @Column_Depth As int
Select @Column_ID = Max(Column_ID) From Tb_Column
IF @Column_ID Is Not Null
Set @Column_ID = @Column_ID+1
Else
Set @Column_ID = 1
--判斷是否是頂級欄目,設置其Column_Path和Column_Order
Declare @Column_Path As nvarchar(1000)
Declare @Column_Order As int
IF @Parent_ID = 0
Begin
Set @Column_Path =Ltrim(Str(@Column_ID))
Select @Column_Order = Max(Column_Order) From Tb_Column
IF @Column_Order Is Not Null
Set @Column_Order = @Column_Order + 1
Else --如果沒有查詢到記錄,說明這是第一條記錄
Set @Column_Order = 1
--深度
Set @Column_Depth = 1
End
Else
Begin
--獲取父節點的路徑和深度
Select @Column_Path = Column_Path ,@Column_Depth = Column_Depth From Tb_Column Where
Column_ID=@Parent_ID
IF @Column_Path Is Null
Begin
Set @Err = 1
Goto theEnd
End
--獲取同父節點下的最大序號
Select @Column_Order = Max(Column_Order) From Tb_PicColumn Where Column_Path like
''+@Column_Path+'|%' Or Column_ID = @Parent_ID
IF @Column_Order Is Not Null --如果序號存在,那麼將該序號後的所有序號都加1
Begin
--更新當前要插入節點後所有節點的序號
Update Tb_Column Set Column_Order = Column_Order +1 Where Column_Order
>@Column_Order
--同父節點下的最大序號加上1,構成自己的序號
Set @Column_Order = @Column_Order + 1
End
Else
Begin
Set @Err=1
Goto theEnd
End
--父節點的路徑加上自己的ID號,構成自己的路徑
Set @Column_Path = @Column_Path + '|' + Ltrim(Str(@Column_ID))
--深度
Set @Column_Depth = @Column_Depth+1
End
Insert Into Tb_Column(Column_Name,Parent_ID,Column_Path,Column_Depth,Column_Order,Column_Intro)
Values(@Column_Name,@Parent_ID,@Column_Path,@Column_Depth,@Column_Order,@Column_Intro)
IF @@Error<>0
Begin
Set @Err=1
Goto theEnd
End
--更新當前記錄之後的記錄的ORDER
--Update Tb_Column Set Column_Order = Column_Order+1 Where Column_Order > @Column_Order
theEnd:
IF @Err=0
Begin
Commit Tran
Return @Column_ID
End
Else
Begin
Rollback Tran
Return 0
End
GO待續.......