SQLite中的条件更新

时间:2012-02-26 13:55:38

标签: sql sqlite

我可以在SQLite中创建这样的声明吗?

update books set
(if number_of_pages > 0 then number_of_pages = number_of_pages - 1)
where book_id = 10

是否有适用的语法?

3 个答案:

答案 0 :(得分:15)

CASE语句应使用以下语法:

UPDATE
  books
SET number_of_page = CASE WHEN number_of_pages > 0 THEN (number_of_pages - 1) ELSE 0 END
WHERE whatever_condition

答案 1 :(得分:4)

不等于这句话吗?

update books set number_of_pages = number_of_pages - 1 where number_of_pages>0

编辑:

根据新声明:

update books set number_of_pages = number_of_pages - 1 where number_of_pages>0 and book_id = 10

答案 2 :(得分:1)

如果您只想有条件地更新某些行并保留其他行,请执行以下操作:

update books
set number_of_pages = number_of_pages - 1
where number_of_pages > 0 AND book_id = 10

如果要将所有行(book_id = 10)更新为不同的值,可以使用2个具有“相反”条件的语句。假设0是“其他”值,那将是这样的:

update books
set number_of_pages = number_of_pages - 1
where number_of_pages > 0 AND book_id = 10

update books
set number_of_pages = 0
where number_of_pages <= 0 AND book_id = 10

或者像其他人建议的那样使用CASE。