2011-10-27 67 views
3

我有一個需要篩選記錄其中:TSQL:NULL的「IN」的條款

NotificationRead = 0 || NULL --> IF GetRead = 0 
NotificationRead = 1 --> IF GetRead = 1 
NotificationRead = 0 || 1 || NULL --> IF GetRead = NULL 

這裏是我使用這個查詢:

DECLARE @GetRead BIT 
DECLARE @Query VARCHAR(20) 

SET @GetRead = NULL 

IF @GetRead = 0 SET @Query = '0,NULL' 
ELSE IF @GetRead = 1 SET @Query = '1' 
ELSE SET @Query = '0,1,NULL' 

SELECT * FROM vwNotifications WHERE NotificationRead IN (@Query) 

上面的查詢基本上失敗當我在IN條款中提供NULL時。 我知道爲什麼感謝this question

但是,如果我採取的方法爲這個問題的答案建議(使用NotificationRead IN (@Query) OR NotificationRead IS NULL),我得到那裏NotificationRead = NULL時,我不需要他們,例如所有記錄,當@GetRead = 1

能否請您指出我的正確的方向嗎?

+1

你不能在'IN' CLASE使用'NULL'因爲'NULL's不能用的'SQL Server'上下文中的其他值/變量進行比較。例如,以下語句將不返回任何內容:'SELECT * FROM [dbo]。[TEST] WHERE [TestColumn] IN(NULL)' – gotqn

回答

6

不,問題在於您提供的值是字符串。

1 IN (1, 2) -- true. 
1 IN ('1, 2') -- false. 

試試這個:

SELECT * 
FROM vwNotifications 
WHERE (@GetRead = 0 AND (NotificationRead = 0 OR NotificationRead IS NULL)) 
OR (@GetRead = 1 AND NotificationRead = 1) 
OR (@GetRead IS NULL AND (NotificationRead IN (0, 1) OR 
          NotificationRead IS NULL)) 
2

其他人可能有更好的辦法,但我會移動你的選擇到每個「如果」語句,並相應修改。

IF @GetRead = 0 
    SELECT * FROM vwNotifications WHERE NotificationRead IS NULL or NotificationRead = 0 
ELSE IF @GetRead = 1 
    SELECT * FROM vwNotifications WHERE NotificationRead = 1 
ELSE 
    SELECT * FROM vwNotifications WHERE NotificationRead IS NULL or NotificationRead in 0, 1 

注意:請不要在生產代碼中使用SELECT *。爲您的列命名。

0

幾個選項:

DECLARE @T TABLE (ID INT IDENTITY(1,1), Notify INT) 
DECLARE @GetRead BIT 
SET @GetRead = 0 

INSERT INTO @T 
     (Notify) 
VALUES (0 -- Notify - int 
     ) 

INSERT INTO @T 
     (Notify) 
VALUES (1 -- Notify - int 
     ) 

INSERT INTO @T 
     (Notify) 
VALUES (NULL -- Notify - int 
     ) 

SELECT * 
FROM @t t 
WHERE @GetRead IS NULL 
    OR (@GetRead = 0 AND (t.Notify =0 OR t.Notify IS NULL)) 
    OR (@getRead = 1 AND t.Notify = @GetRead) 

SELECT * 
FROM @t t 
WHERE @GetRead IS NULL 
    OR ISNULL(t.notify, 0) = @GetRead