Hi Folks,
I'm trying to figure out the best way to insert a record into a single table but only if the item doesn't already exist. The KEY in this case is an NVARCHAR(400) field. For this example, lets pretend it's the name of a word in the Oxford English Dictionary / insert your fav dictionary here. Also, i'm guessing i will need to make the Word field a primary key. (the table will also have a unique identifier PK also).
So .. i might get these words that i need to add to the table...
eg.
- Cat
- Dog
- Foo
- Bar
- PewPew
- etc...
So traditionally, i would try the following (pseudo code)
SELECT WordID FROM Words WHERE Word = @Word
IF WordID IS NULL OR WordID <= 0
INSERT INTO Words VALUES (@Word)
ie. If the word doesn't exist, then insert it.
Now .. the problem i'm worried about is that we're getting LOTS of hits .. so is it possible that the word could be inserted from another process in between the SELECT and the INSERT .. which would then throw a constraint error? (ie. a Race Condition).
I then thought that i might be able to do the following ...
INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
basically, insert a word when it doesn't exist.
Bad syntax aside, i'm not sure if this is bad or good because of how it locks down the table (if it does) and is not that performant on a table that it getting massive reads and plenty of writes.
So - what do you Sql gurus think / do?
I was hoping to have a simple insert and 'catch' that for any errors thrown.