0

我做了一个批量插入,我有一个触发器,它会进行一些检查并相应地插入:假设我的批量插入有两列 HomeTeam AwayTeam。

HomeTeam     AwayTeam
Team1         Team3
Team6         Team9
Team3         Team5

我的数据库有两个表, tblTeamsList(Id,TeamName) 包含团队和 tblPremierLeague(id,HomeTeam,AwayTeam) 我进行批量插入。我有一个 INSTEAD OF INSERT 触发器,它检查 HomeTeam 是否在 tblTeamsList 中,如果不是,则将其插入 tblteams 中,然后检查 AwayTeam 并执行相同操作。最后我想用他们的外键而不是名字将它们插入 tblPremierleague。这是我的触发器。

   instead of INSERT
AS
BEGIN
    DECLARE @homeTeamId INT
    DECLARE @awayTeamId INT
    DECLARE @maxTeamId INT
    DECLARE @matchId INT
    DECLARE @home nvarchar(100)
    DECLARE @away nvarchar(100)

    DECLARE cur CURSOR FOR
    Select HomeTeam,AwayTeam from inserted
    OPEN cur
    FETCH NEXT FROM cur INTO @home, @away

    --- 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 = @home
    IF (@homeTeamId = -1) 
    BEGIN

        INSERT INTO [dbo].[tblTeamslist] (teamname) SELECT  i.hometeam FROM inserted i

    END

    --- Check if away team has already been inserted into the table.
     SELECT @maxTeamId = 0
    SELECT @maxTeamId = ISNULL(MAX(teamId), 0) from [dbo].[tblTeamslist]


    SELECT @awayTeamId = -1
    SELECT 
        @awayTeamId = teamId 
    FROM 
        [dbo].[tblTeamslist] t
        JOIN inserted i
        ON t.teamName = @away
    IF (@awayTeamId = -1) 
    BEGIN

        INSERT INTO [dbo].[tblTeamslist]  (teamname) SELECT  i.awayteam FROM inserted i

    END

    -- insert a record into the matches table with the home team ID and away team ID.

    INSERT INTO [dbo].[tblpremierLeague] 
    SELECT  @homeTeamId, @awayTeamId
    FROM inserted i
FETCH NEXT FROM cur INTO @home, @away

    END
    CLOSE cur
    DEALLOCATE cur

上面的触发器不能正常工作,我在 tblPremierLeague 中得到 300 行相同的行,所有行的值都相同,如下所示:

HomeTeam        AwayTeam
 -1                1

awayteamId 是正确的。而且在 tblTeamsList 中多次插入同一个团队。请帮助如何纠正我的触发器?

4

1 回答 1

1

假设 id 是IDENTITY列:

-- Add all of the home teams we haven't heard of before.
insert into dbo.tblTeamsList
  select i.HomeTeam
    from inserted as i left outer join
      tblTeamsList as TL on TL.TeamName = i.HomeName
    where TL.Id is NULL

-- Add all of the alien teams we haven't heard of before.
insert into dbo.tblTeamsList
  select i.AwayTeam
    from inserted as i left outer join
      tblTeamsList as TL on TL.TeamName = i.AwayTeam
    where TL.Id is NULL

-- Add any **new** pairs to the league.
insert into tblPremierLeague
  select H.Id, A.Id
    from inserted as i inner join
      tblTeamsList as H on H.TeamName = i.HomeTeam inner join
      tblTeamsList as A on A.TeamName = i.AwayTeam left outer join
      tblPremierLeague as TL on TL.HomeTeam = H.Id and TL.AwayTeam = A.Id
    where TL.Id is NULL

请不要通过 Agonizing Row (RBAR) 来执行此行。使用集合操作。

许多人不关心命名表的人造匈牙利符号tblMumble。我会用Mumbles.

于 2013-07-27T16:41:05.203 回答