SQL where clause with case statement

夙愿已清 提交于 2019-12-24 09:29:43

问题


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)


来源:https://stackoverflow.com/questions/6213788/sql-where-clause-with-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!