Home Forums SQL Server 2008 SQL Server Newbies Dynamic WHERE statement if stored procedure parameter is null RE: Dynamic WHERE statement if stored procedure parameter is null

  • Sean Lange (7/10/2013)


    phoenix_ (7/10/2013)


    To be honest with you I don't like dynamic sql because of quotation marks '' which are making whole code harder to read 🙂

    So Instead of this I developed something like this:

    where condition1 and (SomeDate >= CASE WHEN @StartDate is null THEN SomeDate ELSE @StartDate END or SomeDate is null)

    and (SomeDate <= CASE WHEN @EndDate is null THEN SomeDate ELSE @EndDate END or SomeDate is null) and condition2

    This will work to a point. You will end up with some serious performance issues with this type of query though. Check out this article from Gail on the topic.

    http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/[/url]

    +1 to you Sean for the link to the bible on this topic.

    I saw the subject of this thread and visited to make sure someone had already provided it.


    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