需要使用Foreign和Primary键填充表

时间:2018-06-07 09:17:08

标签: oracle foreign-keys primary-key oracle12c

我需要从all_tab_col系统表创建三个表,以便架构详细信息在一个schema_detail table中,表详细信息在table_detail表中,列详细信息在col_table中。这三个表将通过存储过程同时填充,PK(generated using SEQUENCE)中的schema_detailFK表中为table_detail,在PK(generated using SEQUENCE)中为table_detailFK中为col_detail table

2 个答案:

答案 0 :(得分:1)

SQL是一种基于集合的语言,因此我很想通过三个基本步骤来解决您的任务。

一些模拟表(只需为您感兴趣的详细信息添加列):

CREATE TABLE schema_detail (
  schema_id    NUMBER              GENERATED ALWAYS AS IDENTITY NOT NULL,
  schema_name  VARCHAR2(128 BYTE)  NOT NULL,
  CONSTRAINT schema_detail_pk PRIMARY KEY (schema_id)
);

CREATE TABLE table_detail (
  schema_id   NUMBER,
  table_id    NUMBER              GENERATED ALWAYS AS IDENTITY NOT NULL,
  table_name  VARCHAR2(128 BYTE)  NOT NULL,
  CONSTRAINT table_detail_pk PRIMARY KEY (table_id),
  CONSTRAINT table_detail_fk FOREIGN KEY (schema_id) 
    REFERENCES schema_detail(schema_id)
     ON DELETE CASCADE
);

CREATE INDEX table_detail_schema_idx ON table_detail(schema_id);
CREATE INDEX table_detail_name_idx ON table_detail(table_name);

CREATE TABLE col_detail (
  table_id   NUMBER,
  col_id     NUMBER              GENERATED ALWAYS AS IDENTITY NOT NULL,
  col_name   VARCHAR2(128 BYTE)  NOT NULL,
  CONSTRAINT col_detail_pk PRIMARY KEY (col_id),
  CONSTRAINT col_detail_fk FOREIGN KEY (table_id) 
    REFERENCES table_detail(table_id)
     ON DELETE CASCADE
);

CREATE INDEX col_detail ON col_detail(table_id);

我先填写表格schema_detail。 PK自动生成:

INSERT INTO schema_detail(schema_name)
SELECT DISTINCT c.owner FROM all_tab_columns c ORDER BY owner;

SCHEMA_ID SCHEMA_NAME
1         APPQOSSYS
2         AUDSYS
3         CTXSYS
...

接下来,我填写表格。需要在schema_detail表中查找schema_id。同样,我们让PK自动生成:

INSERT INTO table_detail(schema_id, table_name)
SELECT DISTINCT s.schema_id, c.table_name 
  FROM all_tab_columns c
  JOIN schema_detail s ON c.owner = s.schema_name
 ORDER BY table_name;

SCHEMA_ID TABLE_ID TABLE_NAME
1         8403     WLM_CLASSIFIER_PLAN
1         8404     WLM_FEATURE_USAGE
1         8405     WLM_METRICS_STREAM
...

最后,我填写了这些专栏:

INSERT INTO col_detail(table_id, col_name)
SELECT DISTINCT t.table_id, c.column_name 
  FROM all_tab_columns c
  JOIN table_detail    t ON c.table_name = t.table_name
  JOIN schema_detail   s ON c.owner = s.schema_name
 ORDER BY s.schema_id, t.table_id, c.column_name;

这是解决您的问题还是需要PL / SQL程序?

答案 1 :(得分:1)

如果您坚持使用PL / SQL存储过程,我会按照以下行编写代码:

elasticClient.GetMapping(new GetMappingRequest())