SQL Server trigger to insert data into a table

Source: Internet
Author: User

The table user1 contains the field ID, username, email, and address.

The delta2_user1 table contains the field ID, username, email, address, and status.

When table user1 inserts a record, a record is also inserted in delta2_user1, and 'insert' is written in the field status'

When user1 updates a record, delete the original record in delta2_user1, insert a new record, and write 'modify' in the field status'

When a record is deleted from table user1, the status value of the corresponding field is updated to 'delete' in delta2_user1'

Set ansi_nulls on <br/> set quoted_identifier on <br/> go <br/> alter trigger [DBO]. [delta_user2_user1] <br/> on [DBO]. [user1] <br/> for insert, update, delete <br/> as <br/> If exists (select. username from inserted a, deleted B where. username = B. username) <br/> begin <br/> If exists (select delta2_user1.username from delta2_user1, inserted where delta2_user1.username = inserted. username) <br/> Delete delta2_user1 from delta2_user1, inserted where delta2_user1.username = inserted. username; <br/> insert into delta2_user1 select ID, username, email, address, 'modify' from inserted; <br/> end </P> <p> else <br/> begin <br/> If exists (select username from inserted) <br/> begin <br/> insert into delta2_user1 select ID, username, email, address, 'insert' from inserted; <br/> end <br/> else <br/> begin <br/> Update delta2_user1 set status = 'delete' from delta2_user1, deleted where delta2_user1.username = deleted. username; <br/> 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.