2

I have the below table that contains the Application Feature List:

ApplicationFeature

Id Name MenuId

Values are:

1 PatientSearch 2

ApplicationMenu

Id DisplayText Url ParentMenuId

Values are

1 Patient patient NULL

2 PatientSearch search 1

I need to fetch the menu information along with the features. So far I have only been able to get the mapped menu but not the parent menu item as well.

SELECT
AF.Name, AF.Id As FeatureId, AM.Id AS MenuId, AM.DisplayText,AM.Url
FROM 
ApplicationFeature AF 
INNER JOIN ApplicationMeny AM ON AF.MenuId=AM.Id 

My results only show the PatientSearch menu details but don't include the Patient Menu.

How can I cause the query to retrieve parent menu detail too?

Edit:

I need to get build the menu with Parent. In case a parent menu has another parent I need to include that menu also.

-- Parent(Id=2)

  --- SubParent(Id=10 & ParentId=2)

    ----ActualMenuMappedwithFeature(Id=30 & ParentId=10)

In the above case I want result with menu ids 30, 10, 2

Community
  • 1
  • 1
Billa
  • 5,226
  • 23
  • 61
  • 105

2 Answers2

1

Well It's hard to say, what you want to get. But if you want to fetch only one parent, you can do additional join

select
    AF.Name, AF.Id As FeatureId,
    AM.Id as MenuId, AM.DisplayText, AM.Url,
    AMP.Id as ParentMenuId, AMP.DisplayText as ParentDisplayText, AM.Url as ParentUrl
from ApplicationFeature as AF
    inner join ApplicationMenu as AM on AM.Id = AF.MenuId
    left outer join ApplicationMenu as AMP on AMP.Id = AM.ParentMenuId

If you want to get all parents up to the top, please clarify desired output format
EDIT:

declare @FeatureId = ???

;with CTE as (
  select
     AF.Name, AF.Id As FeatureId,
     AM.Id as MenuId, AM.DisplayText, AM.Url,
     AM.ParentId
  from ApplicationFeature as AF
     inner join ApplicationMenu as AM on AM.Id = AF.MenuId
  where AF.Id = @FeatureId

  union all

  select
     null as Name, null as FeatureId,
     AM.Id as MenuId, AM.DisplayText, AM.Url,
     AM.ParentId
  from ApplicationMenu as AM
     inner join CTE as C on C.ParentId = AM.Id
)
select * from CTE
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • edited answer, still don't get why do you need structure like this, but anyway, check is out, may be I misunderstood you – Roman Pekar Aug 02 '13 at 14:50
-1

UPDATED

You need to join a second time to get the parent

SELECT AF.ID,
AM.DisplayText as child,
Parent.DisplayText as parent
FROM ApplicationFeature AF 
LEFT JOIN ApplicationMenu AM ON AF.MenuId = AM.Id 
LEFT JOIN ApplicationMenu as Parent on AM.ParentMenuId = Parent.ID

SQLFiddle

RESULT

enter image description here

Anonymoose
  • 2,389
  • 6
  • 36
  • 69