Question

I'm creating a report (in Crystal Reports XI) based on a SQL stored procedure in a database. The query accepts a few parameters, and returns records within the specified date range. If parameters are passed in, they are used to determine which records to return. If one or more parameters are not passed in, that field is not used to limit the types of records returned. It's a bit complicated, so here's my WHERE clause:

WHERE  ((Date > @start_date) AND (Date < @end_date)) 
    AND (@EmployeeID IS NULL OR emp_id = @EmployeeID) 
    AND (@ClientID IS NULL OR client_id = @ClientID)
    AND (@ProjectID IS NULL OR project_id  = @ProjectID)
    AND (@Group IS NULL OR group = @Group)

Now, for the problem:

The query (and report) works beautifully for old data, within the range of years 2000-2005. However, the WHERE clause is not filtering the data properly for more recent years: it only returns records where the parameter @Group is NULL (ie: not passed in).

Any hints, tips, or leads are appreciated!

Was it helpful?

Solution

Solved!

It actually had nothing to do with the WHERE clause, after all. I had let SQL Server generate an inner join for me, which should have been a LEFT join: many records from recent years do not contain entries in the joined table (expenses), so they weren't showing up. Interestingly, the few recent records that do have entries in the expenses table have a NULL value for group, which is why I got records only when @Group was NULL.

Morals of the story: 1. Double check anything that is automatically generated; and 2. Look out for NULL values! (n8wl - thanks for giving me the hint to look closely at NULLs.)

OTHER TIPS

What are the chances that your newer data (post-2005) has some rows with NULL's in emp_id, client_id, project _id, or group? If they were NULL's they can't match the parameters you're passing.

Since Date and group are reserved words you might try putting square brackets around the fields so they aren't processed. Doing so can get rid of "odd" issues like this. So that would make it:

WHERE  (([Date] > @start_date) AND ([Date] < @end_date)) 
AND (@EmployeeID IS NULL OR emp_id = @EmployeeID) 
AND (@ClientID IS NULL OR client_id = @ClientID)
AND (@ProjectID IS NULL OR project_id  = @ProjectID)
AND (@Group IS NULL OR [group] = @Group)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top