Inserting new rows in table if already not exisitng

时间:2019-01-18 18:33:44

标签: sql sql-server tsql

I have a table than over time can get bigger and I want to insert some of its rows in another table but I also want to make sure I am not duplicating the rows that I had inserted before. So here is the type of condition for my insert:

INSERT INTO SecondTable(Col1,Col2)
SELECT Col5,Col6
FROM
FirstTable ft
WHERE ft.RecType = 'ABC'

So if I keep running this it will keep inserting the same rows again and again. How can I tell it only insert if it is not already there?

3 个答案:

答案 0 :(得分:2)

You can use not exists:

INSERT INTO SecondTable(Col1,Col2)
    SELECT Col5,Col6
    FROM FirstTable ft
    WHERE ft.RecType = 'ABC' AND
          NOT EXISTS (SELECT 1 FROM SecondTable t2 WHERE t2.col1 = ft.col5 AND t2.col2 = ft.colt6);

答案 1 :(得分:1)

Generate unique constraint on table with proper columns which identifies unicity. This will also help you to preserve integrity of your table. when you try to insert records into the RDBMS will give you an error.

ALTER TABLE SecondTable
ADD UNIQUE (col1, col2, col3);

答案 2 :(得分:-1)

INSERT INTO SecondTable(Col1,Col2)
SELECT Col5,Col6
FROM FirstTable ft
LEFT JOIN SecondTable st ON st.Col1 = ft.Col1
WHERE st.Col1 IS NULL AND ft.RecType = 'ABC'