SQLite查询中的CASE语句

时间:2011-02-11 12:12:06

标签: sqlite nested case

为什么此查询不起作用? :(我试图替换嵌套的IF语句“... SET lkey = IF(lkey> = 11,lkey - 5,IF(lkey> 5,lkey + 2,lkey))”

UPDATE pages
SET lkey = CASE lkey WHEN lkey >= 11 THEN
        lkey - 5
    ELSE
        CASE lkey WHEN lkey > 5 THEN
            lkey + 2
        ELSE
            lkey
        END
    END,
    rkey = CASE lkey WHEN lkey >= 11 THEN
        rkey - 5
    ELSE
        CASE rkey WHEN rkey < 11 THEN
            rkey + 2
        ELSE
            rkey
        END
    END
WHERE rkey > 5 AND
    lkey < 12;

2 个答案:

答案 0 :(得分:78)

此子句中的语法错误(和类似的)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

要么是

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

所以在你的情况下,它会显示:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

查看文档(CASE表达式):

http://www.sqlite.org/lang_expr.html

答案 1 :(得分:29)

此外,您不必使用嵌套CASE。您可以使用多个WHEN-THEN行,ELSE行也是可选的,尽管我建议它

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END