一般的な例を次に示します。コピーして貼り付けて実行すると、出力が表示されます。これが機能する場合は、テーブルと列の値を変更して、状況に合わせて機能させることができるはずです。
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');