如果 Andomar 对您想要的东西的解释是正确的,那么如果您有一个已经包含所有可能K
值的表,那么它可能是可行的:
create table dbo.T (
K int null,
V int not null,
)
go
create table dbo.PossibleKs (
K int not null
)
insert into dbo.PossibleKs (K) values (0),(1),(2)
go
create view dbo.TV
with schemabinding
as
select pk.K
from
dbo.T t
inner join
dbo.PossibleKs pk
on
t.K = pk.K or
t.K is null
GO
create unique clustered index IX_TV on dbo.TV (K)
还有你的测试用例:
insert into dbo.T(K,V) values
(0, 32),
(1, 12),
(3, 45)
go
insert into dbo.T(K,V) values
(NULL,89)
--Msg 2601, Level 14, State 1, Line 1
--Cannot insert duplicate key row in object 'dbo.TV' with unique index 'IX_TV'. The duplicate key value is (0).
--The statement has been terminated.
go
delete from dbo.T
go
insert into dbo.T(K,V) values
(NULL,89)
go
insert into dbo.T(K,V) values
(0, 32)
--Msg 2601, Level 14, State 1, Line 1
--Cannot insert duplicate key row in object 'dbo.TV' with unique index 'IX_TV'. The duplicate key value is (0).
--The statement has been terminated.