I have a table of names:
John
Peter
Peter-Paul
Mary
I have a drop down list of these names and I have added 'All' as an option at the top.
I want to pass the name selected from the drop down list as a parameter to a where clause.
What I am trying to do is only have the where clause if name is not passed as 'All'
SELECT City, State
FROM EmployeeDetails
WHERE @NAME =
CASE @NAME
WHEN 'All' THEN '1=1'
ELSE (EmployeeDetails.NAME LIKE '' + @NAME + '%')
I can't get this to work. The ELSE statement gives the error 'Incorrect syntax near the word 'LIKE'.
Looking at other StackOverflow questions I have found:
When running the WHERE clause not in a CASE statement, it works for a specific name such as:
WHERE (EmployeeDetails.NAME LIKE '' + @NAME + '%')
If I search for Peter it would return 2 results as expected. Mary 1 result, etc.
I obviously can't pass 'All' to that.
Don't use case
in the where
. Simply do:
SELECT City, State
FROM EmployeeDetails
WHERE (@NAME = 'All') OR (EmployeeDetails.NAME LIKE '' + @NAME + '%');
I'm not sure what the purpose of '' +
is, but you have it in your question, so I'm leaving it.