数据集来自select查询时不存在的SQL插入

时间:2015-05-25 12:28:16

标签: sql sql-server sql-server-2008 upsert

我正在尝试执行以下查询

INSERT INTO MyTable(Column1, Column2)
SELECT Column1Value, 'Temp'   -- This will return multiple values which are to be inserted.
FROM Table2 t2
    INNER JOIN Table3 t3 ON t2.Column1 = t3.Column1
    ...
    Few more joins
    ...
WHERE t2.Column3 = 0

正如您在插入查询数据中看到的那样,行来自另一个查询。 (这就是为什么我不能在这里使用WHERE != something) 我能够运行此查询,但问题是当几个记录已经存在时,这将抛出异常。所以我需要确保只对那些不存在的记录执行此查询。

有人可以帮忙吗?

谢谢&的问候,

内甚

2 个答案:

答案 0 :(得分:1)

如何添加条件如下:

where not exists (select 1
                  from mytable t
                  where t.column1 = column1value and t.column2 = 'temp'
                 )

这假设两列一起构成唯一或主键。

您的选择也可能返回重复值,这会导致问题。因此,您也可以将select更改为select distinct

INSERT INTO MyTable(Column1, Column2)
    SELECT DISTINCT Column1Value, 'Temp'
    FROM Table2 t2
        INNER JOIN Table3 t3 ON t2.Column1 = t3.Column1
        ...
        Few more joins
        ...
    WHERE t2.Column3 = 0 AND
          NOT EXISTS (select 1
                      from mytable t
                      where t.column1 = column1value and t.column2 = 'temp'
                     );

答案 1 :(得分:0)

你可以这样做:

INSERT INTO MyTable(Column1, Column2)
SELECT Column1Value, 'Temp'
FROM Table2 t2
    INNER JOIN Table3 t3 ON t2.Column1 = t3.Column1
    ...
    Few more joins
    ...
WHERE t2.Column3 = 0
AND 
NOT EXISTS (SELECT Column1 FROM MyTable MT WHERE MT.col1 = t2.col1);