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 1: Basic <strong>Defensive</strong> <strong>Database</strong> <strong>Programming</strong> TechniquesOf course, there are situations when our code will always run under one and thesame settings, in which case there is no need to do anything. For example, if a moduleimplements business rules specific to the state of Minnesota, it is reasonable to assumethat it will always run under the same language settings.<strong>Defensive</strong> Data ModificationData modification is, in general, an area in which I see developers getting into troubletime and again. We'll start with a case that demonstrates how data can be erroneouslyupdated as a result of a false assumption in the stored procedure that modifies it. It is asimple example, but the underlying problem is a very common one: using search criteriathat affect more rows than intended.We'll then discuss a second, somewhat more complex case, where an UPDATE cango wrong because it fails to unambiguously identify the row(s) to be modified,perhaps falsely assuming that the underlying data structures will ensure that nosuch ambiguity exists.Updating more rows than intendedListing 1-19 creates a simple Employee table, and a SetEmployeeManager storedprocedure that assigns a manager to a given employee.CREATE TABLE dbo.Employee(EmployeeID INT NOT NULL ,ManagerID INT NULL ,FirstName VARCHAR(50) NULL ,LastName VARCHAR(50) NULL ,CONSTRAINT PK_Employee_EmployeeIDPRIMARY KEY CLUSTERED ( EmployeeID ASC ) ,CONSTRAINT FK_Employee_EmployeeID_ManagerIDFOREIGN KEY ( ManagerID )REFERENCES dbo.Employee ( EmployeeID )) ;43

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

Saved successfully!

Ooh no, something went wrong!