Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a generic example. You can copy, paste and run it and it will show you the output. If this works you should be able to modify the table and column values to get it to work for your situation.</p> <pre><code>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 + ' &gt; ','') + 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 + ' &gt; ','') + 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'); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload