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.

that exercises the trigger we most recently worked with in this chapter. We can then step into that script,<br />

so we can watch the debugger run through it line by line:<br />

BEGIN TRAN<br />

-- This one should work<br />

UPDATE Production.ProductInventory<br />

SET Quantity = 400 -- Was 408 if you want to set it back<br />

WHERE ProductID = 1<br />

AND LocationID = 1<br />

-- This one shouldn’t<br />

UPDATE Production.ProductInventory<br />

SET Quantity = 1 -- Was 408 if you want to set it back<br />

WHERE ProductID = 1<br />

AND LocationID = 1<br />

IF @@TRANCOUNT > 0<br />

ROLLBACK TRAN<br />

With this script up in the Query Window in Management Studio, we can just press F11 to step into the<br />

script (or set a breakpoint and then use any of the several options that start the debugger). We start, of<br />

course, at the BEGIN TRAN statement. Continue to step into (F11) until you execute the first UPDATE<br />

statement, and note that you wind up in the trigger. Figure 15-6 shows the call stack as you enter the<br />

trigger for the first time.<br />

Figure 15-6<br />

Now, go ahead and step out of the first UPDATE, and into the second UPDATE. Since the first UPDATE<br />

statement didn’t match the violation test in the trigger, you exited almost immediately, but this second<br />

time you should see, as you step through, that the code that aborts the transaction fires.<br />

In short, we were able to utilize a single script that, in this case, had two statements meant to test the<br />

two possible code paths in our trigger. Obviously, you would need more complex scripting to handle the<br />

possible code paths for more complex triggers, but, beyond that, the debugging needs are pretty much<br />

as they are for testing any other code in T-<strong>SQL</strong>.<br />

Summary<br />

Chapter 15: Triggers<br />

Triggers are an extremely powerful tool that can add tremendous flexibility to both your data integrity<br />

and the overall operation of your system. That being said, they are not something to take lightly. Triggers<br />

can greatly enhance the performance of your system if you use them for proper summarization of<br />

data, but they can also be the bane of your existence. They can be very difficult to debug (even now that<br />

471

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

Saved successfully!

Ooh no, something went wrong!