0% found this document useful (0 votes)
23 views

Simple SQL Cheat Sheet - DML Triggers

Uploaded by

FrancesHsieh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Simple SQL Cheat Sheet - DML Triggers

Uploaded by

FrancesHsieh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Simple SQL Cheat Sheet:

DML Triggers

What is a trigger?:
A trigger is used to execute custom code either after or instead of a Data Manipulation
Language (DML) statement that is ran against a table or View. The DML statement can
be an INSERT, UPDATE, or DELETE statement.
AFTER triggers:
AFTER triggers are used to execute custom code after a DML statement is executed.
Syntax:
CREATE TRIGGER trigger_name
ON table_name
AFTER INSERT/UPDATE/DELETE
AS
<trigger body>

You can use the word 'FOR' instead of 'AFTER'. The two are interchangeable.
If you want your trigger to execute for multiple DML statements, just separate those
statements with a comma.
INSTEAD OF triggers:
INSTEAD OF triggers are used to execute custom code instead of a DML statement.
The code inside the trigger will fire instead of the DML statement outlined in the
definition of the trigger.
Syntax:
CREATE TRIGGER trigger_name
ON table_name
INSTEAD OF INSERT/UPDATE/DELETE
AS
<trigger body>

If you want your trigger to execute for multiple DML statements, just separate those
statements with a comma.
The inserted and deleted system tables:
The inserted and deleted tables can be queried within a DML trigger.
The inserted table will contain the new state of the data after the DML statement is
executed.
The deleted table will contain the old state of the data after the DML statement is
executed.
The inserted table is empty when the DML statement is a DELETE.
The deleted table is empty when the DML statement is an INSERT.
Both the inserted and deleted tables are populated with data when the DML
statement is an UPDATE. SQL Server essentially treats an UPDATE as a DELETE plus
an INSERT.
Tips you should know about triggers:
You can use the UPDATE function within your trigger to check if a specific column is
changing.
Example:
CREATE TRIGGER NoChangeToPrices
ON Products
AFTER UPDATE
AS
IF UPDATE(Price)
BEGIN
PRINT 'Changes to product prices are not allowed'
<work to change the Price value back to it's original value>
END

Make sure your trigger can handle a DML statement that modifies more than one
row at once. This might involve using a JOIN statement in an UPDATE statement
within your trigger (joining on either the inserted or deleted table).
You can disable a trigger using the DISABLE TRIGGER statement within an ALTER
TABLE statement.
Example:
ALTER TABLE Products DISABLE TRIGGER NoChangeToPrices
You can drop a trigger using the DROP TRIGGER statement
Example:
DROP TRIGGER NoChangeToPrices

Learn more at
www.SimpleSqlTutorials.com

You might also like