将多个唯一行插入表中

时间:2014-07-25 02:42:09

标签: asp.net sql sql-server-2008

我对SQL并不熟悉。我试图将多行数据插入表中,如果BusinessFilterPhrase列中存在重复值的行,则不要插入。我写了一个我认为应该是的伪代码。

if (filterCategoryList != null)
{
   foreach (KeyValuePair<string, int> filter in filterCategoryList)
   {
      cmd.CommandText = "insert into tblBusinessName (BusinessFilterPhrase,BusinessCategoryID)" +
                        "select @BusinessFilterPhrase,@BusinessCategoryID" +
                        "from tblBusinessName as t1" +
                        "where NOT EXISTS" +
                        "( select * from tblBusinessName as d1 where d1.BusinessFilterPhrase = @BusinessFilterPhrase) ";

      cmd.Parameters.AddWithValue("@BusinessFilterPhrase", filter.Key);
      cmd.Parameters.AddWithValue("@BusinessCategoryID", filter.Value.ToString());

      cmd.ExecuteNonQuery();
   }
}

1 个答案:

答案 0 :(得分:0)

您的代码看起来正确。我会把它写成:

insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
    select @BusinessFilterPhrase, @BusinessCategoryID
    from tblBusinessName t1
    where NOT EXISTS (select 1
                      from tblBusinessName d1
                      where d1.BusinessFilterPhrase = @BusinessFilterPhrase
                     )

(这些变化只是装饰性的。)

编辑:

如果性能有问题,请在BusinessFilterPhrase上创建索引:

create index idx_tblBusinessName_BusinessFilterPhrase on tblBusinessName(BusinessFilterPhrase);

如果您希望数据库强制执行列的唯一性,则可以将其设为unique索引(当插入重复值时,它将生成错误。)