我有一个在Insert上触发的触发器。此触发器插入另一个表。这是我的代码:
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上不存在。这是我得到'违反PRIMARY KEY约束'PK_tblTeamsList'的错误。无法在对象'dbo.tblTeamsList'中插入重复键。重复键值为(24)。'。 在代码中我试图每次增加id +1。出了什么问题?
答案 0 :(得分:1)
有两种情况可能会发生此错误。 1)如果在单个insert语句中插入多行,则触发器仅触发一次。在这种情况下插入(如Chris所述)将包含多行。现在插入到tblTeamList中也会尝试插入多行 - 所有这些行都具有相同的teamid。
2)如果这些插入中的两个同时发生,则它们都可能读取相同的@maxTeamId。如果发生这种情况,他们都会尝试使用相同的teamid将记录插入到tblTeamList中。
要防止这两个问题,请使用表格上的标识功能,而不是尝试绕过它。