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