简体   繁体   中英

Insert Multiple Rows If Not Exists

I have two tables. Table A and Table B. Table A has some unique id's already existing. I want to insert a new custom row into Table A where those rows for my condition exist in Table B and not in Table A. How do I insert all rows from Table B that don't exist in Table A? I am looking for MSSQL solution.

I have tried the following two forms but neither seem to work:

Example A:

INSERT into TableA
(
    Id, 
    Selection1, 
    Selection2,
    Selection3        
)
SELECT 
(
    Id,  /* this field comes from TableB */
     0,
     0,
     1   
)
from TableB 
where NOT EXISTS ( SELECT * FROM TableA
                INNER JOIN TableB
                ON TableA.Id = TableB.ID)

Example B

IF NOT EXISTS ( SELECT * FROM TableA
        INNER JOIN TableB
        ON TableA.Id = TableB.Id)

    INSERT into TableA
    (
        Id, 
        Selection1, 
        Selection2,
        Selection3
    )
    SELECT 
    (
        Id,  /* this field comes from TableB */
         0,
         0,
         1   
    )
    from TableB 

You're looking for MERGE. The following pseudo code will get you there:

MERGE INTO [TableA] AS [target]
using (SELECT distinct [Id] /* multiple ids exist in table a */
              , [Selection1]
              , [Selection2]
              , [Selection3]
       FROM   [TableB]) AS [source]
ON [target].[ID] = [source].ID
WHEN NOT matched THEN
    INSERT ([Id]
            , [Selection1]
            , [Selection2]
            , [Selection3])
    VALUES ([Id]
            , [Selection1]
            , [Selection2]
            , [Selection3]); 

You are very close with the first query. The problem is the JOIN in the subquery:

INSERT into TableA (Id, Selection1, Selection2, Selection3)
    SELECT Id, /* this field comes from TableB */, 0, 0, 1
    from TableB b
    where NOT EXISTS (SELECT 1
                      FROM TableA a
                      WHERE a.Id = b.ID
                     );

Notes:

  • Table aliases make the query easier to write and to read.
  • Columns called Selection1 , etc. are suspicious. You should probably be putting three rows into a "selections" table of some sort.

Using EXCEPT could be performance improvement, because MERGE needs data to be sorted.

INSERT into TableA
(
    Id, 
    Selection1, 
    Selection2,
    Selection3        
)
SELECT Id,0,0,1   
from TableB 
EXCEPT
SELECT Id,0,0,1 
FROM TableA INNER JOIN TableB
                ON TableA.Id = TableB.ID

only thing is number and types of columns have to match in both SELECTs

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