Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is about a bizarre behaviour I found in Microsoft Sql Server. Please correct me if I'm wrong.

SELECT COUNT(*) FROM TABLEA 
WHERE [Column1] IS NULL;

This returns 30018 rows.

CREATE VIEW VIEWB AS 
SELECT * FROM TABLEA AS t1 
WHERE t1.[Column1] NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal')  

If I check VIEWB, I don't find NULL in Column1:

SELECT COUNT(*) FROM VIEWB 
WHERE [Column1] IS NULL;

This returns 0 rows.

Why? The query above excludes the 3 values, but it isn't supposed to exclude NULL. Why does Ms Sql Server behave this way? Should I have expected this? How can I fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is actually a common mistake made with SQL Server in treating NULL as a value. By default, it's treated as UNKNOWN, as documented here. So, in your view, you also need to include an OR t1.[Column1] IS NULL.

You can change this behavior by calling SET ANSI_NULLS OFF. It is not recommended to use this, however, as the feature is deprecated as pointed out by @Martin Smith.

This is not a SQL Server specific issue, however. It's part of the ANSI SQL standard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...