If you need to use a CASE statement in a check constraint, you may be inclined to use something like this:
use AdventureWorks2008
GO
ALTER TABLE Person.EmailAddress ADD CONSTRAINT CK_EmailAddress_Is_Valid_Email
CHECK
(
CASE
WHEN EmailAddress IS NULL THEN 0
WHEN LEN(EmailAddress) = 0 THEN 0
ELSE 1
END
)
GO
This code segment however will give you an error similar to the following: An expression of non-boolean type specified in a context where a condition is expected, near ‘)’.
The thing to remember about CHECK constraints is that they check to see if an expression is true or false. The code block above returns a 1 or 0 it does not evaluate to true or false. In order to get a true / false value, simply compare the output of the CASE statement to a given value. For example:
use AdventureWorks2008
GO
ALTER TABLE Person.EmailAddress ADD CONSTRAINT CK_EmailAddress_Is_Valid_Email
CHECK
(
(CASE
WHEN EmailAddress IS NULL THEN 0
WHEN LEN(EmailAddress) = 0 THEN 0
ELSE 1
END) = 1
)
GO
By wrapping the CASE statement in parenthesis and then comparing the final result to the desired value – in this case “1”, SQL Server can evaluate this expression as a boolean “true / false” statement.
—-
SQL Server Expert, Steve Abraham, holds 8 Microsoft certifications and specializes in SQL Server and .Net Framework architecture, high availability, capacity planning, development, and performance tuning.
Posted in Programming SQL Server, SQL Server 2005, SQL Server 2008, T-SQL, Uncategorized Tagged: CASE, CHECK CONSTRAINT, SQL Server 2005, SQL Server 2008, T-SQL
