Wednesday, June 1, 2011

Multi record Insert into column with unique key constraint and ignore duplicate

Lets say i have got a table named tblcity and it contains two columns cityid and cityname.
this table contains lets say 1000 records.
now wants to insert some cities from a another table into this table and i wants that if city already exists in tblcity then it should not be reinserted.

to do so, mysql provides very good facility to ignore duplicate like:

INSERT IGNORE INTO Table2(Id, Name) SELECT Id, Name FROM Table1

Source: My Dear Friend Jitendra Dhoot

unfortunately sql server not provide this facility to use "ignore" keyword to ignore duplicate values while performing bulk insert.

To do so in sql server you will have do:
When you are creating a unique index on column, at that time you can set it to "ignore duplicates", in which case SQL Server will ignore any attempts to add a duplicate.

Otherwise we have 3 other option:

Using NOT EXISTS:

INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE NOT EXISTS(SELECT id
                    FROM TABLE_2 t2
                   WHERE t2.id = t1.id)
Using NOT IN:

INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE t1.id NOT IN (SELECT id
                       FROM TABLE_2)
Using LEFT JOIN/IS NULL:

INSERT INTO TABLE_2
  (id, name)
   SELECT t1.id,
          t1.name
     FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
    WHERE t2.id IS NULL


Compiled By Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates