问题描述
对于经典的如何插入新记录或更新已存在的记录",我找到了一些可能"的解决方案,但我无法让其中任何一个在 SQLite 中工作.
I've found a few "would be" solutions for the classic "How do I insert a new record or update one if it already exists" but I cannot get any of them to work in SQLite.
我有一个表定义如下:
CREATE TABLE Book
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name VARCHAR(60) UNIQUE,
TypeID INTEGER,
Level INTEGER,
Seen INTEGER
我想做的是添加一个具有唯一名称的记录.如果名称已存在,我想修改字段.
What I want to do is add a record with a unique Name. If the Name already exists, I want to modify the fields.
有人能告诉我怎么做吗?
Can somebody tell me how to do this please?
推荐答案
看看 http://sqlite.org/lang_conflict.html.
你想要这样的东西:
insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);
请注意,如果该行已存在于表中,则任何不在插入列表中的字段都将设置为 NULL.这就是 ID
列有一个子选择的原因:在替换情况下,语句会将其设置为 NULL,然后分配一个新的 ID.
Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID
column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.
如果您想在替换案例中的行保留特定字段值但在插入案例中将该字段设置为 NULL,则也可以使用此方法.
This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.
例如,假设您想单独保留 Seen
:
For example, assuming you want to leave Seen
alone:
insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
(select ID from Book where Name = "SearchName"),
"SearchName",
5,
6,
(select Seen from Book where Name = "SearchName"));
这篇关于如果不存在则插入 其他更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!