I got lost when I wanted to create trigger using the pre-defined “CREATE TRIGGER” of SQL Server 2008 R2. Could you please give me a direct SQL statement that I can use to create a trigger, and tell me how to define AFTER, BEFORE, and all that?
Also, how can I know the rows UPDATED/INSERTED/DELETED, and use their column values to do operations inside the trigger?
Databases are set-oriented and triggers are no different. A trigger will fire when a given operation is performed and that operation might affect multiple rows. Thus, the question
"Say I want to know the Primary Key of that row"is a misnomer. There could be multiple rows inserted.SQL Server provides two special tables for AFTER triggers named
insertedanddeletedwhich represent the rows that were inserted or deleted by an action and are structured identically to the table being affected. An update trigger might populate bothinsertedanddeletedwhereas an insert trigger would only populate theinsertedtable.From comments:
The answer to this question is to use the
insertedtable (which again, you must assume could have multiple rows) to cycle through the rows and send an email. However, I would recommend against putting email logic in a trigger. Instead, I would recommend putting that logic in a stored procedure and send your email from that.For reference: Create Trigger