I’m wondering if there is a way to insert a record into a table only if the table does not already contain that record?
Is there a query that will do this, or will I need a stored procedure?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You don’t say what version of SQL Server. If SQL Server 2008 you can use MERGE
NB: It is usual to use Merge for an Upsert which is what I originally thought the question was asking but it is valid without the
WHEN MATCHEDclause and just with aWHEN NOT MATCHEDclause so does work for this case also. Example Usage.In terms of execution costs the two look roughly equal when an Insert is to be done…
Link to plan images for first run
but on the second run when there is no insert to be done Matthew’s answer looks lower cost. I’m not sure if there is a way of improving this.
Link to plan images for second run
Test Script