Upsert in SQLite with running total if record is f

2019-03-03 15:36发布

问题:

I would like to upsert data to a table in SQLite, but the column being updated (if the record is found) must be a running total. I am using a parameterized query, and am having trouble with the syntax.

My understanding thus far is that COALESCE is the way to do an upsert in SQLite, so this is the skeleton of what I've got thus far:

INSERT OR REPLACE INTO TABLE (ID, Quantity) 
VALUES (:ID, COALESCE(Quantity + :Quantity_change, :Quantity_change) 

In other words, if the record is found, add the quantity change to the current quantity, else insert the record with the quantity change as the quantity number.

In SQL server it's working perfectly with a merge query:

MERGE ......
.....
WHEN MATCHED THEN UPDATE SET Quantity = Quantity + :Quantity_change
WHEN NOT MATCHED THEN INSERT (..Quantity), VALUES (.. :Quantity_change); 

回答1:

OK so this is working for me:

INSERT OR REPLACE INTO TABLE (ID, Quantity) 
VALUES (:ID, 
        COALESCE(
          (SELECT Quantity FROM TABLE WHERE ID = :ID) + :Quantity_change, :Quantity_change));

Thanks to this SO link for the help.