简体   繁体   中英

How to update the rows of a table from another table? SQL Server

I want to be able to update the data from one table to another without duplicating the rows that already exist in the table where the data will be copied.

I'm using SQL Server 2008.

This is the structure of the table:

TABLE1

date       | value
-----------+----------
2018-05-09 |    27020
2018-05-08 |    27019
2018-05-07 |    27017
.
.
2011-05-08 |      128

TABLE2

date        |  value
------------+---------
2018-06-14  | 27402
2018-06-13  | 27401
2018-06-12  | 27400
.
.
2011-05-08  |   128

I'm using:

INSERT INTO TABLE1
    SELECT * 
    FROM TABLE2 
    WHERE ...

I assume you meant to insert rows into table1 from table2 for the missing dates:

insert into table1 ([date], [value])
select [date], [value]
from table2 t2
where not exists (select * from table1 t3 where t3.[date] = t2.[date]);

Seems you want to insert the new records from Table2 to Table1 So you can use this query :

Insert into Table1 (date, value)
select date, value from Table2 
where not exists (
                select 1 from table1 where table1.[date] = table2.[date] and table1.value = table2.value
                )
Insert into Table1 (date, value)
select date, value from Table2 EXCEPT SELECT date, value from Table1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM