我的数据库中有以下表格定义
CREATE TABLE Products
(
PartNo CHAR (6) NOT NULL ,
Description VARCHAR2 (16) NOT NULL ,
Weight SMALLINT NOT NULL
) ;
ALTER TABLE Products ADD CONSTRAINT CK_PartNo CHECK ( PartNo LIKE '[0-9][A-Z][0-9][0-9][0-9][0-9]') ;
ALTER TABLE Products ADD CONSTRAINT Products_PK PRIMARY KEY ( PartNo ) ;
当我尝试插入一行时,出现不符合约束检查的错误。
insert into PRODUCTS(PARTNO, DESCRIPTION, WEIGHT)
values('1W1234', 'O-ring', 1);
*Action: do not insert values that violate the constraint.
Error starting at line : 1 in command -
insert into PRODUCTS(PARTNO, DESCRIPTION, WEIGHT)
values('1W1234', 'O-ring', 1)
Error report -
SQL Error: ORA-02290: check constraint (DEMO.CK_PARTNO) violated
02290. 00000 - "check constraint (%s.%s) violated"
*Cause: The values being inserted do not satisfy the named check
答案 0 :(得分:3)
ALTER TABLE Products ADD CONSTRAINT CK_PartNo
CHECK ( regexp_like(PartNo, '\d[A-Z]\d{4}') ) ;
答案 1 :(得分:1)
您无法在LIKE
中使用正则表达式语法,您需要使用REGEXP_LIKE
:
CHECK ( REGEXP_LIKE(PARTNO, '[0-9][A-Z][0-9][0-9][0-9][0-9]')
演示:
CREATE TABLE Products
(
PartNo CHAR (6) NOT NULL ,
Description VARCHAR2 (16) NOT NULL ,
Weight SMALLINT NOT NULL
) ;
ALTER TABLE Products ADD CONSTRAINT CK_PartNo
CHECK ( REGEXP_LIKE(PARTNO, '[0-9][A-Z][0-9][0-9][0-9][0-9]') ) ;
ALTER TABLE Products ADD CONSTRAINT Products_PK PRIMARY KEY ( PartNo ) ;
insert into PRODUCTS(PARTNO, DESCRIPTION, WEIGHT)
values('1W1234', 'O-ring', 1);
1 rows inserted.