Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase «««34567

Conditional WHERE Clauses and Boolean Algebra Expand / Collapse
Author
Message
Posted Thursday, September 02, 2010 8:06 AM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Thursday, December 12, 2013 1:44 PM
Points: 69, Visits: 205
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.
Post #979564
« Prev Topic | Next Topic »

Add to briefcase «««34567

Permissions Expand / Collapse