2014-12-24 103 views
2

我正在使用IF語句來選擇SQL SELECT過程中不爲NULL的列。但是,我收到一條錯誤消息,說我的關鍵字IF附近有句法錯誤。IF語句附近的語法不正確

DECLARE @imgURL_prefix VARCHAR(100) 
DECLARE @imgSmall_Suffix VARCHAR(100) 
DECLARE @imgLarge_Suffix VARCHAR(100) 

SET @imgURL_prefix = '//sohimages.com/images/images_soh/' 
SET @imgSmall_Suffix = '-1.jpg' 
SET @imgLarge_Suffix = '-2.jpg' 

SELECT 
    P.ProductCode as ProductCode, 
    P.HideProduct as HideProduct, 
    P.Photos_Cloned_From as Photos_Cloned_From, 
    @imgURL_prefix + 
     LOWER(IF P.Photos_Cloned_From IS NOT NULL 
      P.Photos_Cloned_From 
     ELSE 
      P.ProductCode 
     END) 
     + @imgSmall_Suffix as PhotoURL_Small, 
    @imgURL_prefix + 
     LOWER(IF P.Photos_Cloned_From IS NOT NULL 
      P.Photos_Cloned_From 
     ELSE 
      P.ProductCode 
     END) 
     + @imgLarge_Suffix as PhotoURL_Large, 
    P.PhotoURL_Small as OriginalSmall, 
    P.PhotoURL_Large as OriginalLarge 
FROM 
    Products_Joined P 

該腳本正常工作沒有IF語句,只用LOWER(P.ProductCode)在它的位置。

+0

啊,謝謝。這解決了它。 –

回答

2

您可以在SQL Server 2012及更高版本和較舊版本使用IIF(Expression, true, false)你有CASE語句

/********* SQL SERVER 2012+ ***********/ 

SELECT 
    P.ProductCode as ProductCode, 
    P.HideProduct as HideProduct, 
    P.Photos_Cloned_From as Photos_Cloned_From, 
    @imgURL_prefix + 
     LOWER(IIF(P.Photos_Cloned_From IS NOT NULL , P.Photos_Cloned_From, P.ProductCode)) 
     + @imgSmall_Suffix as PhotoURL_Small, 
    @imgURL_prefix + 
     LOWER(IIF (P.Photos_Cloned_From IS NOT NULL, P.Photos_Cloned_From, P.ProductCode)) 
     + @imgLarge_Suffix as PhotoURL_Large, 
    P.PhotoURL_Small as OriginalSmall, 
    P.PhotoURL_Large as OriginalLarge 
FROM 
    Products_Joined P 

/********* SQL SERVER Older Versions ***********/ 

SELECT 
    P.ProductCode as ProductCode, 
    P.HideProduct as HideProduct, 
    P.Photos_Cloned_From as Photos_Cloned_From, 
    @imgURL_prefix + 
     LOWER(CASE WHEN P.Photos_Cloned_From IS NOT NULL 
       THEN P.Photos_Cloned_From ELSE P.ProductCode END) 
     + @imgSmall_Suffix as PhotoURL_Small, 
    @imgURL_prefix + 
     LOWER(CASE WHEN P.Photos_Cloned_From IS NOT NULL 
       THEN P.Photos_Cloned_From ELSE P.ProductCode END) 
     + @imgLarge_Suffix as PhotoURL_Large, 
    P.PhotoURL_Small as OriginalSmall, 
    P.PhotoURL_Large as OriginalLarge 
FROM 
    Products_Joined P 
+0

是否有可能爲PhotoURL_Small和PhotoURL_Large創建一個像@ @ imgur_url_large'這樣的變量的整個表達式?我想創建一個'WHERE'子句,聲明不導出已經填寫了相同字段的文件。 –