Copying row from one table to another when trigger

2019-08-08 05:27发布

问题:

I have 2 tables

A)
 Table A
     ID | val | 
1.   1    m
2.   2    n
3.   1    o
4    1    p
5.   2    q


 Table B
    ID | val

So I have a requirement where when any row get's inserted into table A the same data get's updated in table B. This I am trying to do using a trigger.My trigger looks like

CREATE Trigger tr_ForInserts
ON A
FOR INSERT
AS
BEGIN
 SET NOCOUNT ON;
insert into B values(NEW.ID,NEW.Val);
END

The problem which I am facing is How I"ll identify which row in table A is inserted as I have duplicate entry for single ID.How I"ll detect the exact row which got inserted after trigger has been called. what should be the parameter in query "insert into B values(NEW.ID,New.Val)".....what should be these New value?

回答1:

CREATE TRIGGER tg_insert ON A
FOR INSERT
AS
BEGIN
  INSERT B
  SELECT id, val
  FROM inserted
END


回答2:

CREATE Trigger tr_ForInserts
ON A
FOR INSERT
AS
BEGIN
    SET NOCOUNT ON;
    declare @id int;
    declare @val int;
    select @id=i.ID from inserted i;    
    select @val =i.Val from inserted i;
    insert into B values(@id, @val);
END