Create MySQL, SQL Server, and Oracle triggers

Source: Internet
Author: User

Scenario: when the users table is in insert, update, delete, the changed id is recorded in the users_log table.

Create a MySQL trigger

Trigger Time: BEFORE, AFTER

Trigger Event: INSERT, UPDATE, DELETE

NEW and OLD Keywords:

| Action | NEW | OLD |

| -------- | ---------------- |

| Insert new data | none |

| Update | modified to new data | modified original data |

| Delete | none | the original data to be deleted |

DELIMITER $
Create trigger insert_user AFTER INSERT
ON users FOR EACH ROW
BEGIN
Insert into users_log (user_id, action) VALUES (NEW. id, 'insert ');
END $
DELIMITER;

SQL Server trigger creation

Trigger Time: instead of (before), FOR (after)

Trigger Event: INSERT, UPDATE, DELETE

INSERTED and DELETED logical (concept) tables: act as the NEW and OLD keywords in MySQL. However, MySQL represents a record, while SQL Server represents a temporary table of all records.

Create trigger insert_user ON users FOR INSERT
BEGIN
DECLARE @ id INT
SELECT @ id = MIN (id) from inserted while @ id IS NOT NULL
BEGIN
Insert into users_log (user_id, action) VALUES (@ id, 'insert ')
SELECT @ id = MIN (id) from inserted where id> @ id
END
END

Create an Oracle trigger

Trigger Time: BEFORE, AFTER

Trigger Event: INSERT, UPDATE, DELETE

: NEW and: OLD Keywords: the function is equivalent to the NEW and OLD keywords in MySQL.

Create or replace trigger insert_user AFTER INSERT
On scott. "users" FOR EACH ROW
BEGIN
Insert into SCOTT. "users_log" ("user_id", "action") VALUES (: NEW. "id", 'insert ');
END;
/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.