IF() statement alternative in SQLite

人走茶凉 提交于 2020-01-09 07:12:53

问题


I have the code for MySQL (perl):

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

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


回答1:


For generic SQL you can use CASE:

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"

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

E.g.

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

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

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 section "Using CASE Expressions When Modifying Data"




回答2:


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

??? it to

UPDATE pages
SET lkey = lkey + 2
WHERE rkey >= $key AND lkey >= $key

UPDATE pages
SET rkey = rkey + 2,
WHERE rkey >= $key

Isn't it better?



来源:https://stackoverflow.com/questions/4874285/if-statement-alternative-in-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!