Reputation: 9617
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?
Upvotes: 1
Views: 16070
Reputation: 3615
You can use LEN function if you want to trim space
SELECT DATALENGTH(' ') --Result is 1
SELECT LEN(' ') -- Result is 0
Upvotes: 0
Reputation: 56
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+'%')
)
Upvotes: 4
Reputation: 15816
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
Upvotes: 1
Reputation: 3962
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+'%'))
Upvotes: -1