2015-10-13 20 views
2

我已經運行下面的代碼,但NULL不顯示在最終的查詢結果。 我可以看到NULL被插入臨時表中。當我在查詢中調用變量時,NULL值不顯示。表變量和NULLS

USE [AdventureWorks2014]; 
GO 

SET NOCOUNT ON; 
SET STATISTICS IO ON; 

DECLARE @values TABLE 
(  
Value VARCHAR(MAX) NULL 
) 

INSERT INTO @values 
VALUES (NULL), ('Black'), ('Blue'), ('Grey'), ('Multi'), ('Red'), ('Silver'), ('Silver'), ('Black'), ('White'), ('Yellow') --SELECT Value FROM @values; 

SELECT Production.Product.Name, Production.Product.ProductNumber, Production.Product.Color, Production.Product.ListPrice, Production.Product.SIZE, Production.Product.[Weight], Production.Product.ProductLine, Production.Product.Class, Production.Product.STYLE, Production.ProductPhoto.ThumbNailPhoto, Production.ProductPhoto.LargePhoto FROM Production.Product INNER JOIN Production.ProductProductPhoto ON Production.Product.ProductID =  Production.ProductProductPhoto.ProductID INNER JOIN Production.ProductPhoto ON Production.ProductProductPhoto.ProductPhotoID =  Production.ProductPhoto.ProductPhotoID 
--BEGIN CALLOUT A 
WHERE --Production.Product.Color IS NOT NULL 
(Production.Product.Color IN (SELECT Value FROM @values)); 
--END CALLOUT A 
GO 

回答

1

IN聲明將同樣執行(field = val1) OR (field = val2) OR (field = val3)。將NULL放在那裏將歸結爲(field = NULL),這自然不會起作用。這裏

WHERE (Production.Product.Color IN (SELECT Value FROM @values)) 
    OR (Production.Product.Color IS NULL) 
+0

小問題:

除了插入NULL@values的,試試這個。如果null未被插入到表變量中怎麼辦? –

+0

@ t-clausen.dk然後不要添加'OR'部分? –

+0

因此當表變量的內容發生變化時更改sql?有趣的 –

0
SET NOCOUNT ON; 
SET STATISTICS IO ON; 

DECLARE @values TABLE 
(  
Value VARCHAR(MAX) NULL 
) 

INSERT INTO @values 
VALUES (NULL), ('Black'), ('Blue'), ('Grey'), ('Multi'), ('Red'), ('Silver'), ('Silver'), ('Black'), ('White'), ('Yellow') --SELECT Value FROM @values; 

SELECT Production.Product.Name, Production.Product.ProductNumber, Production.Product.Color, Production.Product.ListPrice, Production.Product.SIZE, Production.Product.[Weight], Production.Product.ProductLine, Production.Product.Class, Production.Product.STYLE, Production.ProductPhoto.ThumbNailPhoto, Production.ProductPhoto.LargePhoto 
FROM Production.Product 
INNER JOIN Production.ProductProductPhoto ON Production.Product.ProductID =  Production.ProductProductPhoto.ProductID 
INNER JOIN Production.ProductPhoto ON Production.ProductProductPhoto.ProductPhotoID =  Production.ProductPhoto.ProductPhotoID 
--BEGIN CALLOUT A 
WHERE --Production.Product.Color IS NOT NULL 
(ISNULL(Production.Product.Color,'EMPTY') IN (SELECT ISNULL(Value,'EMPTY') FROM @values)); 
--END CALLOUT A 
GO 
+1

戰爭食物:答案應該有一些文字來解釋代碼,或只是文字。只有代碼答案可能有助於OP,但對未來的讀者來說會更難理解。 (這不是一個downvote,只是一個建議) –

0

使用INTERSECT

WHERE 
    exists (SELECT Production.Product.Color INTERSECT SELECT Value FROM @values)