I have one parent table which consists of around 150 columns. I need to get the records from the parent table and insert them into 11 different child tables, which have the column names and data types.
1 回答
Oracle 有一个非常方便的 INSERT ALL 命令可以在这种情况下提供帮助。无条件版本
的语法是:
INSERT ALL
INTO child1( col1, col2, col3 ) VALUES( col1, col2, col3 )
INTO child2 VALUES( col1, col2, col3 )
INTO child3 ( col1, col2, col3 )
INTO child4
SELECT col1, col2, col3
FROM parent
-- WHERE some conditions;
演示链接:--> http://sqlfiddle.com/#!4/3eb62/1
上面的命令使用(在底部)从表中
检索所有行,然后,对于每条检索到的记录,它执行所有陈述。
如果子句也有子句,则只会插入满足这些条件的行。
示例中的查询部分可以有多种形式:parent
SELECT ... FROM ...
INSERT ...
SELECT
WHERE conditions
INSERT
具有明确定义的源表和目标表列的完整形式:
INTO dest_table( destcol1, ... destcolN ) VALUES (sourcecol1, ..., sourcecolN)
仅给出源表中的列的缩短形式
INTO dest_table VALUES (sourcecol1, ..., sourcecolN)
另一种缩短形式,其中仅给出目标表中的列
INTO dest_table( destcol1, ... destcolN )
或最简单的:
INTO dest_table
INSERT ALL
还有一个条件版本:
INSERT ALL
WHEN 1=1 THEN INTO child1( col1, col2, col3 ) VALUES( col1, col2, col3 )
WHEN col1 <> 2 THEN INTO child2 VALUES( col1, col2, col3 )
WHEN col3 < 3 THEN INTO child3 ( col1, col2, col3 )
WHEN col2 = 'rec 3' THEN INTO child4
SELECT col1, col2, col3
FROM parent;
演示链接:---> http://sqlfiddle.com/#!4/e7da3/1
此版本仅在满足 after 子句
指定的条件时才插入行。对于每个选定的行,总是评估所有条件。WHEN
还有另一种条件形式:INSERT FIRST
INSERT FIRST
WHEN col1 >= 4 THEN INTO child1( col1, col2, col3 ) VALUES( col1, col2, col3 )
WHEN col1 >= 3 THEN INTO child2 VALUES( col1, col2, col3 )
WHEN col1 >= 2 THEN INTO child3 ( col1, col2, col3 )
WHEN col1 >= 1 THEN INTO child4
SELECT col1, col2, col3
FROM parent;
演示链接:http
://sqlfiddle.com/#!4/a421e/1
这里,对于每个源行,Oracle 从上到下评估条件,当某些条件为真时,只执行这一条INSERT
语句,并跳过剩余的插入。
- - - - 编辑 - - - -
如何以程序方式执行此操作的示例:
CREATE OR REPLACE PROCEDURE name
AS
BEGIN
INSERT ALL
INTO child1( col1, col2, col3 ) VALUES( col1, col2, col3 )
INTO child2 VALUES( col1, col2, col3 )
INTO child3 ( col1, col2, col3 )
INTO child4
SELECT col1, col2, col3
FROM parent ;
-- if commit is required, place it here
-- COMMIT;
END;
/