SQLite - UPSERT *not* INSERT or REPLACE

后端 未结 18 2628
猫巷女王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:33

    Following Aristotle Pagaltzis and the idea of COALESCE from Eric B’s answer, here it is an upsert option to update only few columns or insert full row if it does not exist.

    In this case, imagine that title and content should be updated, keeping the other old values when existing and inserting supplied ones when name not found:

    NOTE id is forced to be NULL when INSERT as it is supposed to be autoincrement. If it is just a generated primary key then COALESCE can also be used (see Aristotle Pagaltzis comment).

    WITH new (id, name, title, content, author)
         AS ( VALUES(100, 'about', 'About this site', 'Whatever new content here', 42) )
    INSERT OR REPLACE INTO page (id, name, title, content, author)
    SELECT
         old.id, COALESCE(old.name, new.name),
         new.title, new.content,
         COALESCE(old.author, new.author)
    FROM new LEFT JOIN page AS old ON new.name = old.name;
    

    So the general rule would be, if you want to keep old values, use COALESCE, when you want to update values, use new.fieldname

提交回复
热议问题