我同意其他人的观点,即我可能会瞄准与您展示的型号不同的型号,但如果您对它出售,那么以下似乎可以满足您的需求:
create table dbo.Weekdays (
DayOfWeek varchar(10) not null,
constraint PK_Weekdays PRIMARY KEY (DayOfWeek)
)
go
create table dbo.Exclusions (
Fruit varchar(20) not null,
DayOfWeek varchar(10) null,
/* PK? */
constraint FK_Exclusions FOREIGN KEY (DayOfWeek) references Weekdays (DayOfWeek)
)
不确定排除表的 PK 应该是什么,从您显示的内容来看并不明显,但它旨在成为您的表。我们需要引入Weekdays 表才能使后面的视图工作*。现在填充它:
insert into dbo.Weekdays (DayOfWeek)
select 'Monday' union all
select 'Tuesday' union all
select 'Wednesday' union all
select 'Thursday' union all
select 'Friday' union all
select 'Saturday' union all
select 'Sunday'
还有你的样本数据:
insert into dbo.Exclusions (Fruit,DayOfWeek)
select 'Kiwi',NULL union all
select 'Apples','Monday' union all
select 'Strawberries','Monday' union all
select 'Oranges','Tuesday' union all
select 'Bananas','Wednesday' union all
select 'Pineapple','Thursday'
现在我们创建视图来实现您的约束:
create view dbo.Exclusions_NullExpanded
with schemabinding
as
select
e.Fruit,
wd.DayOfWeek
from
dbo.Exclusions e
inner join
dbo.Weekdays wd
on
e.DayOfWeek = wd.DayOfWeek or
e.DayOfWeek is null
go
create unique clustered index IX_Exclusions_NoDups on dbo.Exclusions_NullExpanded (Fruit,DayOfWeek)
而且,如果我们尝试插入您不希望我们插入的行:
insert into dbo.Exclusions (Fruit,DayOfWeek)
select 'Kiwi','Monday'
我们得到:
Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row in object 'dbo.Exclusions_NullExpanded' with unique index 'IX_Exclusions_NoDups'.
The statement has been terminated.
*我最初尝试在不引入 Weekdays 表的情况下执行此操作,并将其作为文本行的子选择出现在视图定义中。但是你不能创建索引来强制我们想要在这样一个视图上的约束。