0

我有一个在插入时触发的触发器。此触发器插入另一个表。这是我的代码:

    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。出了什么问题?

4

1 回答 1

1

有两种情况会发生此错误。1) 如果您在单个插入语句中插入多于一行,则触发器只会触发一次。在这种情况下,插入(如 Chris 所述)将包含多行。现在插入 tblTeamList 也将尝试插入多行 - 都具有相同的 teamid。

2) 如果其中两个插入同时发生,则它们可能都读取相同的@maxTeamId。如果发生这种情况,他们都会尝试使用相同的 teamid 将记录插入到 tblTeamList 中。

为了防止这两个问题,请使用桌子上的身份功能,而不是试图绕过它。

于 2012-10-13T17:38:50.030 回答