Mutually Exclusive Queries
Question How would you role an IF...ELSE that produces mutually exclusive results into a query that produces the same results? Use Case As the principal (currently logged in user)
Solution 1:
Use a union with the "if" condition added to each where clause:
SELECT du.userId
FROM dbo.DepartmentsUsers AS du
JOIN ( SELECT departmentId
FROM dbo.DepartmentsUsers
WHERE organizationId = @organizationId
AND userId = @userId) AS j
ON du.departmentId = j.departmentId
WHERE du.organizationId = @organizationId
AND EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
UNION
SELECT userId
FROM dbo.OrganizationsUsers
WHERE organizationId = @organizationId
AND NOT EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
Solution 2:
SELECT du.userId as UserId,
'Department' as UserType // remove this line unnecessary
FROM dbo.DepartmentsUsers AS du
JOIN (
-- Get department IDs assigned to the principal.
SELECT departmentId
FROM dbo.DepartmentsUsers
WHERE organizationId = @organizationId
AND userId = @userId) AS j
ON du.departmentId = j.departmentId
WHERE du.organizationId = @organizationId
UNION ALL
-- Get all user IDs in the organization.
SELECT userId as UserId,
'Organization' as UserType // remove this line unnecessary
FROM dbo.OrganizationsUsers
WHERE organizationId = @organizationId
Post a Comment for "Mutually Exclusive Queries"