开发者

SQL where clause with case statement

开发者 https://www.devze.com 2023-03-10 09:20 出处:网络
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 al

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
  @use开发者_JAVA技巧r
END

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

Thanks


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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消