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.

Another upshot of this part-of-the-same-transaction business is that triggers inherit the locks already<br />

open on the transaction they are part of. This means that we don’t have to do anything special to make<br />

sure that we don’t bump into the locks created by the other statements in the transaction. We have free<br />

access within the scope of the transaction, and we see the database based on the modifications already<br />

placed by previous statements within the transaction.<br />

Using IF UPDATE() and COLUMNS_UPDATED<br />

In an UPDATE trigger, we can often limit the amount of code that actually executes within the trigger by<br />

checking to see whether the column(s) we are interested in are the ones that have been changed. To do<br />

this, we make use of the UPDATE() or COLUMNS_UPDATED() functions. Let’s look at each.<br />

The UPDATE() Function<br />

The UPDATE() function has relevance only within the scope of a trigger. Its sole purpose in life is to provide<br />

a boolean response (true/false) to whether a particular column has been updated or not. You can<br />

use this function to decide whether a particular block of code needs to run or not — for example, if that<br />

code is relevant only when a particular column is updated.<br />

Let’s run a quick example of this by modifying one of our earlier triggers.<br />

ALTER TRIGGER Production.ProductIsRationed<br />

ON Production.ProductInventory<br />

FOR UPDATE<br />

AS<br />

IF UPDATE(Quantity)<br />

BEGIN<br />

IF EXISTS<br />

(<br />

SELECT ‘True’<br />

FROM Inserted i<br />

JOIN Deleted d<br />

ON i.ProductID = d.ProductID<br />

AND i.LocationID = d.LocationID<br />

WHERE (d.Quantity - i.Quantity) > d.Quantity / 2<br />

AND d.Quantity > 0<br />

)<br />

BEGIN<br />

RAISERROR(‘Cannot reduce stock by more than 50%% at once.’,16,1)<br />

ROLLBACK TRAN<br />

END<br />

END<br />

Chapter 15: Triggers<br />

With this change, we will now limit the rest of the code to run only when the Quantity column (the one<br />

we care about) has been changed. The user can change the value of any other column and we don’t care.<br />

This means that we’ll be executing fewer lines of code and, therefore, this trigger will perform slightly<br />

better than our previous version.<br />

467

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

Saved successfully!

Ooh no, something went wrong!