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 />

Use constraints where possible<br />

In many cases, constraints are the easiest and simplest to use. To demonstrate this point,<br />

consider the <strong>Team</strong>s table shown in Listing 6-25, with a primary key constraint on the<br />

<strong>Team</strong>ID column.<br />

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

(<br />

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

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

CONSTRAINT PK_<strong>Team</strong>s PRIMARY KEY ( <strong>Team</strong>ID )<br />

) ;<br />

Listing 6-25: Creating the <strong>Team</strong>s table.<br />

Since we wish to forbid access to the base tables, teams will be inserted into the table, one<br />

at a time, by calling a stored procedure. Our business rule is simple: team names must be<br />

unique. So, we need to decide where to implement this business rule. One choice is to<br />

enforce it in the stored procedure, as shown in Listing 6-27.<br />

CREATE PROCEDURE dbo.Insert<strong>Team</strong><br />

@<strong>Team</strong>ID INT ,<br />

@Name VARCHAR(50)<br />

AS<br />

BEGIN ;<br />

-- This is not a fully-functional stored<br />

-- procedure. Error handling is skipped to keep<br />

-- the example short.<br />

-- Also potential race conditions<br />

-- are not considered in this simple module<br />

INSERT INTO dbo.<strong>Team</strong>s<br />

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

Name<br />

)<br />

SELECT @<strong>Team</strong>ID ,<br />

@Name<br />

190

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

Saved successfully!

Ooh no, something went wrong!