Trigger Sql Sever

0

I have a database with two tables: Category and Team, the relationship between the tables goes like this: a category can have many teams. I have created a trigger so that at the moment of inserting a team a quantity field of the category table is added to 1. The trigger goes like this:

create trigger Actualizar
on equipo for insert
as
update categoria set cantidad = cantidad + 1
from categoria, equipo
where categoria.id = equipo.categoria;

The first team works well increases 1, but at the time of inserting another team with different category, the amount increases by 1 for both the new and the previous.

    
asked by Jose Sepulveda 03.03.2018 в 04:55
source

1 answer

1

The trigger is updating all records, since the where is not filtering, rather it is acting as a JOIN. To obtain the id of the inserted record, you have to consult inserted

I leave you the complete trigger so you can see it

CREATE TRIGGER Actualizar ON equipo FOR INSERT
AS
BEGIN
    declare @id int;
    set @id = (select categoria from inserted);
    update categoria set cantidad = cantidad + 1
    where id = @id
END
    
answered by 03.03.2018 в 07:17