如何编写嵌套查询

时间:2012-12-19 05:46:57

标签: sql-server nested-queries nested-query

我有一个名为Options的表。有三个字段标题,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

1 个答案:

答案 0 :(得分: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