【问题标题】:Incorrect syntax near IF statementIF 语句附近的语法不正确
【发布时间】:2014-12-24 22:13:11
【问题描述】:

我正在使用 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 sql-server if-statement


【解决方案1】:

您可以在 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

【讨论】:

  • 是否可以将 PhotoURL_Small 和 PhotoURL_Large 的整个表达式设为像 @imgur_url_large 这样的变量?我想创建一个WHERE 子句,声明不导出已填写相同字段的文件。
猜你喜欢
  • 2018-06-26
  • 2013-07-07
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多