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 5: Reusing T-SQL CodeIt is much easier and safer to just create the business rule once, in one place, as aUNIQUE constraint, as shown in Listing 5-27.ALTER TABLE dbo.TeamsADD CONSTRAINT UNQ_Teams_Name UNIQUE(Name) ;Listing 5-27: The UNQ_Teams_Name constraint enforces the uniqueness of teamnames.We can now let the database engine make sure that this business rule is always enforced,regardless of the module or command that modifies the table.Turn to triggers when constraints are not practicalAs we have seen, constraints are extremely useful in many simple cases. However,our business rules are often more complex, and it is sometimes not possible or notpractical to use constraints. To demonstrate this point, let's add one more table,TeamMembers, which references the Teams table through the TeamID column, asshown in Listing 5-28.CREATE TABLE dbo.TeamMembers(TeamMemberID INT NOT NULL ,TeamID INT NOT NULL ,Name VARCHAR(50) NOT NULL ,IsTeamLead CHAR(1) NOT NULL ,CONSTRAINT PK_TeamMembers PRIMARY KEY ( TeamMemberID ) ,CONSTRAINT FK_TeamMembers_TeamsFOREIGN KEY ( TeamID ) REFERENCES dbo.Teams ( TeamID ),CONSTRAINT CHK_TeamMembers_IsTeamLeadCHECK ( IsTeamLead IN ( 'Y', 'N' ) )) ;Listing 5-31: Creating the TeamMembers table.154

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

Saved successfully!

Ooh no, something went wrong!