SQL Server 2008 中 WHERE 子句中的 CASE 语句
CASE statement within WHERE clause in SQL Server 2008
我想写一个CASE
语句,根据@sFRomDate
是否为空来查找两个日期之间的数据。鉴于以下查询不符合我的要求。请帮我找到合适的解决方案
SELECT
*
FROM
tbl_emp_data
WHERE
CASE
WHEN @sFRomDate!=''
THEN SubmissionDate BETWEEN @sFRomDate AND DATEADD(DAY,1,@sToDate)
ELSE
SubmissionDate = NULL
END
这可能是您试图实现的逻辑。如果 @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))
如果我明白你想要什么,我认为如果你这样写会更容易遵循逻辑:
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
我想写一个CASE
语句,根据@sFRomDate
是否为空来查找两个日期之间的数据。鉴于以下查询不符合我的要求。请帮我找到合适的解决方案
SELECT
*
FROM
tbl_emp_data
WHERE
CASE
WHEN @sFRomDate!=''
THEN SubmissionDate BETWEEN @sFRomDate AND DATEADD(DAY,1,@sToDate)
ELSE
SubmissionDate = NULL
END
这可能是您试图实现的逻辑。如果 @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))
如果我明白你想要什么,我认为如果你这样写会更容易遵循逻辑:
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