且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sql查询where子句中的if条件

更新时间:2022-06-03 18:03:22

您可以尝试以下步骤.

更新的查询

declare @userid int = -1
if (@userid = -1)
    BEGIN

     SELECT * FROM mytable 
     where Completion_Date>= '11/01/2011' 
     and Completion_Date<= '12/11/2012' 
     and userid in 
         (select distinct userID from mytable)
    end
ELSE
    BEGIN

     SELECT * FROM mytable 
     where Completion_Date>= '11/01/2011' 
     and Completion_Date<= '12/11/2012' 
     and userid = @userid 

end;

结果:

USERID  NAME    COMPLETION_DATE
123     john    2011-11-01
125     tim     2011-11-02
127     ron     2011-11-08

  • 参考 SQLFIDDLE
  • 查看特定用户:

    根据 OP 的最新评论更新

    Updated after latest comment from OP

    查询:

DECLARE @uid int = -1
SELECT 
*
FROM mytable 
WHERE 
( CASE 
     WHEN @uid <> -1 THEN @uid
     ELSE userid
  END
) = userid

and Completion_Date>= '11/01/2011' 
     and Completion_Date<= '12/11/2012' 
;

结果:当@uid = -1

Results: when @uid = -1

USERID  NAME    COMPLETION_DATE
123     john    2011-11-01
125     tim     2011-11-02
127     ron     2011-11-08

如果您尝试过,请发表评论:)

Please comment if you have tried this out :)