问题
I am trying to set a constraint where user are only allowed to input 11 digits into the Number Data Type (Phone Number). I've tried
alter table "booyeah" add constraint
"booyeah_CC1" check ( LENGTH("PHONE_NO") = 11)
/
and
alter table "booyeah" add constraint
"booyeah_CC1" check ( PRECISION("PHONE_NO") = 11)
/
but got an error. For the first one, I kept getting error because it's not detecting the character length, while the second one, gave me an invalid identifier.
Thanks for the help!
回答1:
Set the data type for that column to varchar(11)
. If it must be exactly 11 characters every time, a check constraint will guarantee that: check (length(phone_no) = 11)
. To guarantee length and "numerality" (all digits, no letters), use
check (length(phone_no) = 11 and
regexp_like(phone_no, '^[[:digit:]]{11}$')
)
If you have to use a numeric type--and this is a bad idea--your best bet is probably numeric(11,0).
A check constraint can help you restrict the range of valid input, but no numeric types store leading zeroes. You'll have to jump through unnecessary and avoidable hoops if something like 00125436754
is a valid phone number.
回答2:
You can add the following check constraint:
... check (length(n||'')=11)
This check constraint is sufficiently simple. And you don't have to change the data type from number
to varchar2
, and don't have to check the input contains character other than digits.
I created simple table and checked whether it works properly:
create table t (n number check (length(n||'')=11));
insert into t values (1234567890); -- 10 digits
=> ORA-02290: check constraint (USER_4_552B1.SYS_C001297489) violated : insert into t values (1234567890)
insert into t values (12345678901);
=> Record Count: 0; Execution Time: 1ms
insert into t values (123456789012); -- 12 digits
=> ORA-02290: check constraint (USER_4_552B1.SYS_C001297489) violated : insert into t values (123456789012)
Another way is to use log
of base 10: (looks more complicated)
... check (trunc(log(10,phone_no)) = 10)
If the given number has 11 digits, its log
value would be 10.xxxx.
来源:https://stackoverflow.com/questions/16577451/oracle-db-set-input-number-to-exact-length