18

I have a sql table that has two columns id and name. I have list of names about 20 and I need to write a query that checks if name exists before insert.

Is there a better way of doing this rather then just having the below query 20 times but with different names (I need do this in t-sql):

IF NOT EXISTS(SELECT* 
              FROM   mytable 
              WHERE  name = 'Dan') 
  BEGIN 
      INSERT INTO mytable 
                  (name) 
      VALUES     ('dan') 
  END 
5
  • 1
    Where is the list of names you want to exclude, stored? Commented Aug 12, 2014 at 14:06
  • Just on an email at the minute. It needs to be tsql I can't use the import tool Commented Aug 12, 2014 at 14:07
  • Can you use the name as a parameter? Commented Aug 12, 2014 at 14:07
  • Ye can do, how do I get it to check a list of names? Commented Aug 12, 2014 at 14:08
  • You could try INSERT INTO mytable ... WHERE Name NOT IN ('<Name1>', '<Name2>', '<Name3>'...) Commented Aug 12, 2014 at 14:10

8 Answers 8

27
INSERT INTO MyTable (Name)
SELECT  NewNames.Name
FROM    ( VALUES ('Name1'), ('Name2'), ('Name3') ) AS NewNames (Name)
WHERE   NOT EXISTS ( SELECT 1
                     FROM   MyTable AS MT
                     WHERE  MT.Name = NewNames.Name );
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a limit on how many values you can have in the from clause? Can it be in the millions?
9

I think you could use a merge statement:

MERGE INTO myTable AS Target
USING (VALUES ('name1'),('name2'),('...')) AS source (NAME)
ON Target.NAME = Source.NAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (NAME) VALUES (name)

Comments

5

You can filter values with NOT EXISTS

INSERT INTO myTable (
    Name
)
SELECT DISTINCT
    Name
FROM (
        VALUES ('Name 1'),
               ('Name 2')
    ) AS NewNames(Name)
WHERE
    NOT EXISTS (SELECT 1 FROM TargetTable WHERE myTable.Name = NewNames.Name)

If your new names are in another table, you can change the select query in the above one.

Please note, that the DISTINCT keyword is necessary to filter out the duplications in the source data.

1 Comment

It worked for me! If anyone is trying to do same for tables with multiple columns, you can do as: INSERT INTO myTable ( name, code ) SELECT DISTINCT name, code FROM ( VALUES ('Name 1','Code 1'), ('Name 2','Code2') ) AS NewNames(name, code) WHERE NOT EXISTS (SELECT 1 FROM myTable m WHERE m.name = NewNames.name)
3

I would do this using insert:

with names as (
      select 'Dan' as name union all
      select 'name2' union all
      . . .
     )
insert into myTable(name)
    select distinct name
    from myTable
    where not exists (select 1 from mytable t2 where t2.name = t.name);

Note: you may want to create a unique index on mytable(name) so the database does the checking for duplicates.

Comments

2
INSERT INTO MyTable (Name)
SELECT Name FROM
(
    VALUES ('Name 1'),
           ('Name 2')
) AS Names(Name)
WHERE Name NOT IN
(
    SELECT Name FROM MyTable
)

Comments

1

untested so there might be some minor errors:

merge into mytable x
using (
    values ('name1')
         , ('name2')
         , ...
         , ('namen')
) as y (name)
    on x.name = y.name
when not matched then 
    insert (name)
    values (y.name)

Comments

0

INSERT IGNORE INTO myTable (column1, column2) VALUES (val1, val2),(val3,val4),(val5,val6);

INSERT IGNORE will allow skip on duplicate values

1 Comment

IGNORE doesn't exist in SQL SERVER. Similar functionality being: stackoverflow.com/a/21220868/1918179
0
  1. Use INSERT INTO ... SELECT to insert data conditionally

  2. Each row check with WHERE NOT EXISTS to prevent duplicates based on the column name

  3. Use UNION ALL to combine all rows into a single query

INSERT INTO mytable (name)
SELECT * FROM (
    SELECT 'Dan' AS name,
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE name = 'Dan')
    UNION ALL
    SELECT 'Bob'
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE name = 'Bob')
    UNION ALL
    SELECT 'Mike'
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE name = 'Mike')
) AS new_values;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.