SQLite 中的 IF() 语句替代

2021-12-12 00:00:00 sql if-statement sqlite

我有 MySQL (perl) 的代码:

I have the code for MySQL (perl):

UPDATE pages
SET rkey = rkey + 2,
    lkey = IF(lkey >= $key, lkey + 2, lkey)
WHERE rkey >= $key

我需要将此代码与 SQLite 一起使用,但不支持 IF() 函数.我能做什么?

I need to use this code with SQLite, but there is no support of IF() function. What I can do?

推荐答案

对于通用 SQL,您可以使用 CASE:

For generic SQL you can use CASE:

CASE 用于向 SQL 提供 if-then-else 类型的逻辑.它的语法是:

CASE is used to provide if-then-else type of logic to SQL. Its syntax is:

SELECT CASE ("column_name")
  WHEN "condition1" THEN "result1"
  WHEN "condition2" THEN "result2"
  ...
  [ELSE "resultN"]
  END
FROM "table_name"

来自 http://www.sqlite.org/lang_expr.html 部分CASE 表达式"

From http://www.sqlite.org/lang_expr.html section "The CASE expression"

例如

UPDATE pages
SET rkey = rkey + 2,
    lkey = CASE  WHEN lkey >= $key THEN lkey + 2 ELSE lkey END
WHERE rkey >= $key

另一个关于 SQLite & 的链接案例(以子选择更新为例)http://sqlite.awardspace.info/syntax/sqlitepg09.htm

Another link about SQLite & CASE (with example of update with subselect) http://sqlite.awardspace.info/syntax/sqlitepg09.htm

CASE 可以在通用 SQL 中的 UPDATE 中使用,但我没有关于 SQLite 对 CASE UPDATE 支持的信息

CASE can be used in UPDATE in generic SQL, but I have no info about SQLite support of UPDATEs with CASE

http://www.craigsmullins.com/ssu_0899.htm 部分修改数据时使用 CASE 表达式"

http://www.craigsmullins.com/ssu_0899.htm section "Using CASE Expressions When Modifying Data"

相关文章