17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ON<br />

While triggers take no parameters, they do have a mechanism for figuring out what records they are<br />

supposed to act on (we’ll investigate this further later in the chapter). And, while you can use the<br />

RETURN keyword, you cannot return a specific return code (because you didn’t explicitly call the trigger,<br />

what would you return a return code to?).<br />

What events can you attach triggers to? The three action query types you use in <strong>SQL</strong>. So, there are three<br />

types of triggers, plus hybrids that come from mixing and matching the events and timing that fire them:<br />

❑ INSERT triggers<br />

❑ DELETE triggers<br />

❑ UPDATE triggers<br />

❑ A mix and match of any of the above<br />

It’s worth noting that there are times when a trigger will not fire, even though it seems that the action<br />

you are performing falls into one of the preceding categories. At issue is whether the operation you are<br />

doing is in a logged activity or not. For example, a DELETE statement is a normal, logged activity that<br />

would fire any delete trigger, but a TRUNCATE TABLE, which has the effect of deleting rows, just deallocates<br />

the space used by the table — there is no individual deletion of rows logged, and no trigger is<br />

fired. Bulk operations will not, by default, fire triggers (you can explicitly tell the bulk operation to fire<br />

the triggers).<br />

The syntax for creating triggers looks an awful lot like all of our other CREATE syntax examples, except,<br />

as with a table, it has to be attached to a table — a trigger can’t stand on its own.<br />

Let’s take a look:<br />

CREATE TRIGGER <br />

ON [.]<br />

[WITH ENCRYPTION | EXECUTE AS ]<br />

{{{FOR|AFTER} } |INSTEAD OF}<br />

[WITH APPEND]<br />

[NOT FOR REPLICATION]<br />

AS<br />

< | EXTERNAL NAME ><br />

Chapter 15: Triggers<br />

As you can see, the all too familiar CREATE is still there, as well as<br />

the execution stuff we’ve seen in many other objects — we’ve just added the ON clause to indicate the<br />

table to which this trigger is going to be attached, as well as when and under what conditions it fires.<br />

This part just names the object you are creating the trigger against. Keep in mind that, if the type of the<br />

trigger is an AFTER trigger (if it uses FOR or AFTER to declare the trigger), then the target of the ON clause<br />

must be a table — AFTER triggers are not supported for views.<br />

453

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!