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

前端 未结 7 1484
时光说笑
时光说笑 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:34

    If you are using MS SQL Server, you can create a unique index on your table's columns that need to be unique (documented here):

    CREATE UNIQUE [ CLUSTERED | NONCLUSTERED ] INDEX 
        ON Words ( word [ ASC | DESC ])
    

    Specify Clustered or NonClustered, depending on your case. Also, if you want it sorted (to enable faster seeking), specify ASC or DESC for the sort order.

    See here, if you want to learn more about indexes architecture.

    Otherwise, you could use UNIQUE CONSTRAINTS like documented here:

    ALTER TABLE Words
    ADD CONSTRAINT UniqueWord
    UNIQUE (Word); 
    

提交回复
热议问题