I have a query where I am inserting some records as long as those records do not exist in a table, but I would really like to do is to UPDATE a field of that record in that other table if it is there otherwise insert it as it is doing it right now. I would appreciate any help, or advises. Can it be done?
-- Insert into my my Toys table if record not already there (but would like to also update one of its fields)
INSERT INTO Toys (Date, ToyId)
SELECT inv.Date, inv.Id
FROM Inventory inv
JOIN InventoryStats invSt ON inv.Id = invSt.InventoryId
WHERE (invSt.IsFixed = 1 AND invSt.IsSent = 0 AND invSt.Date >= '01/01/2012 12:00 PM') AND (inv.Id NOT IN (SELECT ToyId FROM Toys))
Basically if the inv.Id is already in Toys table I do not want to insert it again but I would like to update one of its flags while on this process , like
UPDATE Toys SET NewShipDate = inv.Date WHERE ToyId = Inv.Id
You are looking for the MERGE Statement – INSERT a record if it does not exist, UPDATE it if it does.