MYSQL触发器根据特定字段的更新在第二个表中插入记录

时间:2015-01-15 17:01:05

标签: sql sql-server

我需要在Microsoft SQL Server中编写一个简单的触发器。它涉及两个表(抱歉非标准语法):

customer {
  customerno (integer)
  comm_preference (varchar(1))
  email (varchar(255))
  }

email_sent {
  customerno (integer)
  email (varchar(255))
  date (datetime)
}

customer.comm_preference的有效值为M,E,B(移动电话,电子邮件,两者)。我需要一个触发器,如果​​将值更改为E或B,则将带有customer.customerno,customer.email和今天日期的记录插入到email_sent中。

到目前为止,我的努力已经彻底清洗了。有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

试试这个,它将在email_sent表中插入一条新记录,同时记录插入' E'或者' B'或者价值改为' E'或者' B'

CREATE TRIGGER dbo.trg
   ON  customer
   AFTER INSERT,UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF EXISTS (SELECT  1 FROM inserted WHERE comm_preference IN ('E', 'B')
        BEGIN
            INSERT INTO email_sent 
            SELECT customerno, email, GETDATE() from inserted
        END        

END

答案 1 :(得分:0)

尝试这样的事情;

CREATE TRIGGER trgCustomer_Update ON dbo.customer FOR UPDATE
AS
    BEGIN
        IF UPDATE(comm_preference)
            BEGIN
                INSERT  dbo.email_sent
                        ( customerno
                        ,email
                        ,date
                        )
                        SELECT  i.customerno
                               ,i.email
                               ,GETDATE()
                        FROM    inserted i
                        INNER JOIN deleted d
                        ON      i.customerno = d.customerno
                        WHERE   d.comm_preference NOT IN ( 'E', 'B' ) AND
                                i.comm_preference IN ( 'E', 'B' )
            END
    END
GO

此致

里斯