471,108 Members | 1,279 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,108 software developers and data experts.

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

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 '%'
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...


Nov 23 '05 #1
3 3472
How about this:

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

select ...
from mytable
where MyField like @myparam

Nov 23 '05 #2
>How about this:

if @myparam = '' or @myparam is null
@myparam = '%'
@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
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.

Similar topics

1 post views Thread by db2sysc | last post: by
2 posts views Thread by Stephen Zachmann | last post: by
5 posts views Thread by alacrite | last post: by
1 post views Thread by anishap | last post: by
6 posts views Thread by kronecker | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.