Ber*_*ard 1 sql oracle oracle11g
我有一个约束:
ALTER TABLE account
ADD CONSTRAINT chk_account_type CHECK (Type IN ('saving', 'credit', 'HOME LOAN', 'PERSONAL LOAN', 'TERM DEPOSIT', 'CHECK', 'iSaver', 'SHARE' ) );
Run Code Online (Sandbox Code Playgroud)
当我尝试插入时
INSERT INTO Account VALUES ('012878', 123456, 22345678, 'Credit', -1534.52);
Run Code Online (Sandbox Code Playgroud)
这是行不通的.因为Credit以大写字符开头.如何设计它如何我可以接受储蓄,储蓄,保存.
您可以通过在检查时更改案例来执行此操作:
ALTER TABLE account
ADD CONSTRAINT chk_account_type CHECK (lower(Type) IN ('saving', 'credit',
'home loan', 'personal loan', 'term deposit', 'check', 'isaver', 'share' ));
Run Code Online (Sandbox Code Playgroud)
但允许变化似乎很奇怪,通过检查约束强制执行这些限制也是如此.将帐户类型放在具有主键的单独表中会更加正常且更灵活,并使该type列成为外键.然后,您可以通过添加到该表来添加新帐户类型,而不必修改检查约束,并且如果需要,您可以允许来自帐户类型表的不区分大小写的查找,但始终一致地显示它们.
就像是:
create table account_types(account_type_id number, description varchar2(30),
constraint account_type_pk primary key (account_type_id));
insert into account_types (account_type_id, description) values (1, 'Saving');
insert into account_types (account_type_id, description) values (2, 'Credit');
insert into account_types (account_type_id, description) values (3, 'Home loan');
...
create table account(account_number number, account_type_id number,
-- other columns...
constraint account_pk primary key (account_number),
constraint account_fk_account_type foreign key (account_type_id)
references account_types(account_type_id));
Run Code Online (Sandbox Code Playgroud)
然后创建一个"保存"帐户:
insert into account values (123, 1);
1 rows inserted.
Run Code Online (Sandbox Code Playgroud)
如果你的价值无效,你会得到:
insert into account values (124, 42);
SQL Error: ORA-02291: integrity constraint (MYSCHEMA.ACCOUNT_FK_ACCOUNT_TYPE) violated - parent key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1689 次 |
| 最近记录: |