0

我有一个名为 Options 的表。具有三个字段 Caption、OptionID、ParentOptionID。它包含一些记录,例如:

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.

这是我尝试过的查询:

;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
4

1 回答 1

2

您可以尝试以下查询吗

;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
于 2012-12-19T06:54:25.393 回答