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

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

sql - NULL values are excluded. Why?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...