2013-12-09 41 views
0

爲了解釋:創建檢查約束的信息憑藉在另一個表引用它

在一個表,讓我們把它叫做GroupMember,有一個叫JoinDate列。 GroupMember s被分配到Group s其中有DateFounded

Group 
-------- 
GroupID identity int (PK) 
DateFounded datetime 


GroupMember 
-------- 
GroupMemberID identity int (PK) 
GroupID int (FK) 
JoinDate datetime 

我想對GroupMemberJoinDate約束,這將防止它被輸入爲DateFounded爲它的Group之前。我應該如何處理它?我可以使用檢查約束嗎?或者我需要一個函數/觸發器?

感謝

回答

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中的存儲值,並在檢查約束被破壞時自動更新失敗。