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 
                INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.
There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.
The basic syntax for INSERT IF NOT EXISTS is as follows. Copy INSERT INTO name_of_the_table (column_name) SELECT * FROM (SELECT value_name) AS val WHERE NOT EXISTS (<conditonal expression>); In the name_of_the_table we insert the value_name in the column_name if the conditional expression is met.
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 );
                        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)
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With