SQL Server: A simple trigger example for adding data to one table and triggering data update from another table

Source: Internet
Author: User
Create trigger updateuserroletouserloginon tb_userrolefor insertasbegin update tb_userlogin set roleid = T. roleid from tb_userlogin tend

AboveCodeThe simple meaning is:

When data is inserted in the tb_userrole table, the value of the roleid field in the tb_userlogin table is the value of the roleid in the add record.

Case 2:

In this case, there are two tables T1 and T2. Later, due to the change, a field needs to be added to table T2. This field is exactly the field value in Table T1 (PS: there is an external association between t1 and t2)

At present, the original insert statement remains unchanged, but while inserting data, we hope that the new fields in the modified T2 table can synchronize values in Table T1. What should we do?

-- Synchronize citycode table create trigger tr_inserton Real-Time alerts for Real-Time alerts after insertasdeclare @ ID int, @ name varchar (20), @ code varchar (20) Begin select @ ID = [objectid], @ code = [region] From inserted; select @ name = [cityname] From citycode where citycode = @ code; update real-time dangerous situation set [region] = @ name where [objectid] = @ ID; end; insert into real-time dangerous situation (upload time, region, and county) values ('2017-10-18 ', '20170101', ''); select * from real-time danger;
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.