我有一个名为 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