如何向对象添加约束
How to add a constraint to an object
执行代码:https://dbfiddle.uk/?rdbms=oracle_21&fiddle=69131953cf61459b64092025737d79b7
我有一个有多个字段的对象。
而我想说的是,一个字段只能有一定的值。
我尝试用与 table
相同的方式来做到这一点
create type oa as object(
a VARCHAR2(59) constraint cta check(a in ('a1','a2' ))
)
ORA-24344: success with compilation error
我尝试创建一个 table 并说我的对象具有相同的字段
CREATE TABLE ta(
a VARCHAR2(59) constraint cta check(a in ('a1','a2' ))
)
Create type oa2 as ta%rowtype
ORA-24344: success with compilation error
也不行。
你不能;约束只能应用于 table 或视图。
Constraint clauses can appear in the following statements:
CREATE TABLE
(see CREATE TABLE
)
ALTER TABLE
(see ALTER TABLE
)
CREATE VIEW
(see CREATE VIEW
)
ALTER VIEW
(see ALTER VIEW
)
作为替代方案,您可以将类型声明为:
CREATE TYPE oa as object(
a VARCHAR2(59)
);
然后声明一个 object-derived table 添加了 CHECK
约束:
CREATE TABLE oat OF oa (
CONSTRAINT oat_chk CHECK (a in ('a1', 'a2'))
);
然后:
INSERT INTO oat VALUES (oa('a1'));
INSERT INTO oat (a) VALUES ('a1');
有效但是:
INSERT INTO oat VALUES (oa('b1'));
INSERT INTO oat (a) VALUES ('b1');
违反检查约束。
db<>fiddle here
执行代码:https://dbfiddle.uk/?rdbms=oracle_21&fiddle=69131953cf61459b64092025737d79b7
我有一个有多个字段的对象。 而我想说的是,一个字段只能有一定的值。
我尝试用与 table
相同的方式来做到这一点create type oa as object(
a VARCHAR2(59) constraint cta check(a in ('a1','a2' ))
)
ORA-24344: success with compilation error
我尝试创建一个 table 并说我的对象具有相同的字段
CREATE TABLE ta(
a VARCHAR2(59) constraint cta check(a in ('a1','a2' ))
)
Create type oa2 as ta%rowtype
ORA-24344: success with compilation error
也不行。
你不能;约束只能应用于 table 或视图。
Constraint clauses can appear in the following statements:
CREATE TABLE
(seeCREATE TABLE
)ALTER TABLE
(seeALTER TABLE
)CREATE VIEW
(seeCREATE VIEW
)ALTER VIEW
(seeALTER VIEW
)
作为替代方案,您可以将类型声明为:
CREATE TYPE oa as object(
a VARCHAR2(59)
);
然后声明一个 object-derived table 添加了 CHECK
约束:
CREATE TABLE oat OF oa (
CONSTRAINT oat_chk CHECK (a in ('a1', 'a2'))
);
然后:
INSERT INTO oat VALUES (oa('a1'));
INSERT INTO oat (a) VALUES ('a1');
有效但是:
INSERT INTO oat VALUES (oa('b1'));
INSERT INTO oat (a) VALUES ('b1');
违反检查约束。
db<>fiddle here