Looking for help on whether the following query can be simplified.
Basically it's
Select records From A
Union
Select records From B WHERE records NOT IN (Select records From A)
Can I more easily write this without effectively duplicating the select on A
Basically it's
Select records From A
Union
Select records From B WHERE records NOT IN (Select records From A)
Can I more easily write this without effectively duplicating the select on A
Code:
SELECT s.id AS SYSTEMID, s.NAME AS SYSTEMNAME, t.ID AS TEAMID, t.NAME AS TEAMNAME,
t.ISFIRSTLINE, t.NATIONALSERVICETEAM, tu.DEFAULTTEAM
FROM TBLCLTEAMUSER tu WITH (NOLOCK)
INNER JOIN TBLCLTEAM t WITH (NOLOCK) ON tu.TEAMID = t.ID
INNER JOIN TBLCLSYSTEM s WITH (NOLOCK) ON t.SYSTEMID = s.ID
WHERE t.ACTIVE = 1
AND tu.USERID = @userid
UNION
SELECT s.id AS SYSTEMID, s.NAME AS SYSTEMNAME, t.ID AS TEAMID, t.NAME AS TEAMNAME,
t.ISFIRSTLINE, t.NATIONALSERVICETEAM, 0 AS DEFAULTTEAM
FROM TBLCLTEAM t
INNER JOIN TBLCLSYSTEM s WITH (NOLOCK) ON t.SYSTEMID = s.ID
WHERE t.ACTIVE = 1
AND (
-- inherit teams in system if user is a member of a 1st line team in system
t.SYSTEMID IN
(SELECT t.SYSTEMID
FROM TBLCLTEAMUSER AS tu WITH (NOLOCK)
INNER JOIN TBLCLTEAM AS t WITH (NOLOCK) ON tu.TEAMID = t.ID
WHERE tu.USERID = @userid
AND t.ACTIVE = 1
AND t.ISFIRSTLINE = 1)
OR
-- inherit teams in system if user is system admin in system
t.SYSTEMID IN
(SELECT SYSTEMID
FROM TBLCLSYSTEMADMIN WITH (NOLOCK)
WHERE USERID = @userid
AND SYSTEMADMIN = 1)
)
-- but don't create duplicate with actual granted permissions
AND t.ID NOT IN
(SELECT t.ID
FROM TBLCLTEAMUSER tu WITH (NOLOCK)
INNER JOIN TBLCLTEAM t WITH (NOLOCK) ON tu.TEAMID = t.ID
WHERE t.ACTIVE = 1
AND tu.USERID = @userid)
ORDER BY SYSTEMNAME, TEAMNAME