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 6: Common Problems with Data Integrityoptimizer will ignore non-trusted constraints, meaning that valuable information will gounused, and could lead to suboptimal plans.Problems with UDFs wrapped in CHECK constraintsSome complex business rules are difficult or impossible to implement via regularconstraints. In such cases, it seems intuitive to develop a scalar UDF and wrap it ina CHECK constraint.For example, suppose that we need to enforce a data integrity rule that states:We can have any number of NULLs in the Barcode column, but the NOT NULL valuesmust be unique.Clearly, we cannot use a UNIQUE index or constraint in this situation, because itwould only allow a single NULL value, and we need to support multiple NULL values inthis column.The behavior of UNIQUE in SQL Server is not ANSI standardANSI specifies that a UNIQUE constraint should enforce uniqueness for non-NULLvalues only. Microsoft's implementation of the UNIQUE constraint deviates from thisstandard definition.To set up the example, we just need to add a Barcode column to our Items table, asshown in Listing 6-27.ALTER TABLE dbo.ItemsADD Barcode VARCHAR(20) NULL ;Listing 6-27: Adding a Barcode column to the Items table.To enforce our business rule, it is technically possible to develop a scalar UDF and invokeit from a CHECK constraint, as demonstrated in Listing 6-28.180

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

Saved successfully!

Ooh no, something went wrong!