Mutually Exclusive Queries

Viewed 624

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) 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.

Example

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
2 Answers
Related