我正在使用IF语句,以便在SQL SELECT过程中选择非NULL的列。但是,我收到错误,说我的语法在关键字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