从一个表复制到另一个行时触发器被称为(Copying row from one table to a

2019-10-19 05:47发布

我有2个表

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


 Table B
    ID | val

所以,我有在当任何行获取的插入表格中的相同数据得到在表B.更新此我想用trigger.My触发样子,要求做到

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

我现在面临的问题是如何我“会找出哪一行表格中的插入,因为我有一个重复的条目ID.How我”会发现它得到了扳机被称为后插入的确切行。 应该是什么查询参数“插入B值(NEW.ID,New.Val)” ......应该是什么这些新的价值?

Answer 1:

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


Answer 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


文章来源: Copying row from one table to another when trigger is called