1 为创建的表中某一列创建检查约束(check)时,
create table test --创建示例表test
(
testid char(10) not null,
/*
为列testid创建check约束,其格式形如[P][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
*/
constraint chk_testid check(
testid like '[P][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)表创建成功,检查约束chk_testid创建成功
当向表test中插入数据时
insert into io.test --io是用户方案,登录数据库的用户名
values('P070920001');在SQL Developer中执行报告错误如下:在行 1 上开始执行命令时出错:
insert into io.test
values('P070920001')
错误报告:
SQL 错误: ORA-02290: 违反检查约束条件 (IO.CHK_TESTID)
02290. 00000 - "check constraint (%s.%s) violated"
*Cause: The values being inserted do not satisfy the named check
*Action: do not insert values that violate the constraint.
create table test --创建示例表test
(
testid char(10) not null,
/*
为列testid创建check约束,其格式形如[P][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
*/
constraint chk_testid check(
testid like '[P][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)表创建成功,检查约束chk_testid创建成功
当向表test中插入数据时
insert into io.test --io是用户方案,登录数据库的用户名
values('P070920001');在SQL Developer中执行报告错误如下:在行 1 上开始执行命令时出错:
insert into io.test
values('P070920001')
错误报告:
SQL 错误: ORA-02290: 违反检查约束条件 (IO.CHK_TESTID)
02290. 00000 - "check constraint (%s.%s) violated"
*Cause: The values being inserted do not satisfy the named check
*Action: do not insert values that violate the constraint.
你需要的是regexp_like
/*
为列testid创建check约束,其格式形如[P][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
*/ 1 为创建的表中某一列创建检查约束(check)时,
create table test --创建示例表test
(
testid varchar2(10),
constraint chk_testid check(
testid BETWEEN 'P000000001' AND 'P999999999'),
constraint chk_testid2 check(
LENGTH(testid)=10)
)insert into test(testid) --io是用户方案,登录数据库的用户名
values('P000000001');
在SQL Developer中创建不成功
不知为何
还是谢谢
like 不支持 正则
--还要控制字符串的长度(10),所以还要加一个约束,
--或则类似如:'P0000000009E','P000000000999'将也会插入成功
--正确代码如下:
CREATE TABLE test --创建示例表test
(
testid VARCHAR2(14),
CONSTRAINT chk_testid1
CHECK (REGEXP_LIKE(testid, '[P]'||'[0-9]{9}')),
CONSTRAINT chk_testid2
CHECK (LENGTH(testid)=10)
)
把另一种情况(varchar2类型)也考虑进去了