SQL where clause with case statement

2019-07-29 00:04发布

问题:

I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END

I'm not sure how to process the -1 to say select all users

Thanks

回答1:

Perhaps the following would work:

SELECT whatever
  FROM wherever
  WHERE something = somethingelse AND
        usertable.userid = CASE @user
                             WHEN -1 THEN usertable.userid
                             ELSE @user
                           END

Share and enjoy.



回答2:

you can change the clause like this to return all users...

AND ( @user = -1 
    OR usertable.userid = @user
)

No need of case statement this way...



回答3:

Could you not put the whole think in an if statement...

Something like

if (@userId = -1)
    SELECT * FROM usertable
else
    SELECT * FROM usertable WHERE Id = @userId


回答4:

usertable.userid = COALESCE(NULLIF(@user, -1), usertable.userid)