如果不存在则插入多行

时间:2017-12-07 21:38:41

标签: sql sql-server

我有两张桌子。表A和表B.表A具有一些已存在的唯一ID。我想在表A中插入一个新的自定义行,其中我的条件的那些行存在于表B而不是表A中。如何插入表B中表A中不存在的所有行?我正在寻找MSSQL解决方案。

我尝试了以下两种形式,但似乎都不起作用:

示例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)

例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 

3 个答案:

答案 0 :(得分:4)

你正在寻找MERGE。以下伪代码将帮助您:

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]); 

答案 1 :(得分:1)

您与第一个查询非常接近。问题是子查询中的JOIN

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
                     );

注意:

  • 表别名使查询更易于编写和阅读。
  • 名为Selection1等的列是可疑的。您应该将三行放入"选择"某种表格。

答案 2 :(得分:1)

使用EXCEPT可以提高性能,因为MERGE需要对数据进行排序。

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

唯一的事情是列的数量和类型必须在两个SELECT中匹配