解释:
在一个表格中,我们称之为GroupMember
,有一个名为JoinDate
的列。 GroupMember
已分配给Group
个DateFounded
。
Group
--------
GroupID identity int (PK)
DateFounded datetime
GroupMember
--------
GroupMemberID identity int (PK)
GroupID int (FK)
JoinDate datetime
我希望对GroupMember
列JoinDate
设置一个约束,以防止它DateFounded
之前输入Group
{{1}}。我该怎么办呢?我可以使用检查约束吗?或者我需要一个功能/触发器?
由于
答案 0 :(得分:1)
它可以完成,但它有点乱(并且确实使用触发器,但只支持插入,而不是强制实际约束):
create table dbo.Group (
GroupID int identity not null primary key,
DateFounded datetime not null,
constraint UQ_Group_Founded UNIQUE (GroupID,DateFounded)
)
go
create table dbo._GroupMember (
GroupMemberID int identity not null primary key,
GroupID int not null references Group (GroupID)
JoinDate datetime not null,
_Founded datetime not null,
constraint FK_GroupMember_Founding FOREIGN KEY (GroupID,_Founded) references Group (GroupID,DateFounded),
constraint CK_GroupMember_NoTimeTravel CHECK (JoinDate >= _Founded)
)
go
create view dbo.GroupMember
with schemabinding
as
select GroupMemberID,GroupID,JoinDate
from dbo.GroupMember
go
create trigger T_GroupMember_I
on dbo.GroupMember
instead of insert
as
insert into dbo._GroupMember (GroupID,JoinDate,_Founded)
select i.GroupID,i.JoinDate,g.DateFounded
from inserted i inner join Group g on i.GroupID = g.GroupID
现在您将视图GroupMember
视为原始GroupMember
表并忽略_GroupMember
表。
您是否继续对Group
以及包含DateFounded
列的明确外键约束取决于您。如果您希望允许在Group
中调整该日期,则应将外键标记为ON UPDATE CASCADE
,并且它应自动调整_GroupMember
中的存储值并且如果然后打破检查约束。