我做了一个批量插入,我有一个触发器,它会进行一些检查并相应地插入:假设我的批量插入有两列 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 中多次插入同一个团队。请帮助如何纠正我的触发器?