简体   繁体   English

更新后的SQL触发器将数据插入另一个表

[英]SQL Trigger After Update Insert data into another table

I have two table. 我有两个桌子。 One is customer_info and another one is update_log. 一个是customer_info,另一个是update_log。 I want to create a trigger that will execute after update in customer_info. 我想创建一个触发器,该触发器将在customer_info中更新后执行。 If cust_name, Contact is updated then cust_no, Cust_name, Contact, Date will be added to second table. 如果cust_name, Contact已更新,则cust_no, Cust_name, Contact, Date将添加到第二个表中。 Second table will have two row with old data and new data. 第二个表将包含两行,分别包含旧数据和新数据。 my code is not working. 我的代码无法正常工作。 Any help will be highly appreciated. 任何帮助将不胜感激。

CREATE  TRIGGER  update_trigger
AFTER UPDATE  ON CUSTOMER_info
FOR EACH ROW
BEGIN
  IF NEW.cust_name <> OLD.cust_name || NEW.contact <> OLD.contact then
    insert into update_log values 
    ( OLD.cust_no,OLD.cust_name, OLD.contact, CURRENT_DATE); 

    insert into update_log  values
    ( NEW.cust_no,NEW.cust_name, NEW.contact,CURRENT_DATE);                 
  END IF
END

If You use MSSQL, You can use that trigger: 如果您使用MSSQL,则可以使用该触发器:

CREATE  TRIGGER  update_trigger
ON CUSTOMER_info 
FOR update AS

    BEGIN
        IF UPDATE (cust_name) OR UPDATE (contact)
        BEGIN
            INSERT INTO update_log (
                cust_no
                ,Cust_name
                ,Contact
                ,Date
                )
            SELECT cust_no
                ,cust_name
                ,contact
                ,GetDate()
            FROM INSERTED

            INSERT INTO update_log (
            cust_no
            ,Cust_name
            ,Contact
            ,Date
            )
        SELECT cust_no
            ,cust_name
            ,contact
            ,GetDate()
            FROM DELETED
        END
END
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM