Sql-server – Check constraint

constraintsql server

check (phone like'[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')

This is to check the phone number whether it has exactly 10 digits. But I have no idea about placing number as '[0-9]'. It seems to be a string. So how can we check numbers inside string?
Can some one explain this query?

The type of column phone is char(10).

Best Answer

You can check the opposite (does not contain chars not in the 0-9 interval).

CHECK (phone NOT LIKE '%[^0-9]%')

Be warned that telephone numbers typically contain also other characters (+,-,.). In that case, you can add allowed symbols to the list:

CHECK (phone NOT LIKE '%[^0-9+-.]%')

See LIKE (Transact-SQL) in the documentation.