简体   繁体   中英

Include NULL values in a designated field in my where clause on SSRS

I am learning SQL so be gentle. If I have designated a specific role in my where clause it is only pulling those cases where that role is populated. How can I also include the NULL values or those roles that are blank?

Here is the where clause now:

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. When the query optimizer encounters a COALESCE() call, it will internally rewrite that expression to an equivalent CASE...WHEN expression. 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) .

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

This is also assuming that any joins in your query aren't filtering out rows whose role_sk column is 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. Functions in WHERE clause often cause Index-Scans instead of the more efficient Index-Seeks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM