sql server not in查询没结果原因分析

2014-11-24 13:31:19 · 作者: · 浏览: 0
sql server not in查询没结果原因分析
今天使用SQL Server 时,遇到使用not in 和not exist的查询结果有差异:not in 查询没结果。
原因:not in 遇到null就不工作了。
摘录:
SELECT foreignStockId
FROM[Subset].[dbo].[Products]
Probably returns a NULL. Try

SELECT  stock.IdStock
        ,stock.Descr       
FROM[Inventory].[dbo].[Stock] stock
WHERE   stock.IdStock NOTIN(SELECT foreignStockId FROM[Subset].[dbo].[Products]WHERE foreignStockId ISNOTNULL)
a NOT IN (x,y,NULL) Will always return no results as it is equivalent to

a<>
x and a<>y and a<>NULL which is true and true and unknown Which eva luates to unknown under the rules of three valued logic. I normally use NOT EXISTS for this type of query SELECT stock.idstock, stock.descr FROM[Inventory].[dbo].[Stock] stock WHERENOTEXISTS(SELECT*FROM[Subset].[dbo].[Products] p WHERE p.foreignstockid = stock.idstock)