Sql 中的递归研究
CREATE TABLE [dbo].[Test](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[ParentID] [int] NULL,
[Level] [int] NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
WITH F
AS(
SELECT * FROM Test WHERE ID = 5
UNION ALL
SELECT TEST.* FROM Test INNER JOIN F ON TEST.ID = F.ParentID WHERE F.ParentID IS NOT NULL
)
Select * From F
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[ParentID] [int] NULL,
[Level] [int] NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
WITH F
AS(
SELECT * FROM Test WHERE ID = 5
UNION ALL
SELECT TEST.* FROM Test INNER JOIN F ON TEST.ID = F.ParentID WHERE F.ParentID IS NOT NULL
)
Select * From F