简体   繁体   中英

SQL Server - Insert into tbl2 from tbl1 where tbl1.column1 <> tbl2.column1

I have 2 tables, which have the same columns. Like the topic title says, I'd like to insert into the 2nd tables the records of the 1st table where the values of the same column are different.

I've tried with:

SELECT * FROM Table1 INNER JOIN Table2 ON Table2.column1 <> Table1.column1;

or

SELECT * FROM Table1, Table2 WHERE Table1.column1 <> Table2.column1;

But the results are replicated values from the two tables, I think because I select from both tables.

If I do the following:

INSERT INTO Table2 SELECT * FROM Table1 WHERE Table1.column1 <> Table2.column1;

it throws me an error of:

Impossibile associare l'identificatore in più parti "Table2.column1"

You cannot compare column values unless you specify which row you are talking about. In your case, it sounds like the answer to the question "which row" is "any row in Table2 ", so you can apply the existential quantifier to rows of Table2 to decide which rows of Table1 you wish to insert. Long story short, you tell SQL to insert the missing rows.

The corresponding SQL is as follows:

INSERT INTO Table2
    SELECT * FROM Table1 t1
    WHERE NOT EXISTS (
        SELECT * FROM Table2 t2
        WHERE t1.column1 = t2.column1
    )

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