這是可以做到,但它是一個有點亂(和不使用觸發器,但是隻支持插入,不執行實際的約束):
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
中的存儲值,並在檢查約束被破壞時自動更新失敗。