简体   繁体   中英

SQL CASE in Where Clause?

I have a two optional parameters empName, empLoc. Both of these parameters can be null, empty or have some value. If both has values, i will have to get all the values, if empName has value then i only need to get value where empName is equal to passed parameter @empName, and same with @empLoc. I know i can write separate sql's in same stored procedure but i want to do it using CASE clause, since it is going to save most of the repeated code. However i am having problem while setting up query. And i know it's the CASE clause. Here is what my query looks like:

SELECT 
     EmpID,
     EmpDept
FROM Employee
WHERE TimeStamp = @timeStamp
 **AND (CASE
        WHEN DATALENGTH(@empName) > 0 THEN EmployeeName LIKE '%' +@empName+'%'
      ELSE
         EmployeeLocation LIKE '%' +@empLoc+'%'
      END)**

NOTE: im already doing null check for these parameters. Also this query will only run if either @empName or @empLoc has some value.

Any suggestions how to fix this?

Actually you must put the DATALENGTH(@empName) <= 0 on the second part of the OR because the CASE implies an exclusive OR. So the correct one would be:

SELECT 
     EmpID,
     EmpDept
FROM Employee
WHERE TimeStamp = @timeStamp
AND 
(
    (DATALENGTH(@empName) > 0 AND EmployeeName LIKE '%' +@empName+'%')
      OR
    (DATALENGTH(@empName) <= 0 AND EmployeeLocation LIKE '%' +@empLoc+'%')
)

CASE is an expression that returns a value:

where TimeStamp = @timeStamp and
  CASE WHEN DATALENGTH(@empName) > 0 AND EmployeeName LIKE '%' +@empName+'%' THEN 1
    WHEN EmployeeLocation LIKE '%' +@empLoc+'%' THEN 1
    ELSE 0
    END = 1

You can use LEN function if you want to trim space

SELECT DATALENGTH(' ') --Result is 1
SELECT LEN(' ') -- Result is 0

you don't need to case when statement for this problem

SELECT 
     EmpID,
     EmpDept
FROM Employee
WHERE TimeStamp = @timeStamp
 AND
    ( ( DATALENGTH(@empName) > 0 AND EmployeeName LIKE '%' +@empName+'%')
      OR
      ( DATALENGTH(@empName) = 0 AND  EmployeeLocation LIKE '%' +@empLoc+'%'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM