30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - 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 6: Reusing T-<strong>SQL</strong> Code<br />

Turn to triggers when constraints are not practical<br />

As we have seen, constraints are extremely useful in many simple cases. However, our<br />

business rules are often more complex, and it is sometimes not possible or not practical<br />

to use constraints. To demonstrate this point, let's add one more table, <strong>Team</strong>Members,<br />

which references the <strong>Team</strong>s table through the <strong>Team</strong>ID column, as shown in Listing 6-28.<br />

CREATE TABLE dbo.<strong>Team</strong>Members<br />

(<br />

<strong>Team</strong>MemberID INT NOT NULL ,<br />

<strong>Team</strong>ID INT NOT NULL ,<br />

Name VARCHAR(50) NOT NULL ,<br />

Is<strong>Team</strong>Lead CHAR(1) NOT NULL ,<br />

CONSTRAINT PK_<strong>Team</strong>Members PRIMARY KEY ( <strong>Team</strong>MemberID ) ,<br />

CONSTRAINT FK_<strong>Team</strong>Members_<strong>Team</strong>s<br />

FOREIGN KEY ( <strong>Team</strong>ID ) REFERENCES dbo.<strong>Team</strong>s ( <strong>Team</strong>ID ) ,<br />

CONSTRAINT CHK_<strong>Team</strong>Members_Is<strong>Team</strong>Lead<br />

CHECK ( Is<strong>Team</strong>Lead IN ( 'Y', 'N' ) )<br />

) ;<br />

Listing 6-28: Creating the <strong>Team</strong>Members table.<br />

Suppose that we need to implement the following business rule: no team can have more<br />

than two members. Implementing this business rule in a trigger is quite straightforward,<br />

as shown in Listing 6-29, and you only have to do it once. It is possible, but much more<br />

complex, to implement this rule via constraints.<br />

CREATE TRIGGER dbo.<strong>Team</strong>Members_<strong>Team</strong>SizeLimitTrigger<br />

ON dbo.<strong>Team</strong>Members<br />

FOR INSERT, UPDATE<br />

AS<br />

IF EXISTS ( SELECT *<br />

FROM ( SELECT <strong>Team</strong>ID ,<br />

<strong>Team</strong>MemberID<br />

FROM inserted<br />

UNION<br />

192

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

Saved successfully!

Ooh no, something went wrong!