我有一个在插入时触发的触发器。此触发器插入另一个表。这是我的代码:
SELECT @maxTeamId = 0
SELECT @maxTeamId = ISNULL(MAX(teamId), 0) from [dbo].[tblTeamslist]
--- Check if home team has already been inserted into the table.
SELECT @homeTeamId = -1
SELECT
@homeTeamId = teamId
FROM
[dbo].[tblTeamslist] t
JOIN inserted i
ON t.teamName = i.hometeam
IF (@homeTeamId = -1)
BEGIN
SET IDENTITY_INSERT tblteamslist ON
SELECT @homeTeamId = @maxTeamId + 1
SELECT @maxTeamId = @maxTeamId + 1
INSERT INTO [dbo].[tblTeamslist] (teamid,teamname) SELECT @homeTeamId, i.hometeam FROM inserted i
SET IDENTITY_INSERT tblteamslist off
END
--- Check if away team has already been inserted into the table.
SELECT @awayTeamId = -1
SELECT
@awayTeamId = teamId
FROM
[dbo].[tblTeamslist] t
JOIN inserted i
ON t.teamName = i.awayteam
IF (@awayTeamId = -1)
BEGIN
SET IDENTITY_INSERT tblteamslist ON
SELECT @awayTeamId = @maxTeamId + 1
SELECT @maxTeamId = @maxTeamId + 1
INSERT INTO [dbo].[tblTeamslist] (teamid,teamname) SELECT @awayTeamId, i.awayteam FROM inserted i
SET IDENTITY_INSERT tblteamslist off
END
正如您所意识到的,我正在尝试输入一个团队,如果 tblTeamsList 上不存在该团队。这是我收到“违反主键约束”PK_tblTeamsList“的错误。无法在对象“dbo.tblTeamsList”中插入重复键。重复键值为 (24).'。在代码中,我试图每次将 id 增加 +1。出了什么问题?