这个PL / SQL块代码有什么问题?

时间:2014-02-22 21:50:20

标签: sql plsql oracle11g

我的数据库中有3个表:

manufacturer: IDm int primary key, manufacturerName varchar.

car: IDc int primary key, manufacturer foreign key references manufacturer(IDm).

rent: IDr int primary key, car foreign key references car(IDc).

我想为每个制造商创建一个打印出来的程序:制造商生产的汽车数量,以及制造商生产的租车数量。

这是我的代码:

create or replace procedure Q8 as 
cursor c is select distinct manufacturername, IDm from manufacturer; 
cursor c2 is select * from car; 
rents int:=0; 
cars int; 
allrents int; 
p1 number(38,2); 
p2 number(38, 2); 
id int;  
begin 
   select count(IDr) into allrents from rent; 
   dbms_output.put_line('manufacturer cars rented cars % rents %'); 
   for k in c loop 
     select count(IDc) into cars from car c where c.manufacturer=k.IDm; 
     for k2 in c2 loop 
         select IDc into id from car where car.manufacturer=k.IDm;
         select count(car) into rents from rent r where r.car=id;
     end loop; 
     p1:=(rents/cars)*100; 
     p2:=(rents/allrents)*100; 
     dbms_output.put_line(k.manufacturerName||' '||cars||' '||p1||' '||p2); 
  end loop; 
end;

那么,我的代码中哪里出错?

2 个答案:

答案 0 :(得分:2)

你真的不需要游标来实现这个目标

select manufacturername, IDm, count(cars.IDC) as CarsMade,
                              count(rent.car) as Rental,
                              count(rent.car)/count(cars.IDC) as p1,
                              count(rent.car)/xx.Tot as p2
from manufacturer m
join cars on cars.manufacturer=m.IDm;
join rent on rent.car=car.id
join (select count(*) as Tot from Rent) xx

查看该查询是否为您提供所需内容,它的运行速度比嵌套游标快得多

答案 1 :(得分:0)

收听OldProgrammer - 在第二个循环之前输入一个if。
如果汽车!= 0,则执行第二次循环
其他租金也是0,只是设置它。
您还必须更改p1语句,因为(0/0)* 100将抛出除以零的错误 p2也将和(0 / allrents)* 100始终为0。

相关问题