WHEN

2013-05-21 69 views
0

鑑於這種T-SQL代碼在CASE「指定的非布爾類型的表達式」:WHEN

SELECT CASE 
     WHEN (Cast (CASE 
         WHEN Isnull(bpe.new, 0) = 0 
          AND Isnull(bpe.regular, 0) = 0 
          AND Isnull(bpe.bargain, 0) = 0 THEN 0 
         ELSE 1 
         END AS BIT) 
       AND @siteID IS NULL 
       OR bpe.siteid = @siteID) THEN 1 
     ELSE 0 
     END AS SiteHasBrandException 
FROM brandpromoexceptions AS bpe 

我得到的錯誤消息:

在指定的非布爾類型的表達式上下文中預期的條件TSQL

這是爲什麼?

回答

1

如果你的意思是零「假」爲第一位,查詢應該是等同於:

SELECT CASE WHEN 
NOT (ISNULL(bpe.new, 0) = 0 
     AND Isnull(bpe.regular, 0) = 0 
     AND Isnull(bpe.bargain, 0) = 0) 
AND (@siteID IS NULL 
     OR bpe.siteid = @siteID) 
THEN 1 
ELSE 0 
END AS SiteHasBrandException 
FROM brandpromoexceptions AS bpe 

您可能需要小心使用該「或」條款,或添加括號以進行說明。我猜在這裏。

0

您正在將您的第一個CASE聲明傳遞給CAST而不是條件聲明。該錯誤消息幾乎拼出來了。

我不確定你想要做什麼,但你似乎明白,你需要傳遞一個布爾值到CASE WHEN根據你的後續使用CASE,所以希望這有助於。

這是嘗試改變你的代碼,這在黑暗中拍攝:

SELECT CASE 
    WHEN (Cast (CASE 
        WHEN Isnull(bpe.new, 0) = 0 
         AND Isnull(bpe.regular, 0) = 0 
         AND Isnull(bpe.bargain, 0) = 0 THEN 0 
        ELSE 1 
        END AS BIT) = 1 
      AND @siteID IS NULL 
      OR bpe.siteid = @siteID) THEN 1 
    ELSE 0 
    END AS SiteHasBrandException 
FROM brandpromoexceptions AS bpe