A trigger is basically a query executed when something happens to a table.
There are 3 trigger types - INSERT, UPDATE, DELETE.
It looks something like this:
Code:
CREATE TRIGGER LeTrigger
ON Chars
AFTER UPDATE
AS IF UPDATE(K1)
BEGIN
-- the SQL code to execute
END
This will create a trigger which executes when the a cell of the K1 column from the Chars table is modified.
The easier way to create a trigger is by using the SQL Server Management Studio interface. Expand a table's options by clicking the + sign -> right click on Triggers -> New Trigger.
There are 2 important terms for triggers to keep in mind -
inserted and
deleted.
deleted represents the row before it was changed, whereas
inserted represents the new row.
For example, for an UPDATE(K1) trigger:
Code:
DECLARE @OldK1 INT = (SELECT K1 FROM deleted) -- old value
DECLARE @NewK1 INT = (SELECT K1 FROM inserted) -- new value
That's pretty much the basics.
There's also some other aspects, such as INSTEAD OF, which are rather interesting. For example, INSTEAD OF INSERT will mean that the code in the BEGIN/END block will be executed INSTEAD OF an insert, rather than AFTER the insert.