Search code examples
t-sqlinserttemp-tables

Insert records if not exist SQL Server 2005


SQL Server 2005 Database. I have a temporary table with many records, these records are coming from an RSS feed and need to be inserted periodically. Some of the data will change, and some will remain the same. I only need to insert the 'new' records, and eliminate the chance of inserting redundant data resulting in duplicate records. How do I accomplish this?

Example, tempTable,

        BEGIN
            INSERT INTO myTable
                (
                    row1
                    ,row2
                    ,row3
                )
            SELECT
                row1
                ,row2
                ,row3
            FROM @tempTable
        END

Solution

  • One way is a not exists subquery:

    INSERT  myTable
            (row1, row2, row3)
    SELECT  row1, row2, row3
    FROM    @tempTable temp
    WHERE   NOT EXISTS
            (
            SELECT  *
            FROM    myTable
            WHERE   row1 = temp.row1
                    and row2 = temp.row2
                    and row3 = temp.row3
            )