6

当我想要特定用户的数据时,下面是查询的 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)决定是否在查询中添加额外的条件。当我想要所有用户的数据和特定用户的 system_user_id 将被发送时,我将发送 -1。

4

2 回答 2

9

您可以尝试以下程序。

更新查询

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

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

于 2012-12-13T11:03:36.673 回答
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)
于 2012-12-13T10:59:47.370 回答