How to add, delete, and update data between two tables in the database

Source: Internet
Author: User

Create add, delete, and update triggers respectively to synchronize data between two tables.
1: Data Synchronization increases:
If there are two tables, table A and Table B, create A trigger to enable table B to insert data synchronously after Table A is inserted. The inserted data fields in Table B must correspond to those in table.
Copy codeThe Code is as follows:
Create trigger name
On a table
AFTER INSERT
AS BEGIN INSERT
Table B (Table B Field 1, table B Field 2, Table B Field 3)
SELECT Table A Field 1, Table A Field 2, Table A Field 3
FROM INSERTED
END

2. delete data synchronization:
If there are two tables, table A and Table B, create A trigger so that table B also deletes data after Table A is deleted. Table B and table A should have corresponding primary keys.
Copy codeThe Code is as follows:
Create trigger name
On a table
AFTER DELETE
Table AS BEGIN DELETE B
WHERE
Table B primary key IN (
SELECT Table A primary key
From deleted)
END

3. synchronize data updates:
If there are two tables, table A and Table B, create A trigger so that after table A data is updated, table B also updates data synchronously.
Copy codeThe Code is as follows:
Create trigger name
On a table
AFTER UPDATE
AS
Update Table B
SET
B. B Table Field 1 = A. A table Field 1
FROM
Table B as B, INSERTED AS
Where B. B Table Primary Key = A. A table primary key

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.