[英]SQL where clause with case statement
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.我对 SQL 有一个问题,我还没有找到解决方案,我试图做的是一个 where 子句,用于一个 userID 变量可以包含有效的 userID 或 -1 以指示所有用户的过程。
However im stuck at this part of the where clause:但是我停留在 where 子句的这一部分:
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我不知道如何处理 -1 说 select 所有用户
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...你能不能把整个想法放在一个 if 语句中......
Something like就像是
if (@userId = -1)
SELECT * FROM usertable
else
SELECT * FROM usertable WHERE Id = @userId
usertable.userid = COALESCE(NULLIF(@user, -1), usertable.userid)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.