CASE in WHERE clause

I have a stored procedure that functions fine as long as the @userTypes parameter contains something like '100,200,300,400,500' - but how can I branch out the WHERE clause to also allow '%', as the CSVToTable doesn't handle that of course, and throws an error :) ?

WHERE  userRole like @uRole AND userType IN (SELECT * FROM dbo.CSVToTable(@userTypes))

Open in new window


I've tried with this, but still get an error:

WHERE  userRole like @uRole AND userType IN (CASE @userTypes WHEN '%' THEN userType ELSE (SELECT * FROM dbo.CSVToTable(@userTypes)) END)

Open in new window

LVL 1
Mik MakConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
This code will match either a single value, like '100', or aLIKE pattern, such as '100%', even in the same @userTypes list:

;WITH cte_search_values AS (
    SELECT value /* change to match the actual column name returned by the function */
    FROM dbo.CSVToTable(@userTypes)
)
SELECT <...>
FROM dbo.main_table mt
INNER JOIN cte_search_values csv ON mt.userType LIKE csv.value
Mik MakConsultantAuthor Commented:
Thank you. Sorry for the noob questions, but will it also handle the single '%' and the multiple values '100,200,300,400,500' ?

And where can I then attache the other part of the clause - "userRole like @uRole" ?
Scott PletcherSenior DBACommented:
Yes, it will handle any mix of single values and patterns (values with % in them).

Sorry, left off the @uRole check, use a WHERE clause as before:

;WITH ... ( ...
)
SELECT <...>
FROM dbo.main_table mt
INNER JOIN cte_search_values csv ON mt.userType LIKE csv.value
WHERE  userRole like @uRole

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mik MakConsultantAuthor Commented:
Excellent ! - thank you very much :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
T-SQL

From novice to tech pro — start learning today.