子句不起作用的地方 - SQL Server

时间:2014-07-24 05:12:32

标签: sql sql-server sql-server-2008

我之前的问题是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的值进行硬编码。但它不起作用

1 个答案:

答案 0 :(得分:3)

您必须在使用()的where子句中使用AndOR,以便定义每个条件的优先级:

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)
             )
        )