这是一个通用示例。您可以复制、粘贴和运行它,它会显示输出。如果这可行,您应该能够修改表和列值以使其适用于您的情况。
If Object_ID('dbo.Services') Is Not Null Drop Table [dbo].[Services];
Create Table [dbo].[Services] (ServiceID Int Identity(1,1) NOT NULL, ParenServiceID Int NULL, ServiceDescription Nvarchar(250) NULL);
Insert [dbo].[Services]
Select null, 'Automobiles'
Union All
Select 1, 'Germany'
Union All
Select 2, 'BMW'
Union All
Select 3, '4 Wheel Drive'
Union All
Select 1, 'Italy'
Union All
Select 5, 'FIAT'
Union All
Select 4, 'X3'
Union All
Select 6, 'Front Wheel Drive'
Union All
Select 8, 'Punto';
With recurCTE As
(
Select h.ServiceID, h2.ParenServiceID As nextParent, Convert(Varchar(max),Isnull(h2.ServiceDescription + ' > ','') + h.ServiceDescription) As Hierarchy
From [dbo].[Services] h
Left Join [dbo].[Services] h2
On h.ParenServiceID = h2.ServiceID
Union All
Select rc.ServiceID, h.ParenServiceID As nextParent, Convert(Varchar(max),Isnull(h.ServiceDescription + ' > ','') + rc.Hierarchy) As Hierarchy
From recurCTE rc
Join [dbo].[Services] h
On rc.nextParent = h.ServiceID
), orderedResults As
(
Select ServiceID, Hierarchy
From (Select Row_Number() Over (Partition By ServiceID Order By Len(Hierarchy) Desc) As lenPriID,
ServiceID,
Hierarchy
From recurCTE) As n
Where lenPriID = 1
)
Select h.*, o.Hierarchy
From orderedResults o
Join [dbo].[Services] h
On o.ServiceID = h.ServiceID
Where ServiceDescription In ('X3','Punto');