My table contains these values
Name VARCHAR(50),
Program VARCHAR(50),
Branch VARCHAR(30),
TotalP INT,
TotalN INT)
I’ve been trying to INSERT records into this table IF the Name doesn’t already exist. This has probably already been answered on here but when I type something into the search it comes up with 7000+ results and I looked through 100+ and still didn’t find the answer. Any and all help is appreciated.
If you aren’t worried about concurrency, the following would work:
The problem here would be that if two processes attempted to add the same
nameat the same moment… both would pass theIF NOT EXISTScheck, and then both wouldINSERT.To prevent this, you can either add a unique constraint to the
namecolumn, which would cause one of the inserts to fail, or you could lock the table in yourNOT EXISTScheck usingWITH (UPDLOCK, HOLDLOCK), which would reduce concurrency but not raise any errors.EDIT:
If the values that you want are from a
SELECTstatement, the following would work:This will insert the row from
YourSourceTableif the row is not found inYourDestinationTable… implemented using aLEFT JOINandIS NULLcheck.This has the same caveats as before… if two processes run this statement simultaneously, you can end up with duplicate
namevalues; either add a unique constraint onname, or perform a(UPDLOCK, HOLDLOCK)on the row in the destination table that you’re testing for existence inside of a transaction: