Link to home
Start Free TrialLog in
Avatar of Arnold Layne
Arnold LayneFlag for United States of America

asked on

How to check if a record already exists before inserting a new one

I'm looking for a simple clean way to make an MS SQL statement that selects all of column1 and column2 from one table, and inserts them into another table as new records, but only if the values for both column1 and column2 do not already exist in the table the insertion is being attempted on. Essentially, I do not want any duplication of values where the value of either column1 OR column2 must contain a unique value, but both do not need to be unique. Hope this is an easy one. Thanks.
Avatar of Sean Stuber
Sean Stuber

best way is to put a unique constraints/indexes on the table.

then simply insert the rows and capture exception on duplicates.
you can either ignore or report the attempt as needed.
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Arnold Layne

ASKER

Hi sdstuber. I was hoping to not raise any exceptions at all. Is there one semi complex SQL statement that can accomplish this without errors?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I saw this which looks like it might do what I want. Does anybody know about this and will it work?
INSERT INTO table ( column1, column2, column3 )
   (
    SELECT $column1, $column2, $column3
     WHERE NOT EXISTS (
       SELECT 1
         FROM table
        WHERE column1 = $column1
          AND column2 = $column2
          AND column3 = $column3 )
    )

I think it's clo9se to what I want but it might not do exactly what I want. I don't fully understand it.
Let us know if you're interested in trying the solution I posted, as I've used it in multiple projects, and can attest that it meets the requirements as stated in this question.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks guys.