要求如下:
创建一个名为findtotalcarmodels的PL / SQL函数,以返回属于特定模型的汽车总数。该函数应具有单个IN参数作为model_name。然后,您应该使用显式光标计算属于该汽车型号的汽车数量并返回最终计数。您不得使用任何隐式游标,表联接,子查询,集合运算符,组函数或SQL函数(例如COUNT)来创建此函数。
到目前为止我提出的代码是:
CREATE OR REPLACE Function findtotalcarmodels
(model_name IN varchar2)
RETURN NUMBER
IS
CURSOR car_count_cur IS
SELECT model_name FROM i_car;
Rec_car_details car_count_cur%ROWTYPE;
BEGIN
OPEN car_count_cur;
LOOP
FETCH car_count_cur INTO Rec_car_details;
EXIT WHEN car_count_cur%NOTFOUND;
END LOOP;
CLOSE car_count_cur;
RETURN Rec_car_details;
END;
我收到以下错误:
Errors for FUNCTION FINDTOTALCARMODELS:
LINE/COL ERROR
15/1 PL/SQL: Statement ignored
15/8 PLS-00382: expression is of wrong type
我在这里做错了什么?
答案 0 :(得分:1)
您正试图从内联函数返回光标,该函数正在寻找返回整数。
每次遍历游标时都需要一个(整数)计数器递增...然后你可以返回它。我没有对此进行测试,但这应该有效:
CREATE OR REPLACE Function findtotalcarmodels
(model_name_in IN varchar2)
RETURN NUMBER
IS
DECLARE counter INTEGER := 0;
CURSOR car_count_cur IS
SELECT model_name FROM i_car WHERE model_name = model_name_in;
Rec_car_details car_count_cur%ROWTYPE;
BEGIN
OPEN car_count_cur;
LOOP
FETCH car_count_cur INTO Rec_car_details;
EXIT WHEN car_count_cur%NOTFOUND;
counter := counter + 1;
END LOOP;
CLOSE car_count_cur;
RETURN counter;
END;
答案 1 :(得分:1)
CREATE OR REPLACE FUNCTION findtotalcarmodels (vc_model_name IN VARCHAR2)
RETURN NUMBER
AS
CURSOR c1
IS
SELECT *
FROM i_car
WHERE UPPER (model_name) = UPPER (vc_model_name);
cnt NUMBER;
BEGIN
cnt := 0;
FOR i IN c1 LOOP
cnt := cnt + 1;
END LOOP;
RETURN cnt;
END;
您可以签入双表,例如,
SELECT findtotalcarmodels('SUV1') FROM DUAL; -- here suv1 is your modelname