简体   繁体   中英

Conditional SQL insert between 2 tables

I have table1 where I have already some nvarchar results.

nvarchar name
name1
name3
name4

I have table2 where I have records in format

nvarchar name | nvarchar subname
name1         | subname1
name1         | subname2
name1         | subname3
name1         | subname4
name2         | subname1
name2         | subname2
name3         | subname3

I need to go through all the records in table2 and group them by name, then insert all name records into table1 but with the condition they dont exist in table1 already.

Could you please help with this? I would rather delete table1 and recreate it from table2 but table1 has some records which are not in table2 and they have to stay there.

Thank you.

This will insert all names from table2 into table1 that isn't already in table1:

INSERT INTO table1 
(
    name
)
SELECT t2.name
FROM   table2 t2
WHERE NOT EXISTS
(
    SELECT 1
    FROM   table1 t1
    WHERE  t1.name = t2.name 
)

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