我想写一个CASE
语句来查找基于@sFRomDate
为空的两个日期之间的数据。鉴于以下查询不符合我的要求。请帮我找一个合适的解决方案
SELECT
*
FROM
tbl_emp_data
WHERE
CASE
WHEN @sFRomDate!=''
THEN SubmissionDate BETWEEN @sFRomDate AND DATEADD(DAY,1,@sToDate)
ELSE
SubmissionDate = NULL
END
答案 0 :(得分:2)
这可能是您尝试实施的逻辑。如果@sFRomDate
为NULL
或空且 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