如果将记录插入表,则触发器插入另一个表

时间:2015-03-12 12:32:43

标签: sql sql-server-2008 triggers

我有tblAtblB

+----------------------------------------------------+
|                        tblA                        |
+----------------------------------------------------+
| id         | INT IDENTITY(1,1), PRIMARY KEY        |
+------------+---------------------------------------+
| usrnm      | nvarchar[50], NOT NULL                |
+------------+---------------------------------------+
| InsertDate | DateTime DEFAULT(getdate()), NOT NULL |
+------------+---------------------------------------+

+----------------------------------------------------+
|                        tblB                        |
+----------------------------------------------------+
| id         | INT IDENTITY(1,1), PRIMARY KEY        |
+------------+---------------------------------------+
| tblA_id    | INT, NOT NULL                         |
+------------+---------------------------------------+
| usrnm      | nvarchar[50], NOT NULL                |
+------------+---------------------------------------+
| InsertDate | DateTime DEFAULT(getdate()), NOT NULL |
+------------+---------------------------------------+

每次将记录插入tblA时,我都需要自动向tblB插入记录。

INSERT INTO tblA (username, action) VALUES ('usrnm', '0')

所以在上面的代码之后,我需要立即运行以下代码:

INSERT INTO tblB (tblA_ID, username, action, InsertDate) 
VALUES
('id of the above record', 'usrnm', '0', 'InsertDate of the above rec')

这可能吗?我试图弄清楚如何触发它,但没有运气。

修改: 好的,基于我得到的链接应该看起来像这样:

CREATE TRIGGER AutoInsert
ON tblA
AFTER INSERT
AS
    INSERT INTO tblB
    (tblA_id, usrnm, InsertDate)
    VALUES
    (inserted.id, inserted.usrnm, inserted.InsertDate)

我应该如何引用tblA值?

2 个答案:

答案 0 :(得分:1)

您可以在表A上创建TRIGGER,如下所示:

SQL 有关After Triggers in SQL

的更多信息
CREATE TRIGGER TriggerName
   ON tblA
   FOR INSERT
   AS
   BEGIN
      SET NOCOUNT ON
      INSERT INTO tblB
        (id, name, etc)
    SELECT
        id, name, etc
        FROM inserted
    END

MySQL 有关After Triggers in MySQL

的更多信息
DELIMITER $$
CREATE TRIGGER TriggerName
   AFTER INSERT ON tblA FOR EACH ROW
   BEGIN
      INSERT INTO tblB (ID, name, etc)
      VALUES (NEW.ID, NEW.name, NEW.etc)            
    END;
$$
DELIMITER ;

答案 1 :(得分:1)

使用inserted

CREATE TRIGGER AutoInsert ON tblA AFTER INSERT AS
BEGIN
    INSERT INTO tblB (tblA_id, usrnm, InsertDate)
        select id, usrnm, InsertDate
        from inserted i;
END;