Insert records if not exist SQL Server 2005

泄露秘密 提交于 2019-12-11 02:05:11

问题


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

回答1:


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
        )



回答2:


Try this:

con.Open();
SqlCommand cmd = new SqlCommand("If Not Exists(select * from stholidays where holiday='"+ dd + "') begin insert into stholidays values('" + dateTimePicker12.Text + "','" + dateTimePicker20.Text + "','" + dateTimePicker13.Text + "','" + mbk + "','" + dateTimePicker14.Text + "','" + dateTimePicker15.Text + "','" + lt + "','" + dateTimePicker16.Text + "','" + dateTimePicker17.Text + "','" + ebk + "','" + dateTimePicker18.Text + "','" + dateTimePicker19.Text + "','" + textBox105.Text + "','" + textBox106.Text + "','" + textBox107.Text + "','" + dd + "','" + textBox104.Text + "')end", con);
cmd.ExecuteNonQuery();
con.Close();


来源:https://stackoverflow.com/questions/5062980/insert-records-if-not-exist-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!