Friday, December 14, 2012

Regular Expressions:Match Number Patterns in Sql Server

When working with sql server some times we might need to add custom check constraints for the tables. One scenario that i have gone through is checking the phone number format when inserting into the table. What i did was, i have added a check constraint to the table for the phone number column using regular expressions.

The number format pattern i need to match is (800) 555-1212


ADD CONSTRAINT Chk_Phone CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')

[0-9] - Match any digit.

You can write a select query as below

Select * from #temp 
where Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'

No comments:
Write comments
Recommended Posts × +