I'm trying to create a SQL statement in Firebird 2.5 in order to update an integer quantity by adding to it if the record exists or simply insert a new row. I can't seem to find a real answer to my specific question about adding to a certain quantity if it already exists.
The SQL I could think of is the following :
UPDATE OR INSERT INTO Pencils(Number, Location, Quantity)
VALUES('12345678/90', 'TOP', 20)
MATCHING(Number, Location);
So if there is a matching record I would like to add a certain amount to the actual 20 quantity.
Like I would do with an UPDATE statement :
UPDATE Pencils SET Quantity = Quantity + 20 WHERE Number = '12345678/90'
Is it possible to achieve such result with the UPDATE OR INSERT statement or is there another way?
.
.
EDIT : Solution for a query used with parameters with IBExpert / Delphi
MERGE INTO Pencils AS Dest
USING (SELECT CAST(:myNumb as varchar(30)) AS Number,
CAST(:myLoca as varchar(10)) AS Location,
CAST(:myQuan as integer) AS Quantity
FROM RDB$DATABASE) Src
ON (Dest.Number = Src.Number AND Dest.Location = Src.Location)
WHEN MATCHED THEN
UPDATE SET Dest.Quantity = Dest.Quantity + Src.Quantity
WHEN NOT MATCHED THEN
INSERT (Number, Location, Quantity) VALUES (Src.Number, Src.Location, Src.Quantity);