【问题标题】:Insert records if not exist SQL Server 2005如果不存在则插入记录 SQL Server 2005
【发布时间】:2011-07-01 02:00:06
【问题描述】:

SQL Server 2005 数据库。我有一个包含许多记录的临时表,这些记录来自 RSS 提要,需要定期插入。有些数据会改变,有些数据会保持不变。我只需要插入“新”记录,并消除插入冗余数据导致重复记录的机会。我该如何做到这一点?

示例,临时表,

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

【问题讨论】:

    标签: tsql insert temp-tables


    【解决方案1】:

    一种方法是not exists 子查询:

    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
            )
    

    【讨论】:

    • 太好了,这正是我一直在寻找的解决方案。非常感谢。我还有 1 个问题。如果行的顺序不重要怎么办?我是否必须用尽 where 子句中的所有排列?例如。其中 row1 = temp.row1 或 row1 = temp.row2 或 row1 = temp.row3?
    • @Timothy:是的,但更好的方法是规范化表格。
    • @Timothy:其实没有。比较是为了确定是否已经存在包含您要插入的数据的表行(而不是称为 row1、row2、row3 等的列)。
    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 2021-09-03
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      相关资源
      最近更新 更多