Database triggers for,instead of and after use

Source: Internet
Author: User

Recently engaged in SQL server2008 R2 Database course design, in the use of for,instead of and after is encountered a little hindrance, the final Solution:

The following triggers are created:

1  Use [Choose_man]2 GO3 /** * * * Object:trigger [dbo].    [Tri_field] Script date:11/24/2017 20:49:38 * * * * **/4 SETAnsi_nulls on5 GO6 SETQuoted_identifier on7 GO8 ALTER Trigger [dbo].[Tri_field]  on [dbo].[Tb_field]9  for Insert,UpdateTen  as One if(Select COUNT(*) fromtb_college,inserted A      whereTb_college.collegeid=Inserted.collegeid)=0 - begin  -        Print 'If you do not find the department information, please add the appropriate department and try again! ' the        rollback - End - Else IF -(SELECT    COUNT(*) fromtb_field,inserted +      whereTb_field.fieldid=Inserted.fieldid)>0 -  begin  +     Print'Professional number conflicts, please check and try again! ' A     rollback at  End -  

The data is inserted as follows:

1 Insert  into Values ('F0022','C0008',' Department of Mathematics and Statistics ' ,' Xia Hong Xing ','3345901')

Error:

Solve:

First use for, code line nineth, when I insert the data, the trigger is triggered after the SQL statement execution completes, so after inserting the data, the trigger checks out the same fieldid, so the check condition should be set to greater than 1, not 0

(SELECT    COUNT (* from tb_field,inserted      where tb_field.fieldid=inserted.fieldid)>1

Finally, the data is inserted successfully.

When using for control, it defaults to the same as after, with instead of Yes, executing the SQL statement before triggering the trigger, and finally showing (1 rows affected), but when I query the table data, I find that the data is not inserted into the table, it should be the SQL statement is not executed, here to inform.

Database triggers for,instead of and after use

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.