我之前的问题是Case Statement With Between Clause In Sql Server
我得到了一个解决方案并且有效。但问题是,当我向WHERE
子句添加另一列时,它不会使用此新列进行过滤:
SELECT
tbl1.Column1, tbl1.Column2
FROM
table1 tbl1
WHERE
EmployeeId = CASE WHEN @employeeId = '' THEN tbl1.EmployeeId
ELSE @employeeId END
AND (@DateTo = '1900-01-01' AND @DateFrom = '1900-01-01') OR
(NOT (@DateTo = '1900-01-01' AND @DateFrom = '1900-01-01')
AND (CAST(tbl1.txnDate AS DATE) BETWEEN @DateFrom AND @DateTo))
这段代码就是我想要使用的。但它不起作用。我尝试对EmployeeId
的值进行硬编码。但它不起作用
答案 0 :(得分:3)
您必须在使用(
和)
的where子句中使用And
和OR
,以便定义每个条件的优先级:
SELECT tbl1.Column1,tbl1.Column2
FROM table1 tbl1
WHERE EmployeeId = CASE WHEN @employeeId = '' THEN tbl1.EmployeeId ELSE @employeeId END
AND (
(@DateTo = '1900-01-01' AND @DateFrom = '1900-01-01')
OR (
NOT (@DateTo = '1900-01-01' AND @DateFrom = '1900-01-01')
AND (CAST(tbl1.txnDate AS DATE) BETWEEN @DateFrom AND @DateTo)
)
)