sql - IF 语句附近的语法不正确

标签 sql sql-server if-statement

我使用 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/

相关文章:

sql - 错误 : operator does not exist: integer == integer

mysql - 一个查询中给定时间段内用户的第一个和最后一个记录

sql同名但值不同

javascript - 如何将 if 语句的结果放入我稍后可以返回的新数组中

mysql - 使用 SQL/Mysql 部分枚举行

php - 从数组中的一个查询中插入多行

java - 哪些 MS SQL Server 类型映射到 Types.VARCHAR

sql-server - 在另一个字符串中查找字符串的任何部分transact sql

MYSQL:根据if语句两次获取结果

java - jvm 在这两条 java 行 : 上有什么区别吗