Conditional WHERE Clauses and Boolean Algebra

  • UncleJimBob (8/31/2010)


    I ran into performance issues caused by parameter sniffing so many times using this type of construct

    at work that I had to stop using it.

    Now I use this:

    declare @local_firstname nvarchar(50)

    declare @local_lastname nvarchar(50)

    select @local_firstname = isnull(@firstname,''), @local_lastname = isnull(@lastname,'')

    SELECT ID, FirstName, LastName FROM People

    WHERE

    FirstName LIKE '%' + @local_firstname + '%'

    and

    LastName LIKE '%' + @local_lastname + '%'

    It's more work up front but:

    a) makes the query easier to understand (and therefore maintain) and

    b) avoids slow queries caused by the use of inappropriate query plans via parameter sniffing

    Just my 2c

    I've also found it necessary to use a variable in the sql, rather than the parameter from the header, due to parameter sniffing. As indicated, a little up-front work assingning a value to the variable can save you a lot of headache.

    Specifically I find this useful for date-related reports. Users can run a report and specify a start and end date, but they can leave them blank, or null, and sql will return a month-to-date, or previous month report. This is very useful for report schedulers, such as Crystal Reports. Crystal does not provide a way to pass a 'today' parameter, so I create the stored procedure to accept a null, and then use ISNULL (in a simple SET or SELECT, not in the 'main' query) to assign a variable using a FirstOfMonth function. The I use that variable in my 'main' query.

Viewing post 61 (of 60 total)

You must be logged in to reply to this topic. Login to reply