Advertise with us

How to Insert mutiple unique rows into a table

I am not familiar with SQL that much. I'm trying to insert multiple rows of data into a table that if there exist a row with with duplicate value in BusinessFilterPhrase column then just don't insert. I wrote a pseudocode of what I think it should be.

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


Last updated:1/8/2015 2:51:51 AM

1 Answers

Takeshi Okada
Takeshi Okada

You code looks correct. I would write it as:

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

(The changes are only cosmetic.)


If performance is an issue, create an index on BusinessFilterPhrase:

create index idx_tblBusinessName_BusinessFilterPhrase on tblBusinessName(BusinessFilterPhrase);

You can make this a unique index, if you want the database to enforce the uniqueness of the column (it will generate an error when duplicate values would be inserted).