Question

I have a table named Options. have Three fields Caption, OptionID, ParentOptionID. it contains some records like :

OptiondID        Caption        ParentOptionID
        1        Entry          0
        2        Sale           1
        3        Sale Invoice   2
----------------------------------------------
I want the result as :

OptiondID        Caption                        ParentOptionID
        1        Entry                          0
        2        Entry - Sale                   1
        3        Entry - Sale - Sale Invoice    2
-----------------------------------------------
Option Caption of its parent option - added in current Options Caption, and it should be nested.

This is the query that I have tried:

;with MyRelation as ( 

  -- Anchor member definition 
  select OID, Cast(Caption as Varchar(1000)) as Caption, POID, iid 
  from #tmpOptions as e 

  UNION ALL 

  -- Recursive member definition 
  select e.OID, Cast(e.Caption + '-' + r.Caption as Varchar(1000)) as Caption, e.POID, e.iid 
  from #tmpOptions as e join MyRelation R on e.POID = R.OID

) 

-- Statement that executes the CTE 
select OID, Caption, POID, iid 
from MyRelation
Was it helpful?

Solution

Could you tried with below query

;WITH MyRelation AS ( 
  SELECT OptiondID, convert(varchar(max), Caption) AS Caption, ParentOptionID
  FROM Options
  WHERE  ParentOptionID = 0
  UNION ALL 
  SELECT Options.OptiondID, MyRelation.Caption + ' - ' + Options.Caption, Options.ParentOptionID
  FROM Options
  INNER JOIN MyRelation ON Options.ParentOptionID = MyRelation.OptiondID
  WHERE Options.ParentOptionID <> 0
) 
SELECT * FROM MyRelation
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top