简体   繁体   中英

SQL INSERT missing rows from Table A to Table B

I'm trying to insert rows into table 'Data' if they don't already exist.

For each row in Export$, I need the code to check 'Data' for rows that match both Period (date) and an ID (int) - if the rows don't already exist then they should be created.

I'm pretty sure my 'NOT EXISTS' part is wrong - what's the best way to do this? Thanks for all your help

    IF NOT EXISTS (SELECT * FROM Data, Export$ WHERE Data.ID = Export$.ID AND Data.Period = Export$.Period)
    INSERT INTO Data (Period, Performance, ID)
    SELECT Period, [Return], [ID] FROM Export$

try this:

INSERT INTO Data (Period, Performance, ID)
SELECT Period, [Return], [ID] 
FROM Export$ e
where not exists (
select *
from Data
where  ID = e.ID and Period = e.Period)

try something like, will need tweaking to fit your tables

insert into data
select * from export
left join data on data.id = export.id
                     and data.period = export.period
where data.id is null

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