Solution to CHECK Constraint Puzzle
Check your answer here to the T-SQL Black Belt CHECK constraint puzzle.
December 31, 2002
The problem I posed in the main article was to write a CHECK constraint that allows only digits in the column sn. Latin characters a thorough z and special characters aren't allowed. You need to apply the single-expression approach in your solution. When I give this puzzle to my students, most of them usually come up with the following expression:
sn NOT LIKE '%[a-z]%'
However, this solution doesn't take special characters into consideration. One possible solution is to replicate the string '[0-9]' as many times as there are characters in the sn column by using the REPLICATE() and LEN() functions:
sn LIKE REPLICATE('[0-9]', LEN(sn))
A more elegant solution uses negation twice. You can express the requirement by not allowing any character that isn't a digit:
sn NOT LIKE '%[^0-9]%'
About the Author
You May Also Like