How can I create a unique constraint on my column (SQL Server 2008 R2)?

前端 未结 4 708
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 21:44

I have SQL Server 2008 R2 and I want to set a unique column.

There seems to be two ways to do this: \"unique index\" and \"unique constraint\". They are not much

4条回答
  •  臣服心动
    2020-12-07 22:04

    One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

    create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 
    
    --Commands completed successfully.
    
    sp_help Customer
    
    ---> index
    --index_name    index_description   index_keys
    --PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id
    
    ---> constraint
    --constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
    --PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
    
    
    ---- now adding the unique constraint
    
    ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
    
    -- Commands completed successfully.
    
    sp_help Customer
    
    ---> index
    ---index_name   index_description   index_keys
    ---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
    ---U_Name   nonclustered, unique, unique key located on PRIMARY name
    
    ---> constraint
    ---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
    ---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
    ---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name
    

    as you can see , there is a new constraint and a new index U_Name

提交回复
热议问题