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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: When Upgrading Breaks CodeCREATE TABLE dbo.Developers(DeveloperID INT NOT NULL ,FirstName VARCHAR(30) NOT NULL ,Lastname VARCHAR(30) NOT NULL ,Status VARCHAR(10) NOT NULL ,CONSTRAINT PK_Developers PRIMARY KEY (DeveloperID) ,CONSTRAINT CHK_Developers_Status CHECK ( Status IN( 'Active','Vacation' ) )) ;GOCREATE TABLE dbo.Tickets(TicketID INT NOT NULL ,AssignedToDeveloperID INT NULL ,Description VARCHAR(50) NOT NULL ,Status VARCHAR(10) NOT NULL ,CONSTRAINT PK_Tickets PRIMARY KEY ( TicketID ) ,CONSTRAINT FK_Tickets_DevelopersFOREIGN KEY ( AssignedToDeveloperID )REFERENCES dbo.Developers ( DeveloperID ) ,CONSTRAINT CHK_Tickets_StatusCHECK ( Status IN ( 'Active', 'Closed' ) )) ;Listing 4-7: Creating the Developers and Tickets tables.Note that, thanks to our FOREIGN KEY constraint, FK_Tickets_Developers, newlyadded developers cannot have tickets assigned to them. We only need to make sure ourrules are enforced at the point when a developer's status is updated. Therefore, on theDevelopers table, we create an AFTER UPDATE trigger, as shown in Listing 4-8. It isdesigned to make sure that developers cannot go on vacation if they have active ticketsassigned to them.111

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

Saved successfully!

Ooh no, something went wrong!