SQL Server - How to insert a record and make sure it is unique

前端 未结 7 1493
时光说笑
时光说笑 2020-12-08 02:45

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. Fo

7条回答
  •  长情又很酷
    2020-12-08 03:27

    Your solution:

    INSERT INTO Words (Word)
        SELECT @Word
    WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
    

    ...is about as good as it gets. You could simplify it to this:

    INSERT INTO Words (Word)
        SELECT @Word
    WHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word)
    

    ...because EXISTS doesn't actually need to return any records, so the query optimiser won't bother looking at which fields you asked for.

    As you mention, however, this isn't particularly performant, because it'll lock the whole table during the INSERT. Except that, if you add a unique index (it doesn't need to be the primary key) to Word, then it'll only need to lock the relevant pages.

    Your best option is to simulate the expected load and look at the performance with SQL Server Profiler. As with any other field, premature optimisation is a bad thing. Define acceptable performance metrics, and then measure before doing anything else.

    If that's still not giving you adequate performance, then there's a bunch of techniques from the data warehousing field that could help.

提交回复
热议问题