我使用 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)
即可。
最佳答案
您可以在 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
关于sql - IF 语句附近的语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642582/