我有两个表,一个叫做emp\u info的父表和一个叫做emp\u attention的子表,它们由empid连接。
目前,我使用两个不同的序列,每个表一个序列来创建empid。对于empèu考勤表,我创建了一个具有空值的记录,然后使用随机日期时间字段插入或更新。ses代码如下。
我想去掉emp\u attention seq序列和合并代码,执行嵌套插入或使用emp\u info表中的empid来填充emp\u attention表。
你能为我的要求提供解决办法吗。
投放序列emp\ U info\ seq;删除表emp\u info;投放顺序emp\ U seq;员工考勤表;
Create sequence emp_info_seq;
CREATE TABLE emp_info(
empid INTEGER,
empname VARCHAR2(50)
);
INSERT INTO emp_info
SELECT emp_info_seq.NEXTVAL,
DBMS_RANDOM.string('U',
DBMS_RANDOM.value(3,15))
FROM dual
CONNECT BY LEVEL <=3;
Create sequence
emp_attendance_seq;
CREATE TABLE emp_attendance
(empid INTEGER,
start_date DATE,
end_date DATE );
INSERT INTO emp_attendance
(empid)
SELECT
emp_attendance_seq.NEXTVAL
FROM dual
CONNECT BY LEVEL <= 3 ;
MERGE INTO emp_attendance dst
USING (
WITH cntr (n) AS
(
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <=5
)
, got_start_date (rid, empid, start_date) AS
(
SELECT CASE
WHEN cntr.n = 1
THEN e.ROWID
END
, e.empid
, trunc(sysdate)
+ dbms_random.value (1, 30)
FROM emp_attendance e
CROSS JOIN cntr
WHERE e.start_date IS NULL
)
SELECT rid
, empid
, start_date
, start_date + dbms_random.value (0, .75) AS end_date
FROM got_start_date
) src
ON (dst.ROWID = src.rid)
WHEN MATCHED THEN UPDATE
SET dst.start_date = src.start_date
, dst.end_date = src.end_date
WHEN NOT MATCHED THEN.
INSERT (dst.empid, dst.start_date, dst.end_date)
VALUES (src.empid, src.start_date, src.end_date)
;
/
EMPID START_DATE END_DATE
1 20200603 20:06:47 20200603 21:51:02
1 20200611 08:07:12 20200611 20:34:13
1 20200614 10:24:01 20200614 17:16:12
2 20200616 04:50:04 20200616 19:08:22
2 20200608 19:39:52 20200608 21:01:01
2 20200613 00:56:53 20200613 08:23:10
3 20200615 13:46:58 20200616 01:30:50
3 20200621 03:15:32 20200621 07:54:38
3 20200613 04:13:58 20200613 06:38:28
1条答案
按热度按时间6jjcrrmo1#
我已经在某处回答了类似的问题,但找不到。我的建议是使用
insert all
. 下面的示例在第一个表中生成3行,在子表中为每个行生成5行:D小提琴
编辑:我会尽我所能,一步一步地解释。这是我们的主查询,它生成15行包含随机数据:
insert all
when rn = 1 then into emp_info (empid, empname) values (id, name)
when 1 = 1 then into emp_attendance (empid, start_date, end_date)
values (id, d1, d1 + dbms_random.value (0, .75))