在SQL CASE where子句中使用BETWEEN

在SQL CASE where子句中使用BETWEEN,sql,case,where,Sql,Case,Where,我有一个表单,用户从中提取报告。 在表单中,它们可以选择开始日期和结束日期,或者为这两个值传递null。如果选择null,则返回所有记录,其中effectivedate

我有一个表单,用户从中提取报告。 在表单中,它们可以选择开始日期和结束日期,或者为这两个值传递null。如果选择null,则返回所有记录,其中effectivedateCASE语句似乎不喜欢between,也不喜欢'您的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)
从tbReport中选择*
哪里
(@StartDate为null,@EndDate为null,EffectiveDateEffectiveDate>=@StartDate和EffectiveDate假设这是SQL Server,您可以通过使用isnull来简化它:

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

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

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()
        )
选择*
来自tbReport
在哪里(
@StartDate不为空
及
@EndDate不为空
及
@StartDate和@EndDate之间的生效日期
)
或
(
(
@StartDate为空
或
@EndDate为空
)
及
EffectiveDate
类似的功能应该可以使用,但我还没有检查语法是否正确

SELECT * FROM tbReport
WHERE EffectiveDate < IsNull(@EndDate,GetDate())
AND EffectiveDate > IsNull(@StartDate,'01/01/1979')
从tbReport中选择*
其中EffectiveDateIsNull(@StartDate,'01/01/1979')

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

写这篇文章的多种方式之一是:

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
在哪里
当@StartDate不为NULL且@EndDate不为NULL且EffectiveDate介于(@StartDate和@EndDate)之间时,则为1

当(@StartDate为NULL或@EndDate为NULL)和EffectiveDate时,很遗憾,这没有考虑到如果其中任何一个日期为NULL,则返回EffectiveDatewhere 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
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 )
                            )