Home > Enterprise >  How can I construct a where clause based on a parameter value in Microsoft Transact SQL?
How can I construct a where clause based on a parameter value in Microsoft Transact SQL?

Time:09-17

I have a situation where if I pass a parameter @param, then I need my where clause to be

where field1 = @param

But, depending on the value of @param1, the where clause might be

where field1 in (... several possibilities)

Also, the where clause could be

where field1 is in (... several possibilities) 
   or field1 like ...%

So, based on what I pass, the where clause can have multiple "personalities". How do you do this?

I looked at creating a string

@sqlquery = "select whatever from wherever where ..."

and then executing it with sp_executesql, but I'm still not sure exactly how to do this. This appears to be the direction I need to go in.

CodePudding user response:

Switch the field and param, so it will be

where  @param like '%field1%'

CodePudding user response:

The method outlined on @aaronbertran's blog (KitchenSink) did indeed resolve my issue. There were even more complicating factors but this translated into all of them. Thank you for all your suggestions.

  • Related