我有两张桌子。 Order_header和Order_detail。对于Order_header表中的每一行,我想生成一个或多个Order_detail行并将它们插入Order_detail表中。每个标题行的详细信息行数是随机的,直到常量max_detailrows中的数字。如何继续为Order_detail表生成行?
答案 0 :(得分:0)
您可以使用DBMS_RANDOM.VALUE函数来生成随机值。 在hierarchical query中使用此选项可为Order_Header表中的每一行生成行。
架构设置:
create table order_header(
order_id number,
order_desc varchar2(10)
);
insert into order_header values(1,'lorem');
insert into order_header values(2,'ewroc');
insert into order_header values(3,'tdsfg');
commit;
create table order_details(
order_id number,
order_detail_nr number,
order_detail_desc varchar2(20)
);
查询:
insert into order_details
select
order_id,
level,
order_desc || '_' || level
from order_header
connect by level <= dbms_random.value(1,7) --max number of rows needed should be given here.
and prior order_id = order_id
and prior sys_guid() is not null;
输出:
select * from order_details
order by 1,2;
ORDER_ID ORDER_DETAIL_NR ORDER_DETAIL_DESC
---------- --------------- ------------------
1 1 lorem_1
1 2 lorem_2
1 3 lorem_3
2 1 ewroc_1
2 2 ewroc_2
2 3 ewroc_3
2 4 ewroc_4
3 1 tdsfg_1