SQLite - UPSERT *not* INSERT or REPLACE

后端 未结 18 2890
猫巷女王i
猫巷女王i 2020-11-21 23:53

http://en.wikipedia.org/wiki/Upsert

Insert Update stored proc on SQL Server

Is there some clever way to do this in SQLite that I have not thought of?

18条回答
  •  孤城傲影
    2020-11-22 00:17

    I realize this is an old thread but I've been working in sqlite3 as of late and came up with this method which better suited my needs of dynamically generating parameterized queries:

    insert or ignore into (, , , ...) values(, , , ...); 
    update 
    set =, =, ... where changes()=0 and =;

    It's still 2 queries with a where clause on the update but seems to do the trick. I also have this vision in my head that sqlite can optimize away the update statement entirely if the call to changes() is greater than zero. Whether or not it actually does that is beyond my knowledge, but a man can dream can't he? ;)

    For bonus points you can append this line which returns you the id of the row whether it be a newly inserted row or an existing row.

    select case changes() WHEN 0 THEN last_insert_rowid() else  end;
    

    提交回复
    热议问题