如何在oracle的第二个表中插入第一个表的运行时值?

时间:2018-10-23 04:13:58

标签: sql oracle oracle11g

我有表格A列在下面

> id, name, salary
> 
> Max+1(10) ,'aa',100 max+1(11), 'bb',200 . .like that i have 10 record
> is there . Max+(21),'xx',1000

现在可以毫无问题地插入10行。

第二张表如下

p_id,age,id

p_id max+1 (41) ,30,(here i need to insert same id from A table 1st record(Max+1(10)))
p_id max+1 (42) ,31,(here i need to insert same id from A table 2nd record(Max+1(11)))
p_id max+1 (43) ,32,(here i need to insert same id from A table 3rd record(Max+1(12)))
.
.
.
.

同样,我需要在循环中插入10行。谢谢。

1 个答案:

答案 0 :(得分:1)

使用存储过程,但不要获取MAX()+1值,请使用序列:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table1 (
  id      NUMBER(20,0) PRIMARY KEY,
  name    VARCHAR2(200),
  salary  NUMBER(12,2)
)
/

CREATE TABLE table2 (
  p_id    NUMBER(20,0) PRIMARY KEY,
  age     NUMBER(3,0),
  id      NUMBER(20,0) REFERENCES table1 (id)
)
/

CREATE SEQUENCE table1__id__seq
/
CREATE SEQUENCE table2__p_id__seq
/

CREATE PROCEDURE add_Details(
  in_name   TABLE1.NAME%TYPE,
  in_salary TABLE1.SALARY%TYPE,
  in_age    TABLE2.AGE%TYPE
)
IS
  p_id TABLE1.ID%TYPE;
BEGIN
  INSERT INTO table1 ( id, name, salary )
  VALUES ( table1__id__seq.NEXTVAL, in_name, in_salary )
  RETURNING id INTO p_id;

  INSERT INTO table2 ( p_id, age, id )
  VALUES ( table2__p_id__seq.NEXTVAL, in_age, p_id );
END;
/

查询1

BEGIN
  add_Details( 'aa', 100, 30 );
  add_Details( 'bb', 200, 31 );
  add_Details( 'cc', 300, 32 );
END;

查询2

SELECT * FROM table1

Results

| ID | NAME | SALARY |
|----|------|--------|
|  1 |   aa |    100 |
|  2 |   bb |    200 |
|  3 |   cc |    300 |

查询3

SELECT * FROM table2

Results

| P_ID | AGE | ID |
|------|-----|----|
|    1 |  30 |  1 |
|    2 |  31 |  2 |
|    3 |  32 |  3 |