Note that there are some explanatory texts on larger screens.

plurals
  1. POHandle multiple rows in trigger (BULK insert)
    primarykey
    data
    text
    <p>I do a bulk insert and i have a trigger which makes some checks and inserts accordingly: Let's say that my Bulk insert have two columns HomeTeam AwayTeam.</p> <pre><code>HomeTeam AwayTeam Team1 Team3 Team6 Team9 Team3 Team5 </code></pre> <p>My database has two tables, tblTeamsList(Id,TeamName) which contains the teams and tblPremierLeague(id,HomeTeam,AwayTeam) which i do the bulk insert. I have an INSTEAD OF INSERT trigger which checks if HomeTeam is in tblTeamsList if not then it inserts it inside the tblteams, then it checks the AwayTeam and do the same. And finally i want to insert them into tblPremierleague with their foreign keys and not by name. Here is my trigger.</p> <pre><code> 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 </code></pre> <p>The above trigger does not work correctly and i get 300 same rows in tblPremierLeague, all rows have the same values as follow:</p> <pre><code>HomeTeam AwayTeam -1 1 </code></pre> <p>The awayteamId is correct. Moreover into tblTeamsList inserts the same team many times. Any help how to correct my trigger please?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload