if object_id('table1')is not null drop table table1
go
create table table1(Id int ,username varchar(10)unique)
insert table1 select 1,'abc'
insert table1 select 2,'abc'
/*
所影响的行数为 1 行)服务器: 消息 2627,级别 14,状态 2,行 1
Violation of UNIQUE KEY constraint 'UQ__table1__5D2BD0E6'. Cannot insert duplicate key in object 'table1'.
The statement has been terminated.*/

解决方案 »

  1.   

    建立唯一索引,或唯一约束。如果想出错情况能得到控制,比如事务加回滚,那么,需要主观处理,比如,先if exists(....)再行插入。
      

  2.   

    if object_id('table1')is not null drop table table1
    go
    create table table1(Id int ,username varchar(10)COLLATE   Chinese_PRC_CS_AS unique)
    insert table1 select 1,'abc'
    insert table1 select 2,'Abc'--Chinese_PRC_CS_AS 区分大小写
    select * from table1
    /*
    Id          username   
    ----------- ---------- 
    1           abc
    2           Abc(所影响的行数为 2 行)*/
      

  3.   

    表table1中有一个 username(nvarchar(50)),我想让这个列成为此表中的唯一标识符。 
    也就是说再有输入同样username的时候提示已存在用唯一约束create table t(userName nvarchar(50) unique)或唯一索引create table t(userName nvarchar(50))create index U_T_userName on t(userName)
      

  4.   

    --建立测试表
    Use Test
    Go
    If Object_id('User','U') Is Not null
    Drop Table [User]
    Go
    Create Table [User]
    (
    ID int Identity(1,1) Not null,
    username nvarchar(50) null,
    Constraint PK_User_ID Primary Key(ID Asc)
    )
    Go
    --将username这个列成为此表中的唯一标识符
    Alter Table [User] Add Constraint U_User_username Unique(username Asc)
    Go
    --测试:
    Insert Into [User] Select N'张三'
    Insert Into [User] Select N'张三'
    /*
    (1 行受影响)
    消息 2627,级别 14,状态 1,第 3 行
    违反了 UNIQUE KEY 约束 'U_User_username'。不能在对象 'dbo.User' 中插入重复键。
    语句已终止。
    */
      

  5.   

    看来大家误会了:表已经建好,我只是想把username这一列从nvarchar改称unique identifier
      

  6.   


    ALTER TABLE table1 
    ADD CONSTRAINT nameUnique UNIQUE (username)