SQL Server 2008中WHERE子句中的CASE语句

时间:2016-08-19 04:50:32

标签: sql-server sql-server-2008 where-clause case-statement

我想写一个CASE语句来查找基于@sFRomDate为空的两个日期之间的数据。鉴于以下查询不符合我的要求。请帮我找一个合适的解决方案

SELECT 
    * 
FROM 
    tbl_emp_data 
WHERE
    CASE 
       WHEN @sFRomDate!='' 
          THEN SubmissionDate BETWEEN @sFRomDate AND DATEADD(DAY,1,@sToDate) 
       ELSE
          SubmissionDate = NULL
    END

2 个答案:

答案 0 :(得分:2)

这可能是您尝试实施的逻辑。如果@sFRomDateNULL或空 SubmissionDate也为NULL或为空,则会返回记录。否则,将检查SubmissionDate以确保它在您定义的范围内。

SELECT *
FROM tbl_emp_data
WHERE (COALESCE(@sFRomDate, '') = '' AND
       COALESCE(SubmissionDate, '') = '') OR
      (COALESCE(@sFRomDate, '') <> ''     AND
       COALESCE(SubmissionDate, '') <> '' AND
       SubmissionDate BETWEEN @sFRomDate AND DATEADD(DAY, 1, @sToDate))

答案 1 :(得分:1)

如果我理解你想要什么,我认为如果你写下来,遵循逻辑会变得更简单:

IF @sFromDate = ''
BEGIN
SELECT * FROM tbl_emp_data where SubmissionDate=null
END
ELSE
BEGIN
SELECT * FROM tbl_emp_data where SubmissionDate between @sFRomDate and DATEADD(DAY,1,@sToDate)
END

但正如@Tim Biegeleisen所说,小心空值,不只是@sFromDate而且@sToDate