SQL创建表依赖项

时间:2014-12-01 12:50:29

标签: sql oracle create-table

我一直坚持创建表格。

以下是我如何使代码在loan_type中工作以编写办公室工作人员或非办公室工作人员的代码

create table loaner 
(
   loan_id number(5) primary key,
   loan_type VARCHAR2 (16),
   loan_start_date date,
   loan_end_date date,
)

create table office_worker 
(
   worker_id number(5) primary_key,
   loan_id number(5) references loaner(loan_id),
   worker_name varchar2(50)
)

create table nonoffice_worker 
(
   nonworker_id number(5) primary_key,
   loan_id number(5) references loaner(loan_id),
   nonworker_name varchar2(50)
);

commit;

2 个答案:

答案 0 :(得分:1)

您无法创建约束来检查现有表结构。一种常见的方法是这样的:

create table loaner (
loan_id number(5) primary key,
loan_type VARCHAR2 (16),
loan_start_date date,
loan_end_date date,
constraint loaner_uk unique (loan_id, loan_type)
);

create table office_worker (
worker_id number(5) primary_key,
loan_id number(5),
loan_type VARCHAR2 (16),
worker_name varchar2(50),
constraint office_worker_loaner_fk foreeign key (loan_id, loan_type) references loaner (loan_id, loan_type),
constraint office_worker_loan_type_chk check (loan_type = 'OFFICE')
);

create table nonoffice_worker (
nonworker_id number(5) primary_key,
loan_id number(5),
loan_type VARCHAR2 (16),
nonworker_name varchar2(50),
constraint nonoffice_worker_loaner_fk foreeign key (loan_id, loan_type) references loaner (loan_id, loan_type),
constraint nonoffice_worker_loan_type_chk check (loan_type = 'NONOFFICE')
);

那是:

  1. 在第一个表中的(load_id,loan_type)中创建一个冗余的UNIQUE约束。
  2. 将loan_type添加到子类型表并将外键基于(loan_id,loan_type)。
  3. 为每个子类型表添加一个检查约束,以确保使用正确的loan_type。

答案 1 :(得分:1)

您还可以向表中添加检查约束,但是您必须检查列loan_type是否仅包含所需的值(office workernon office worker),否则这将不起作用:

alter table loaner add (CONSTRAINT chk_loan_type CHECK 
(loan_type='office worker' or loan_type='non office worker'));