[英]Include NULL values in a designated field in my where clause on SSRS
I am learning SQL so be gentle. 我正在学习SQL,所以要保持柔和。 If I have designated a specific role in my where clause it is only pulling those cases where that role is populated.
如果我在where子句中指定了特定角色,则只会拉那些填充该角色的情况。 How can I also include the NULL values or those roles that are blank?
如何还包含NULL值或空白角色?
Here is the where clause now: 现在是where子句:
WHERE (dbo.vcases.lawtype = 'My Cases') AND
(dbo.vcase_parties_people.role_sk = 4001) AND
**(v1.role_sk = 3940) AND
(v1.report_ind = 'Y') AND
(v2.role_sk = 3939) AND
(v2.report_ind = 'Y')** AND
(dbo.vcases.case_type NOT IN ('Case type 1', 'Case type 2'))
The COALESCE()
expression in SQL is useful for substituting a default value when NULL is encountered for a given column or expression. 当给定列或表达式遇到NULL时,SQL中的
COALESCE()
表达式可用于替换默认值。 When the query optimizer encounters a COALESCE()
call, it will internally rewrite that expression to an equivalent CASE...WHEN
expression. 当查询优化器遇到
COALESCE()
调用时,它将在内部将该表达式重写为等效的CASE...WHEN
表达式。 In your sample query, WHERE (COALESCE(v1.role_sk, 3940) = 3940)
would operate (and optimize) the same as WHERE (CASE WHEN v1.role_sk IS NOT NULL THEN v1.role_sk ELSE 3940 END = 3940)
. 在您的示例查询中,
WHERE (COALESCE(v1.role_sk, 3940) = 3940)
操作(并优化)与WHERE (CASE WHEN v1.role_sk IS NOT NULL THEN v1.role_sk ELSE 3940 END = 3940)
相同WHERE (CASE WHEN v1.role_sk IS NOT NULL THEN v1.role_sk ELSE 3940 END = 3940)
。
Since your example specifically involves a condition in the WHERE
clause, you may want to use an OR
operation, which could optimize better than a COALESCE()
expression: WHERE (v1.role_sk = 3940 OR v1.role_sk IS NULL)
. 由于您的示例专门涉及
WHERE
子句中的条件,因此您可能希望使用OR
操作,该操作比COALESCE()
表达式的优化效果更好: WHERE (v1.role_sk = 3940 OR v1.role_sk IS NULL)
。
This is also assuming that any joins in your query aren't filtering out rows whose role_sk column is NULL. 这也假设查询中的所有联接都不会过滤出role_sk列为NULL的行。
You might edit your code as follows: 您可以按以下方式编辑代码:
WHERE (dbo.vcases.lawtype = 'My Cases') AND
(dbo.vcase_parties_people.role_sk = 4001) AND
(v1.role_sk = 3940 OR v1.role_sk IS NULL) AND
(v1.report_ind = 'Y') AND
(v2.role_sk = 3939) AND
(v2.report_ind = 'Y') AND
(dbo.vcases.case_type NOT IN ('Case type 1', 'Case type 2'))
The use of the Coalesce function has been suggested but a good rule of thumb in SQL is to avoid the use of functions in the WHERE clause because it reduces the efficiency of the table's indexes. 已经建议使用Coalesce函数,但是SQL中的一个好的经验法则是避免在WHERE子句中使用函数,因为它会降低表索引的效率。 Functions in WHERE clause often cause Index-Scans instead of the more efficient Index-Seeks.
WHERE子句中的函数通常导致索引扫描,而不是更有效的索引查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.