• aaron.reese (5/13/2016)


    Another option would be to turn the query into dynamic SQL and append

    'WHERE searchValue in (''' + @inParameterString +''')'

    The @inParameterString is them passed in as "A", "B" or "A','B"

    Which will result in the Where clause looking like

    'WHERE searchValue in ('A')'

    'WHERE searchValue in ('B')'

    'WHERE searchValue in ('A','B')'

    However you will never be able to build a query plan that is high performance in all cases as it will be subject to parameter sniffing. Also if you are taking the parameter list from a non-secure source (e.g. Web Form) you will need to protect against SQL injection attacks.

    I am not saying that you SHOULD do this, in fact I would reccomend against it if you can, but it is a possiblity

    Actually dynamic SQL is in many cases/ways THE BEST way to solve this classic "open-ended search" problem. It is especially useful in situations where you can eliminate joins to a table that you aren't even touching for filtering. And you are giving the optimizer EXACTLY the right stuff to get the best query plan.

    Best,
    Kevin G. Boles
    SQL Server Consultant
    SQL MVP 2007-2012
    TheSQLGuru on googles mail service