One option is to put a DELETE
statement before your INSERT INTO
statement, for example...
DELETE FROM food
WHERE FoodName IN (SELECT FoodName FROM NEWfoods)
..., and simplify your INSERT INTO
statement:
INSERT INTO food
SELECT -- Also, consider SELECT DISTINCT here unless you truly want repeat records like 'Bread'|'Grain', 'Bread'|'Grain'.
nf.FoodName
,nf.FoodType
FROM NEWfoods AS nf
Whereas the results of SELECT * FROM food
is...
FoodName FoodType
-------------------------------------------------- --------------------------------------------------
Apples Fruit
Avocado Fruit
Bananas Fruit
Mangos Fruit
Bread Grain
Cottage Cheese Dairy
Tacos Meals
Carrots Vegetables
Celery Vegatables
(9 row(s) affected)
...and SELECT * FROM NEWfoods
is...
FoodName FoodType
-------------------------------------------------- --------------------------------------------------
Avocado Vegetables
Apples Fruit
Salt Preservative
Turkey Protein
Bread Grain
Bread Grain
Tacos Meals
(7 row(s) affected)
...prior to the DELETE
and revised INSERT INTO
, the result of the SELECT * FROM food
becomes the following after the DELETE
and revised INSERT INTO
statements are run:
FoodName FoodType
-------------------------------------------------- --------------------------------------------------
Avocado Vegetables
Apples Fruit
Bananas Fruit
Mangos Fruit
Salt Preservative
Cottage Cheese Dairy
Turkey Protein
Carrots Vegetables
Celery Vegatables
Bread Grain
Bread Grain
Tacos Meals
(12 row(s) affected)
Of course, if a lot of NEWfoods
records will perfectly match food
records, this will produce a lot of unnecessary deletes as-is. You could enhance the DELETE
(and INSERT INTO
) statement(s) to avoid this, but it really depends on the particulars of the data('s life cycle).
Also, you could of course wrap the DELETE
and INSERT INTO
statements in a transaction to make them all-or-nothing.
As @Thomas points out, EXCEPT
and MERGE
are great ways to do what you want as well if you are using SQL Server 2008 or later; both are frankly more elegant; but distinct DELETE
and INSERT INTO
statements are an option.