如果您想在表中使用不同的表示形式,那么您可能必须实现一个视图,并通过它而不是基表执行插入。
就像是:
CREATE TABLE realMatches (
MatchID int IDENTITY(1,1) not null, /* Identity? */
HomeTeamID int not null,
AwayTeamID int not null,
Score int not null, /* int? */
constraint PK_realMatches PRIMARY KEY (MatchID),
constraint FK_Matches_HomeTeams (HomeTeamID) references tblTeams (TeamID),
constraint FK_Matches_AwayTeams (AwayTeamID) references tblTeams (TeamID)
)
GO
CREATE VIEW tblMatches
AS
SELECT
MatchID,
ht.TeamName as HomeTeam,
at.TeamName as AwayTeam,
Score
FROM
realMatches m
inner join
tblTeams ht
on
m.HomeTeamID = ht.TeamID
inner join
tblTeams at
on
m.AwayTeamID = at.TeamID
GO
CREATE TRIGGER T_Matches ON tblMatches
INSTEAD OF INSERT
AS
SET NOCOUNT ON
INSERT INTO realMatches (HomeTeamID,AwayTeamID,Score)
SELECT ht.TeamID,at.TeamID,i.Score
FROM
inserted i
inner join
tblTeam ht
on
i.HomeTeam = ht.TeamName
inner join
tblTeam at
on
i.AwayTeam = at.TeamName
您现在可以(假设“A Team”和“Team America”存在于 中tblTeams
):
INSERT INTO tblMatches (HomeTeam,AwayTeam,Score)
VALUES ('A Team','Team America',19)
当然,这(还)不涉及任何试图更改匹配表中的球队的更新,也没有处理如果球队还不存在的情况下该怎么办tblTeam
,但你还没有问过这些。