17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 4: When Upgrading Breaks CodeCREATE TRIGGER dbo.Developers_Upd ON dbo.DevelopersAFTER UPDATEASBEGIN ;IF EXISTS ( SELECT *FROM inserted AS iINNER JOIN dbo.Tickets AS tON i.DeveloperID =t.AssignedToDeveloperIDWHERE i.Status = 'Vacation'AND t.Status = 'Active' )BEGIN ;-- this string has been wrapped for readability here-- it appears on a single line in the code download fileRAISERROR ('Developers must assign theiractive tickets to someoneelse before going onvacation', 16, 1 ) ;ROLLBACK ;END ;END ;Listing 4-8: The Developers_Upd trigger.Similarly, on the Tickets table, we create an AFTER UPDATE trigger, as shown inListing 4-9. It is designed to make sure that inactive tickets cannot be changed to activestatus if they are assigned to developers who are on vacation. In a complete solution,we would also need to create an AFTER INSERT trigger to ensure that it is impossibleto insert a new ticket with active status and assign it to a developer who is on vacation.However, we will focus only on the AFTER UPDATE trigger here.CREATE TRIGGER dbo.Tickets_Upd ON dbo.TicketsAFTER UPDATEASBEGIN ;IF EXISTS (SELECT *112

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

Saved successfully!

Ooh no, something went wrong!