I haven't used the merge tool mentioned in the comments, it might be better, but here is how I would do it:
First, change your existing query into something that inserts into a temporary table (a temp-table is indicated with a #
before its name):
select <your select-clause>
into #temp
from <your from-clause>
where <your where-clause>
So now we have 2 tables, both containing data. Let's call the table we are adding to S
, and the temporary table to be used as a basis for the data to be added T
.
First, we need to figure out which of the rows in T
already exists in S
. They probably have a common row identifier, let's call it id
, and find the set of rows in T
that have a corresponding row in S
through a simple join:
select * from S s join T t on s.id = t.id;
The rows returned in this query is the rows that we want to update. To do so, a query of this type can be used:
update S
set c1 = (select t.c1 from T t where t.id = S.id),
c2 = (select t.c2 from T t where t.id = S.id),
...
cN = (select t.cN from T t where t.id = S.id)
where S.id in (
select t.id
from S s join T t on s.id = t.id);
We update all rows in S
that exists in both T
and S
, and "pick" the values from T
with inner selects.
Next, we need to insert the rows in T
that are not already in S
. This query will do that:
insert into S (id, c1, c2, ..., cN)
select id, c1, c2, ..., cN
from T where id not in (select id from S);
(Could have used a join in the where
-clause, but this works just as well..)
This query will insert the rows in T
that are not already in S
into S
.