--在SQL Server 中其实提供了CTE[公共表表达式]来实现递归:
- Declare @Id Int
- Set @Id = 24; ---在此修改父节点
- With RootNodeCTE(Id,ParentId)
- As
- (
- Select Id,ParentId From Dept Where ParentId In (@Id)
- Union All
- Select Dept.Id,Dept.ParentId From RootNodeCTE
- Inner Join Dept
- On RootNodeCTE.Id = Dept.ParentId
- )
- Select * From RootNodeCTE
表结构(数据为纵向的):
/****** Object: Table [dbo].[Sys_Role] Script Date: 2015/2/16 13:17:55 ******/ SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO
CREATE TABLE [dbo].[Sys_Role](
[ID] [nvarchar](36) [PRIMARY] NOT NULL,
[RoleName] [nvarchar](20) NOT NULL,
[ParentID] [nvarchar](36) NULL,
[UpdateBy] [nvarchar](50) NULL,
[UpdateDate] [datetime] NULL)
时间: 2024-11-06 14:57:02