Search code examples
sqlwhere-clauserdl

SQL Boolean Vars in Where stament


I am making an rdl report and I have three check-boxes that if checked need to alter my WHERE statement. If none are checked the result should only match by date range. If one or more are checked it needs to return the fields that match the variables corresponding string.

WHERE 
(EffectiveDate BETWEEN @StartDate AND @EndDate) 
AND (((@IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR @IncludeSEWPrefix = 0)
AND ((@IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR @IncludePAWPrefix = 0)
AND ((@IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR @IncludeRPLPrefix = 0)) 

My code so far works when none are checked and when one is checked, but returns nothing when more than one check-box has been checked. So to try and fix this I altered the code to this

WHERE 
(EffectiveDate BETWEEN @StartDate AND @EndDate) 
AND ((((@IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR @IncludeSEWPrefix = 0)
OR ((@IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR @IncludePAWPrefix = 0)
OR ((@IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR @IncludeRPLPrefix = 0)))

Which resulted in all rows being returned no matter what was selected. Can someone tell me where I am going wrong?


Solution

  • I believe this is the correct rearrangement. Trickier problem than it first appears. The issue was seperating lines like ((@IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR @IncludeSEWPrefix = 0) with AND meant that if two includes were true, a row would need to have both PrefixId's, which can't happen. And if you separated them with OR, then having just one include false, means that every row will pass. So instead, check that a row has the prefix of any that are included, otherwise all includes have to be off.

    WHERE EffectiveDate BETWEEN @StartDate AND @EndDate
    AND 
    (
        (@IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR
        (@IncludePAWPrefix = 1 AND PrefixId = 'PAW') OR 
        (@IncludeRPLPrefix = 1 AND PrefixId = 'RPL') OR
        (@IncludeSEWPrefix = 0 AND @IncludePAWPrefix = 0 AND @IncludeRPLPrefix = 0)
    )