IntroductionTriggers are a special kind of Stored Procedure that executes automatically when a user tries to modify a database. Triggers are built for SELECT, UPDATE, INSERT and DELETE statements; whenever a user tries to executes these queries to perform a transaction, triggers stop him and keep our database secure. Sample Code for Triggersuse [Database_Name]GOCreate Trigger Trigger_Nameon dbo.table_nameAFTER INSERTASBEGINPRINT 'INSERTION IS NOT ALLOWED !! 'ROLLBACK TRANSACTIONendGo This code creates a trigger on a particular table; if a user tries to insert a value into this table, a trigger would be generated automatically which would prevent the user from any insertion.A little bit of explanation about this code:use [database] --the database which is in useCreate Trigger Trigger_Name --Creates a Trigger, specifying its nameon dbo.table_name --specifies the table where we want to set the TriggerAFTER INSERT --Specify a keyword here "INSERT", "UPDATE", "DELETE" or "SELECT", after the keyword AFTERROLLBACK TRANSACTION -- Rolls a transaction back to a savepoint or beginning of transaction, in this case it will Rollback us to the original state of the table (no change will occur)You can use the same code for other statements too.For example if we don't want our user to update data in the database we would follow up with this trigger:use [DatabaseName]GOcreate Trigger updateTriggeron dbo.tableNameAFTER UPDATEASBEGINPRINT 'UPDATION IS NOT ALLOWED'ROLLBACK TRANSACTIONENDGOTo prevent deletion:use [DatabaseName]GOcreate Trigger Delete_Triggeron dbo.tableNameAFTER DELETEASBEGINPRINT 'DELETION IS NOT ALLOWED'ROLLBACK TRANSACTIONENDGOTo prevent selection:use [DatabaseName]GOcreate Trigger Select_Triggeron dbo.tableNameAFTER SELECTASBEGINPRINT 'SELECTION IS NOT ALLOWED'ROLLBACK TRANSACTIONENDGOConclusionWe can do many modifications with the same triggers. Use these and make your programming more efficient.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: