我有一个组织名称表,其结构如下:
CREATE TABLE [dbo].[DP_ORG_OrganizationUnit](
[GID] [uniqueidentifier] NULL,
[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[Code] [nvarchar](100) NULL,
[Name] [nvarchar](100) NULL,
[LastUpdated] [datetime] NULL,
[ManagedBy] [int] NULL, **SELF REFERENCING ID {For parent - child }***
[Manager] [int] NULL,
CONSTRAINT [PK_DP_ORG_OrganizationUnit] 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]
要求是我需要创建一个视图,该视图将为我提供每个组织单元的完整路径。
ID CODE NAME MANAGEDBY MANAGER
1 HO Head Office 0
2 IT Information Technology 1
3. FI Finance 1
4. SP IT Support 2
5. M Mergers 3
我需要数据来作为
1. Head Office
2. Head Office/Information Technology
3. Head Office/Finance
4. Head Office/Information Technology/IT Support
5. Head Office/Finance/Mergers
我想直接将其拉入报告的标准表单中,以便可以从一个组合中选择子部门!我怎样才能以任何方式从 TSQL(ms sql 2005)得到这个。提前感谢任何解决方案。
解决方案#1:
with cteAnchor as (
select ID,CAST(Name as nvarchar(500)) as Name
from DP_ORG_OrganizationUnit
where ManagedBy = 21)
, cteRecursive as
(select ID,CAST(Name as nvarchar(500))as Name
from cteAnchor
union all
select t.ID,CAST( r.Name + ' / ' + t.Name AS nvarchar(500))
from DP_ORG_OrganizationUnit t
join cteRecursive r on t.ManagedBy = r.ID)
select * from cteRecursive;