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> TechniquesThis time, only the description of Indiana is updated. In a similar fashion, we couldfilter out (i.e. ignore) ambiguities with the help of an analytical function, as shown inListing 1-28.-- rerun the code from Listing 1-22-- before executing this codeBEGIN TRAN ;WITH c AS ( SELECT c.Code ,c.Description ,s.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 = NewDescriptionWHERE NumVersions = 1 ;ROLLBACK ;Listing 1-28: Using PARTITION BY to ignore ambiguities when updatingan inline view.In some cases, the approach of only performing unambiguous updates, and silentlyignoring ambiguous ones, is unacceptable. In the absence of built-in methods, we canuse tricky workarounds to reuse the code as much as possible and still raise an error ifthere is an ambiguity. Consider the example shown in Listing 1-29, in which a divide byzero occurs if there is an ambiguity.-- rerun the code from Listing 1-22-- before executing this codeDECLARE @ambiguityDetector INT ;WITH c AS ( SELECT c.Code ,c.Description ,52

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

Saved successfully!

Ooh no, something went wrong!