Skip to content
Advertisement

change where statement given a case

I have a table which contains users info. with the columns:

  • id_staff
  • email
  • id_supervisor
  • id_branch
  • id_department

and I want to select the information in this table depending on a variable like

DECLARE @user_type nvarchar(20) = 'manager'

How can I change the where statement based on the variable

Example:

SELECT *
FROM users
WHERE 
(
   CASE WHEN @user_type = 'manager' THEN 
     id_branch = 3 AND id_department = 9
   ELSE
     id_supervisor = 15
)

Advertisement

Answer

Use boolean logic. You seem to want:

SELECT * 
FROM users 
WHERE 
    (@user_type = 'manager' AND id_branch = 3 AND id_department = 9)
    OR (@user_type <> 'manager' AND id_supervisor = 15)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement