使用带条件的唯一索引 。 给你写一个示例 create table test(id int identity,name varchar(10)) go create unique index test_ix on test(name) where (name is not null) and (name != '') go insert into test values('a') insert into test values('a') insert into test values(null) insert into test values(null) insert into test values('') insert into test values('') go select * from test go drop table test go (1 行受影响) 消息 2601,级别 14,状态 1,第 2 行 不能在具有唯一索引 'test_ix' 的对象 'dbo.test' 中插入重复键的行。 语句已终止。(1 行受影响)(1 行受影响)(1 行受影响)(1 行受影响) id name ----------- ---------- 1 a 3 NULL 4 NULL 5 6 (5 行受影响)
给你写一个示例
create table test(id int identity,name varchar(10))
go
create unique index test_ix on test(name) where (name is not null) and (name != '')
go
insert into test values('a')
insert into test values('a')
insert into test values(null)
insert into test values(null)
insert into test values('')
insert into test values('')
go
select * from test
go
drop table test
go
(1 行受影响)
消息 2601,级别 14,状态 1,第 2 行
不能在具有唯一索引 'test_ix' 的对象 'dbo.test' 中插入重复键的行。
语句已终止。(1 行受影响)(1 行受影响)(1 行受影响)(1 行受影响)
id name
----------- ----------
1 a
3 NULL
4 NULL
5
6 (5 行受影响)