if条件在sql查询的where子句中

时间:2012-12-13 10:50:27

标签: sql-server

当我想要特定用户的数据

时,下面是我的查询的where子句
where Completion_Date>= '11/01/2011' 
and Completion_Date<= '12/11/2012' 
and System_user_id = 1234
当我想为所有用户提取数据时,

及以下是where子句:

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

由于我不想要2个单独的查询,有没有办法在where子句中添加条件,以便我可以使用单个查询并根据输入(即System_user_id),它将决定是否在其中添加额外的条件查询。 当我想要所有用户的数据时,我将发送-1对于特定用户,将发送system_user_id。

2 个答案:

答案 0 :(得分:8)

您可以尝试以下程序。

更新了查询

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

要查看特定用户:


另一种方法

在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

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

如果你试过这个,请评论:)

答案 1 :(得分:5)

尝试:

WHERE ((@System_user_id = -1)
  AND (Completion_Date >= '11/01/2011') 
  AND (Completion_Date <= '12/11/2012'))
OR ((@System_user_id <> -1) 
  AND (System_user_id = @System_user_id) 
  AND (Completion_Date >= '11/01/2011') 
  AND (Completion_Date <= '12/11/2012'))

使用公用表表达式(SQL Fiddle

的变体
;WITH CompletionDates AS
(
    SELECT *
    FROM MyTable
    WHERE Completion_Date >= '11/01/2011'
    AND Completion_Date <= '12/11/2012'
)
SELECT * 
FROM CompletionDates
WHERE (@System_user_id = -1) OR (System_user_id = @System_user_id)