create table cow(cow_id varchar2(32),age int);
--假设开始时 1头,5年后,就有两头母牛:
--20年后,13头:
SQL>
SQL> declare
2l_count int :=0;
3begin
4delete from cow;
5
6for i in 0..floor(20/5) loop
7
8if i=0 then
9insert into cow values (sys_guid(),0);
10else
11
12for j in (select cow_id from cow where age =5;--计算本年5岁及以上的牛有多少
update niu a set a.age=a.age+1;--进入下一年
for d in 1..j loop
insert into niu values(1,0);--新生小牛数量等于本年5岁及以上母牛的数量
end loop;
execute immediate 'delete from niu where age > 15'; --母牛达到16岁时死亡
end loop;
commit;
select count(*) into c from niu;
dbms_output.put_line(c);
end;
solomon_007 发表于 2019-8-23 10:37
你的很多条件比较模糊,我算的 15年,牛就死了
感谢回复具体一下条件 5岁的时候就可以生小牛,也就是说,去年4岁的小牛,今年5岁,今年就可以生一头小牛,16岁死亡即年龄大于15 ,15岁的时候会生小牛,
我又完善了一下 如下:
create table niu(a number,age number);
truncate table niu;
insert into niu values(1,5);
commit;
select * from niu;
declare
j number;
c number;
begin
insert into niu values(1,0);--第一年出生一头
for i in 1..19 loop --第二年开始判断是否有小牛出生
update niu a set a.age=a.age+1;
execute immediate 'delete from niu where age > 15'; --移除死亡的母牛(年龄大于15岁的)
select count(*) into j from niu where age>=5; --该年有多少头小牛出生
for d in 1..j loop
insert into niu values(1,0);
end loop;
end loop;
select count(*) into c from niu;
dbms_output.put_line(c);
end;