将IIF转换为CASE语句(THEN和ELSE语句中的错误)

时间:2016-05-23 14:22:00

标签: sql sql-server case iif

这是IIF格式的查询。

SELECT [userinfo].[dp_url]
    ,[message_threads].[thread_id]
    ,[userinfo].[fname]
    ,[userinfo].[lname]
    ,[userinfo].[profile_id]
FROM [message_threads]
LEFT JOIN [userinfo] ON (IIF([message_threads].[from] <> 2, [userinfo].[profile_id] = [message_threads].[from], [userinfo].[profile_id] = [message_threads].[to]))
WHERE (IIF([message_threads].[from] <> 2, [to] = 2, [from] = 2))
ORDER BY [last_updated_on] DESC

到目前为止,这是我用CASE声明所做的。

SELECT [userinfo].[dp_url]
    ,[message_threads].[thread_id]
    ,[userinfo].[fname]
    ,[userinfo].[lname]
    ,[userinfo].[profile_id]
FROM [message_threads]
LEFT JOIN [userinfo] ON (
        CASE 
            WHEN ([message_threads].[from] <> 2)
                THEN ([userinfo].[profile_id] = [message_threads].[from])
            ELSE ([userinfo].[profile_id] = [message_threads].[to])
            END
        )
WHERE (
        CASE 
            WHEN ([message_threads].[from] <> 2)
                THEN ([to] = 2)
            ELSE ([from] = 2)
            END
        )
ORDER BY [last_updated_on] DESC

我收到以下错误:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.

使用等于(=)非常必要。

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

CASE是一个表达式,它返回一个不用于程序流的值,因此可以将您的案例重新排列为:

LEFT JOIN [userinfo]
    ON [userinfo].[profile_id] = (
        CASE 
            WHEN ([message_threads].[from] <> 2)
                THEN ([message_threads].[from])
            ELSE ([message_threads].[to])
            END
    )
WHERE 2 = (
    CASE 
        WHEN ([message_threads].[from] <> 2)
            THEN ([to])
        ELSE ([from])
        END
    )

另一种方法是将其转换为布尔条件:

LEFT JOIN [userinfo] ON 
    ([message_threads].[from] <> 2 AND [userinfo].[profile_id] = [message_threads].[from])
    OR 
    ([message_threads].[from] = 2 AND [userinfo].[profile_id] = [message_threads].[to])

,同样适用于WHERE

答案 1 :(得分:0)

尽量不要使用条件进行比较。通常情况下,ANDOR就足够了:

SELECT . . .
FROM [message_threads] LEFT JOIN
     [userinfo]
     ON ([message_threads].[from] <> 2 AND [userinfo].[profile_id] = [message_threads].[from]) OR
        ([message_threads].[from] = 2 AND [userinfo].[profile_id] = [message_threads].[to])
WHERE 2 IN ([from], [to])

注意:我简化了WHERE。如果过于简单,您可以使用:

WHERE ([message_threads].[from] <> 2 AND [to] = 2) OR
      ([message_threads].[from] - 2 AND [from] = 2)

我还强烈推荐表别名以提高可读性:

SELECT . . .
FROM message_threads mt LEFT JOIN
     userinfo ui
     ON (mt.[from] <> 2 AND ui.profile_id = mt.[from]) OR
        (mt.[from] = 2 AND ui.profile_id = mt.[to])
WHERE 2 IN ([from], [to])

此外,您应使用fromto等保留字作为列名。