树形结构的数据存储和数据库表设计

ID int 主键

OBJECTNAME nvarchar(50) 对象名称

OBJECTTYPE  nvarchar(1)  对象级别

PARENTID int 对象父ID

其实对象级别这个字段可以要也可以不要,只是这样清晰些。可以知道你的树有多少级。下面是一般的树形结构:

树形结构的表结构如下:

/********* 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)就可以输入所有记录。

 

posted @ 2010-10-22 14:25  anny0320  阅读(2176)  评论(1编辑  收藏  举报