问题
Constraint for phone number to be of 7 digits. How to check if it is of 7 digits in SQL Server?
CREATE TABLE Customer
(
C_ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
C_Name VARCHAR(255) NOT NULL,
Phone INT
);
回答1:
Do not store phone numbers as integers. Some valid numbers, for instance, could start with a 0 -- if not today, perhaps in the future. To do the validation check, you can use like
:
CREATE TABLE Customer (
C_ID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
C_Name VARCHAR(255) NOT NULL,
Phone CHAR(7), -- you might not want to have such a precise length
CONSTRAINT chk_phone CHECK (phone not like '%[^0-9]%') -- check that no number is not a digit
);
Alternatively, you could write:
CONSTRAINT chk_phone CHECK (phone like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]') -- check that no number is not a digit
回答2:
it worked with Phone VARCHAR CHECK(DATALENGTH(Phone)=7)
回答3:
You'd better store phone number as varchar2 or char type. In Oracle, you can check the validation of phone number by Regular Expression:
CREATE TABLE Customer
(
C_ID INT NOT NULL PRIMARY KEY,
C_Name VARCHAR(255) NOT NULL,
Phone char(10),
CONSTRAINT valid_phone_number
CHECK (REGEXP_LIKE(p_number, '^0\d{9}|\d{10}$'))
);
'^0\d{9}|\d{10}$' means phone number must start with digit 0, then followed by 9 or 10 digits (i.e 01646947314 (11 digits) or 0123456789 (10 digits) is VALID, and 123456789 or 0123456 is not valid). You can modify this code to 7 digits by dropping "|" in regular expression and change to d{7}. Hope this help you (or someone else's having the similar problem)!
回答4:
According to the NANP, seven-digit phone numbers in the US are NXX-XXXX, where N is 2-9 and X is 0-9. Additionally the second and third numbers cannot both be 1. Assuming you want to store only real NANP phone numbers, you could use the following constraint:
ALTER TABLE Customer
ADD CONSTRAINT CHK_Phone_valid
CHECK (Phone >= 2000000 AND Phone <= 9999999 and Phone / 10000 % 100 <> 11)
If you wanted to add an area code, you would need to use a bigint and different/additional constraints. Additionally, any sort in internal phone numbers, extensions, area codes, international phone numbers, etc., will have different requirements.
As someone who frequently deals with a large number of (exclusively NANP) phone numbers in databases, I do find that keeping them in a number format is ideal, as it is faster, smaller, and has the added benefit of preventing various formatting problems by default. Though for most users, this is probably all moot.
回答5:
Let's say you have a student table. In order to check the contact length, the following code works:
ALTER TABLE Student ADD CONSTRAINT SD_CHK check(contact like '[0-9]*10');
Hope this may help you
来源:https://stackoverflow.com/questions/36045875/constraint-for-phone-number-in-sql-server