How would you role an IF...ELSE that produces mutually exclusive results into a query that produces the same results?
As the principal (currently logged in user) I can get a list of users in my organization. If I'm assigned to any departments then the list of users is a smaller set that are assigned to the same departments.
DECLARE @organizationId int = 421;
DECLARE @userId int = 1138;
IF EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
-- Get user IDs in the same department(s) as the principal.
SELECT du.userId
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
ELSE
-- Get all user IDs in the organization.
SELECT userId
FROM dbo.OrganizationsUsers
WHERE organizationId = @organizationId
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With