mysql觸發器執行個體

來源:互聯網
上載者:User

   測試表1
?

1 2 3 4 5 6 7 8 DROP TABLE IF EXISTS test;                  CREATE TABLE test (    id           bigint(11) unsigned NOT NULL AUTO_INCREMENT,    name         varchar(100) NOT NULL DEFAULT '',    type         varchar(100),   create_time  datetime,    PRIMARY KEY (ID)  ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

  測試表2

?

1 2 3 4 5 6 7 8 9 DROP TABLE IF EXISTS test_hisy;                  CREATE TABLE test_hisy (    id           bigint(11) unsigned NOT NULL AUTO_INCREMENT,    name         varchar(100) NOT NULL DEFAULT '',    type         varchar(100),   create_time  datetime,   operation    varchar(100) COMMENT '操作類型',   PRIMARY KEY (ID)  ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

  insert觸發器

  表test新增記錄後,將type值為“1”的記錄同時插入到test_hisy表中(AFTER INSERT:錄入後觸發, BEFORE INSERT:錄入前觸發)

?

1 2 3 4 5 6 7 8 9 10 11 DELIMITER // DROP TRIGGER IF EXISTS t_after_insert_test// CREATE TRIGGER t_after_insert_test AFTER INSERT ON test FOR EACH ROW BEGIN     IF new.type='1' THEN     insert into test_hisy(name, type, create_time, operation)     values(new.name, new.type, new.create_time, 'insert');     END IF; END;//

  update觸發器

  表test修改時,若type值為“2”則將修改前的記錄同時插入到test_hisy表中(AFTER UPDATE:修改後觸發, BEFORE UPDATE:修改前觸發)

?

1 2 3 4 5 6 7 8 9 10 11 DELIMITER // DROP TRIGGER IF EXISTS t_before_update_test// CREATE TRIGGER t_before_update_test BEFORE UPDATE ON test FOR EACH ROW BEGIN     IF new.type='2' THEN     insert into test_hisy(name, type, create_time, operation)     values(old.name, old.type, old.create_time, 'update');     END IF; END;//

  delete觸發器

  表test刪除記錄前,將刪除的記錄錄入到表test_hisy中(AFTER DELETE:刪除後觸發, BEFORE DELETE:刪除前觸發)

?

1 2 3 4 5 6 7 8 9 DELIMITER // DROP TRIGGER IF EXISTS t_before_delete_test// CREATE TRIGGER t_before_delete_test BEFORE DELETE ON test FOR EACH ROW BEGIN     insert into test_hisy(name, type, create_time, operation)     values(old.name, old.type, old.create_time, 'delete'); END;//

  註:以上觸發器例子中出現的new為修改後的資料, old為修改前的資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.