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]
/****创建自定义函数****/
CREATE FUNCTION dbo.fGetTreeTable
(
@ID int= null
)
RETURNS @Tab TABLE(ID int, PID int, Name varchar(10), Lev int)--返回结果的表结构
AS
BEGIN
Declare @lev int
Set @lev=0
While @lev=0 or @@ROWCount>0
Begin
Set @Lev=@Lev+1
Insert @Tab(ID, PID, Name, Lev)
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))
order by ID
End
RETURN
END