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.*/
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.*/
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 行)*/
也就是说再有输入同样username的时候提示已存在用唯一约束create table t(userName nvarchar(50) unique)或唯一索引create table t(userName nvarchar(50))create index U_T_userName on t(userName)
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' 中插入重复键。
语句已终止。
*/
ALTER TABLE table1
ADD CONSTRAINT nameUnique UNIQUE (username)