• The short answer is yes, however I have several issues with what you're trying to do.

    1. [Issue #1] In the statement below, you're setting the right part of the quality to a characters string but unless @SexID already contains embedded quotes the dynamic SQL you're constructing is going to fail.

    SET @SqlQuerySex = ' WHERE sexID = ' + convert(varchar(20), @sexID)

    2. [Issue #2] What happens if more than one of the query parameters has been sent through? It seems that you'll have a WHERE keyword in multiple places in your dynamic SQL.

    3. You can get around issue #2 quite easily (and answer you're original question) by simply starting with the basic SELECT/FROM in a string and then using CASE to attach to it the additional query parameters. Include the WHERE only if any of the filter parameters are specified.

    4. [Issue #3 and solution to issue #1] Instead of assigning the value to the SQL string for filter parameters, consider checking for field = @Filter, and then passing @Filter to sp_executesql. Check BOL for a description of how to do that (I'm guessing that you were planning on using EXEC (@SQL) instead).


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St