By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,568 Members | 1,688 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,568 IT Pros & Developers. It's quick & easy.

Creating WHERE clauses based on IF (or CASE) STATEMENTS Transact-SQL

P: n/a
I am trying to create a stored procedure whose where clause is
dependent on a parameter.

If the parameter @myparam is null or '' then I want the where clause to
be one thing, else I want it to be a completely different thing. I can
do it easily using iif but obviously that is not an option here...

Here is what I have:

Select @ FROM my table WHERE

IF @myparam = '' or @myparam is null
[MyField] = like '%'
ELSE
charindex(@myparam,[MyField]) > 0)

I have also tried variations of this and tried it using CASE. I keep
getting syntax errors. Do I have to write multiple SELECT statements
for every possibility. If I can get this working the query will
actually be a bit more complex, although it will follow this basic
structure...in other words, I'd rather not have to write multiple
queries when the only thing that is changing is the WHERE portion...

Thanks!
Ryan

Nov 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
How about this:

if @myparam = '' or @myparam is null
@myparam = '%'
else
@myparam = '%' + @myparam + '%'

select ...
from mytable
where MyField like @myparam

Nov 23 '05 #2

P: n/a
>How about this:

if @myparam = '' or @myparam is null
@myparam = '%'
else
@myparam = '%' + @myparam + '%'

select ...
from mytable
where MyField like @myparam


Actually, now that I've thought about it more, it would be silly (and
wasteful) to pattern match to everything. This might be better:

select ...
from mytable
where (@myparam = '' or @myparam is null
or charindex(@myparam,[MyField]) > 0))

Nov 23 '05 #3

P: n/a
I want you to know that you are my new hero :) Thank you SOOOOOO much.
I can now home for the night...

Nov 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.