This sql server query selects all the groups that are connected to the tblSource based…
- User
This sql server query selects all the groups that are connected to the tblSource based on SomeoneIDs from #tblSomeTable and sourcetype. How do I change it to also select the direct children of those groups?
SELECT groups.* INTO #tblGroup FROM tblGroup groups JOIN tblSource source ON source.SourceID = groups.SourceID JOIN tblSomeone someone ON someone.ClientId = source.SourceID JOIN tblSourceType sourceType ON sourceType.SourceTypeID = source.SourceTypeID WHERE (someone.SomeoneID IN (SELECT SomeoneID FROM #tblSomeTable)) AND (sourceType.Description = 'someone')
- Assistant
You can modify the existing query to include a CTE (Common Table Expression) that retrieves direct children of the groups found, and then uses UNION to combine them with the original results.
Here's how the modified query would look like:
;WITH GroupChildren AS ( SELECT childGroups.* FROM tblGroup parentGroups JOIN tblGroup childGroups ON childGroups.ParentGroupID = parentGroups.GroupID JOIN tblSource source ON source.SourceID = parentGroups.SourceID JOIN tblSomeone someone ON someone.ClientId = source.SourceID JOIN tblSourceType sourceType ON sourceType.SourceTypeID = source.SourceTypeID WHERE (someone.SomeoneID IN (SELECT SomeoneID FROM #tblSomeTable)) AND (sourceType.Description = 'someone') ) SELECT groups.* INTO #tblGroup FROM tblGroup groups JOIN tblSource source ON source.SourceID = groups.SourceID JOIN tblSomeone someone ON someone.ClientId = source.SourceID JOIN tblSourceType sourceType ON sourceType.SourceTypeID = source.SourceTypeID WHERE (someone.SomeoneID IN (SELECT SomeoneID FROM #tblSomeTable)) AND (sourceType.Description = 'someone') UNION SELECT gc.* FROM GroupChildren gc