17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

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 15: Triggers<br />

458<br />

To illustrate this, let’s take a look at the Sales.SalesOrderDetail and Sales.SpecialOfferProduct<br />

tables in the AdventureWorks<strong>2008</strong> database. The relationship looks like Figure 15-2.<br />

Figure 15-2<br />

So under normal DRI, you can be certain that no SalesOrderDetail item can be entered into the<br />

SalesOrderDetail table unless there is a matching ProductID in the SpecialOfferProduct table (even<br />

if the special offer record is “no discount”). We are, however, looking for something more than just the<br />

norm here.<br />

Our Inventory department has been complaining that our Customer Support people keep placing orders<br />

for products that are marked discontinued. They would like to have such orders rejected before they get<br />

into the system.<br />

We can’t deal with this using a CHECK constraint, because the place where we know about the discontinued<br />

status (the Product table) is a separate table from where we are placing the restriction (the SalesOrderDetail<br />

table). Don’t sweat it though — you can tell the Inventory department, “No problem!”<br />

You just need to use a trigger:<br />

CREATE TRIGGER Sales.SalesOrderDetailNotDiscontinued<br />

ON Sales.SalesOrderDetail<br />

FOR INSERT, UPDATE<br />

AS<br />

IF EXISTS<br />

(<br />

SELECT ‘True’<br />

FROM Inserted i<br />

JOIN Production.Product p<br />

ON i.ProductID = p.ProductID<br />

WHERE p.DiscontinuedDate IS NOT NULL<br />

)<br />

BEGIN<br />

RAISERROR(‘Order Item is discontinued. Transaction Failed.’,16,1)<br />

ROLLBACK TRAN<br />

END

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

Saved successfully!

Ooh no, something went wrong!