2014-07-25 66 views
0

我對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(); 
    } 
} 

回答

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索引。 。

+0

有沒有另外一種方式可以在查詢進入像500>插入時更好地擴展?例子?加入? –