0

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); 
Alex
  • 523
  • 1
  • 8
  • 20

1 Answers1

0

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.

Community
  • 1
  • 1
Alex
  • 523
  • 1
  • 8
  • 20