在SQL CASE where子句中使用BETWEEN

问题描述 投票:5回答:6

我有一个表单,用户在其中提取报告。在表单中,他们可以选择开始日期和结束日期,或者为两个值传递null。如果他们选择null,则返回所有记录,其中effectivedate <GETDATE()CASE语句似乎不喜欢,也不喜欢'<'运算符

这是我的剧本

SELECT * FROM tbReport
WHERE 
    EffectiveDate 
    CASE 
        WHEN (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
        THEN BETWEEN (@StartDate AND @EndDate)          
         ELSE 
                  THEN < GETDATE()

    END
sql case where
6个回答
8
投票

您可以在没有案例的情况下重写它,例如:

SELECT  * 
FROM   tbReport
WHERE   (
            @StartDate is not null 
            and 
            @EndDate is not null
            and 
            EffectiveDate between @StartDate AND @EndDate
        )
        or
        (
            (
                @StartDate is null 
                or 
                @EndDate is null
            )
            and 
            EffectiveDate < getdate()
        )

2
投票

像这样的东西应该工作,我没有检查语法是否正确。

SELECT * FROM tbReport
WHERE EffectiveDate < IsNull(@EndDate,GetDate())
AND EffectiveDate > IsNull(@StartDate,'01/01/1979')

2
投票

假设这是SQL Server,您可以使用isnull简化此操作:

select *
from tbReport
where EffectiveDate between isnull(@StartDate, '1 Jan 1990')
      and isnull(@EndDate, getdate())

0
投票

CASE的语法在这里都是错误的。试试这个:

SELECT * FROM tbReport
WHERE 
    (@StartDate is null and @EndDate is null and EffectiveDate < GetDate()) or 
    (@StartDate is not null and @EndDate is not null and 
     EffectiveDate >= @StartDate and EffectiveDate <= @EndDate)

0
投票

SQL语句写得不正确。 Case不会有条件地选择评估的代码。您可以将大小写视为一个值,因此您必须在大小写和另一个操作数之间放置一个运算符。

写这个的多种方式之一是:

where 
case when @StartDate IS NOT NULL AND @EndDate IS NOT NULL and EffectiveDate BETWEEN (@StartDate AND @EndDate)   then 1
case when (@StartDate IS NULL OR @EndDate IS NULL) and EffectiveDate <getdate() then 1
else 0 end = 1

如果您不想用大写字母书写它,您可以选择其中一个解决方案,但它们使用离散的开始日期。


0
投票
WHERE 

(SR.RecCreateTS BETWEEN  ( CASE WHEN  @SubmittedBegining IS NOT NULL  THEN @SubmittedBegining ELSE SR.RecCreateTS END )
                            AND ( CASE WHEN  @SubmittedEnding IS NOT NULL   THEN @SubmittedEnding ELSE SR.RecCreateTS END )
                            )
© www.soinside.com 2019 - 2024. All rights reserved.