树形结构一般用于无限级分类,无论你使用Java,.Net,PHP,Python等语言平台进行开发应用,树形结构都是很常用的结构设计之一。
本文主要解决树形结构的数据存储和数据库表设计。欢迎你可以根据你的应用,提出您的见解!以供讨论!
树形结构的数据存储
树形结构的表结构如下:
/********* Object: Table [dbo].[Tree] ******/
Create TABLE [dbo].[Tree] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[PID] [int] NULL ,
[Name] [varchar] (10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
Create CLUSTERED INDEX [IX_Tree] ON [dbo].[Tree]([PID]) ON [PRIMARY]
GO
Alter TABLE [dbo].[Tree] WITH NOCHECK ADD
CONSTRAINT [PK_Tree] PRIMARY KEY NONCLUSTERED
(
[ID]
) ON [PRIMARY] ,
CONSTRAINT [子ID不能等于父ID] CHECK ([ID] <> [PID])
GO
Alter TABLE [dbo].[Tree] ADD
CONSTRAINT [FK_Tree_Tree] FOREIGN KEY
(
[PID]
) REFERENCES [dbo].[Tree] (
[ID]
)
GO
树形结构数据库表查询
不用嵌套调用,直接用一个语句就可以生成树,用临时表写了一个存储过程,改写为一个表值函数,供大家参考:
查询树表语句的表值函数如下:
29/********* 对象: 用户定义的函数 dbo.fGetTreeTable ******/
30Create FUNCTION dbo.fGetTreeTable
31 (
32 @ID int= null
33 )
34RETURNS @Tab TABLE(ID int, PID int, Name varchar(10), Lev int)
35AS
36 BEGIN
37 Declare @lev int
38 Set @lev=0
39
40 While @lev=0 or @@ROWCount>0
41 Begin
42 Set @Lev=@Lev+1
43 Insert @Tab(ID, PID, Name, Lev)
44 Select ID, PID, Name, @Lev From Tree Where (@Lev=1 and ((PID=@ID) or (@ID is null and PID is null))) or (PID in (Select ID From @Tab Where Lev=@Lev-1))
45 order by ID
46 End
47 RETURN
48 END
49
50GO
51
52--实际数据
53Insert Tree(PID, Name) values(null, 公司)
54Insert Tree(PID, Name) values(3, IT)
55Insert Tree(PID, Name) values(1, Fin)
56Insert Tree(PID, Name) values(5, XZ)
57Insert Tree(PID, Name) values(1, HR)
58GO
直接查询Select * from dbo.fGetTreeTable(null)就可以输入所有记录。
转载于:https://blog.51cto.com/lynn0917/378845