Advantage of Triggers
The benefits of using triggers in SQL Server include the following:
- Database object rules are established by triggers, which cause changes to be undone if they are not met.
- The trigger will examine the data and, if necessary, make changes.
- We can enforce data integrity thanks to triggers.
- Data is validated using triggers before being inserted or updated.
- Triggers assist us in maintaining a records log.
- Due to the fact that they do not need to be compiled each time they are run, triggers improve the performance of SQL queries.
- The client-side code is reduced by triggers, saving time and labor.
- Trigger maintenance is simple.
SQL Trigger | Student Database
A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when specific table columns are updated. In simple words, a trigger is a collection of SQL statements with particular names that are stored in system memory. It belongs to a specific class of stored procedures that are automatically invoked in response to database server events. Every trigger has a table attached to it.
Because a trigger cannot be called directly, unlike a stored procedure, it is referred to as a special procedure. A trigger is automatically called whenever a data modification event against a table takes place, which is the main distinction between a trigger and a procedure. On the other hand, a stored procedure must be called directly.
The following are the key differences between triggers and stored procedures:
- Triggers cannot be manually invoked or executed.
- There is no chance that triggers will receive parameters.
- A transaction cannot be committed or rolled back inside a trigger.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of Syntax
- Create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
- [before | after]: This specifies when the trigger will be executed.
- {insert | update | delete}: This specifies the DML operation.
- On [table_name]: This specifies the name of the table associated with the trigger.
- [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each affected row.
- [trigger_body]: This provides the operation to be performed as the trigger is fired