some data to play with
create table #UserModules(ModuleID int, UserID int)
create table #Modules_Hirarchy(ParentModuleID int, ChildModuleID int)
insert into #UserModules (ModuleID , UserID)
values(1,1)
,(2,1)
,(3,1)
,(4,1)
,(5,1)
,(6,2)
,(7,2)
insert into #Modules_Hirarchy(ParentModuleID , ChildModuleID )
values (null,1)
,(1,2)
,(2,3)
,(3,4)
,(3,5)
,(null,6)
,(6,7)
resolution
with cts(ModuleID, UserID,parentModule ) as
(
select a.ModuleID, a.UserID , CAST(null as int)as parentModule --, cAST(null as int)as b
from #UserModules a join #Modules_Hirarchy b on a.ModuleID = b.ChildModuleID
where b.ParentModuleID is null
union all
select b.ChildModuleID as ModuleID, a.UserID, b.ParentModuleID
from cts a join #Modules_Hirarchy b
on a.ModuleID = b.ParentModuleID
)
select *
into #RESULT
from cts
edit its hard to say : ) to many variables but things you should do to make query efficient
separate non clustered indexes on columns
ModuleID ParentModuleID ChildModuleID
you probably dont want to query for all of the groups but only for a explicit ones filter out as many groups as posible in anchor statement
select a.ModuleID, a.UserID , CAST(null as int)as parentModule from #UserModules a join #Modules_Hirarchy b on a.ModuleID = b.ChildModuleID where b.ParentModuleID is null and a.ModuleId in (listOfModules)
add unique index for columns
(ParentModuleID, ChildModuleID)
as non unique rows there may lead to huge amount of row duplication
Except on that it depends on data selectivity on the ParentModuleID ChildModuleID, but you cant do much about it
i think it will work fine for big data sets as predicates are simple and as long as data selectivity is high