简体   繁体   中英

Insert different rows between Table A and Table B into Table B

I have two exactly identical tables. Table A has eg 100 rows, Table B has 60 rows. Now I want to insert the "missing" rows from Table A into Table B. To find the different rows I would use:

select * from tableA where language = 4
union
select * from tableB where language = 4

How do I use this code correctly with the "Insert into" statement? My idea:

Insert into tableB
(Select * from tableA where language = 4
union
select * from tableB where language = 4)

Best regards

UNION may be an option but it would cause duplications. I would prefer MINUS operation.

insert into tableB (
select * from tableA where language=4
MINUS
select * from tableB where language=4)
Insert into tableB
(Select * from tableA where language = 4
EXCEPT
select * from tableB where language = 4)

Perhaps EXCEPT ALL should be used, treats duplicates differently.

Outer Join

INSERT INTO TableB (Column1,Column2) 
  SELECT DISTINCT
    a.Column1 ,
    a.Column2 ... more column
  FROM    TableA AS a
    LEFT OUTER JOIN TableB AS b ON b.Column1 = a.Column1 
                                          AND b.Column2 = a.Column2 
    WHERE b.Colum2 IS NULL AND b.Colum1 IS NULL ; 

Not Exists

INSERT INTO TableB (Column1,Column2) 
SELECT  a.Column1 ,
    a.Column2...
FROM    Table1 AS a
WHERE   NOT EXISTS ( SELECT *
                 FROM   Table2 AS b
                 WHERE  b.Column1 = a.Column1 
                        AND b.Column2= a.Column2);

Except

INSERT INTO TableB (Column1,Column2) 
SELECT  Column1,
    Column2
FROM    TaBLE1
EXCEPT
SELECT  Column1,
    Column2
FROM    #TaBLE2;

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