Where语句中的SQL Boolean Vars

时间:2012-07-17 10:06:19

标签: sql where rdl

我正在制作一个rdl报告,我有三个复选框,如果选中则需要更改我的WHERE语句。如果未选中,则结果应仅按日期范围匹配。如果选中了一个或多个,则需要返回与对应字符串变量匹配的字段。

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)) 

到目前为止,我的代码在没有选中的情况下以及选中的代码时都有效,但在选中多个复选框时则不返回任何内容。因此,为了尝试修复此问题,我将代码更改为此

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)))

无论选择什么行,都导致返回所有行。谁能告诉我哪里出错了?

3 个答案:

答案 0 :(得分:1)

我相信这是正确的重新排列。比第一次出现更棘手的问题。问题是((@IncludeSEWPrefix = 1 AND PrefixId = 'SEW') OR @IncludeSEWPrefix = 0)AND之间的分隔意味着如果两个包含为true,则一行需要同时包含PrefixId,这是不可能发生的。如果你用OR分隔它们,那么只有一个包含false,意味着每一行都会通过。因此,请检查一行是否包含任何包含的前缀,否则所有包含都必须关闭。

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)
)

答案 1 :(得分:0)

试试这个

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)
)  

答案 2 :(得分:0)

你有比所需更多的括号,它不会伤害但只是要注意。 也许这可以提供帮助:

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