带有case语句的SQL where子句 [英] SQL where clause with case statement

查看:130
本文介绍了带有case语句的SQL where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQL问题,但尚未找到解决方案,我要尝试做的是在过程中使用where子句,其中userID变量可以包含有效的userID或-1来指示所有用户./p>

但是我仍然停留在where子句的这一部分:

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

ELSE
  @user
END

我不确定如何处理-1以说选择所有用户

谢谢

解决方案

以下方法可能会起作用:

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

分享并享受.

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

解决方案

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.

这篇关于带有case语句的SQL where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆