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 1: Basic <strong>Defensive</strong> <strong>Database</strong> <strong>Programming</strong> Techniquess.Description AS NewDescription ,COUNT(*) OVER ( PARTITION BY s.Code )AS NumVersionsFROM dbo.Codes AS cINNER JOIN dbo.CodesStaging AS sON c.Code = s.Code)UPDATE cSET Description = NewDescription ,@ambiguityDetector = CASE WHEN NumVersions = 1THEN 1-- if we have ambiguities, the following branch executes-- and raises the following error:-- Divide by zero error encountered.ELSE 1 / 0END ;Msg 8134, Level 16, State 1, Line 4Divide by zero error encountered.The statement has been terminated.Listing 1-29: An UPDATE command using an inline view and raising a divide by zeroerror when there is an ambiguity.Of course, the error message raised by this code (divide by zero) is misleading, so weshould only use this approach when none of the previous options are viable.<strong>Defensive</strong> UPDATE…FROMSome of the approaches just outlined for improving the robustness of inline viewupdates, apply equally as well to improving the UPDATE…FROM command. For example,we can use a subquery to ignore ambiguities, as shown in Listing 1-30.-- rerun the code from Listing 1-22-- before executing this codeBEGIN TRAN ;UPDATE dbo.Codes53

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

Saved successfully!

Ooh no, something went wrong!