我正在上课关于数据库。我很陌生,所以请原谅我这是一个明显的错误,但我一直在研究这个问题好几个小时,不知道还能做些什么。
代码是为了创建一个函数
A.)输出参数给出的一年的平均netwin
(由公式(SeasonW-Seasonl)+(PlayoffW-PlayoffL)给出
B.)输出所有具有netwin超过平均值的教练
C.)返回符合此标准的教练数量
D.)有一个匿名块调用此函数,并根据函数的返回输出两个不同的消息。
现在我已成功完成了A,C和D部分。但由于某些原因,当我插入B部分时,我的函数不会被创建。
create or replace function GOOD_COACHES(season IN INT)
return INT
IS
netwin INT;
CNT INT;
BEGIN
--Calculated netwin
select AVG((SEASON_WIN-SEASON_LOSS) + (PLAYOFF_WIN-PLAYOFF_LOSS)) into netwin from COACHESSEASON where YEAR = season;
--Prints out A
dbms_output.put_line('Average Netwin is: ' || netwin);
--This Line messes up the function, I don't know why
select T.FIRSTNAME, T.LASTNAME from COACHESSEASON T where ((T.SEASON_WIN-T.SEASON_LOSS) + (T.PLAYOFF_WIN-T.PLAYOFF_LOSS))>netwin and YEAR = season;
--Calculates the number of teams that satisfy average
select count(T.FIRSTNAME) into CNT from COACHESSEASON T where ((T.SEASON_WIN-T.SEASON_LOSS) + (T.PLAYOFF_WIN-T.PLAYOFF_LOSS))>netwin and YEAR = season;
return CNT;
END;
--End of the Function
--Start of the Anonymous Block
DECLARE
x int := GOOD_COACHES(1998);
BEGIN
if x = 0 then dbms_output.put_line('We didn''t find any good_coaches!');
else dbms_output.put_line('The No. of good coaches is ' || x);
end if;
END;
/
函数中的第三行会混淆它并且不允许它被调用。如果我评论它,它可以正常工作。 当我将它从函数中取出并将其转换为常规SQL语句时,它就可以工作。
select T.FIRSTNAME, T.LASTNAME from COACHESSEASON T where ((T.SEASON_WIN-T.SEASON_LOSS) + (T.PLAYOFF_WIN-T.PLAYOFF_LOSS))>0 and YEAR = /*RandYear*/;
如果有人理解为什么无法使用该行创建该函数,我将不胜感激。我也不知道如何在函数中打印出所选行的结果。
答案 0 :(得分:0)
您没有将T.FIRSTNAME
和T.LASTNAME
选择为任何内容,因此该语句无法包含在PL / SQL块中。
可能会有多个“好教练”,因此您无法将值放入单个变量中,并且必须使用游标或集合。
使用集合,如果您创建表类型以将名字和姓氏收集到:
CREATE TYPE VARCHAR2s_Table AS TABLE OF VARCHAR2(30);
/
然后你可以用它来收集名字和姓氏(作为奖励,收集大小会告诉你有多少好教练,你可以跳过最后一个查询):
create or replace function GOOD_COACHES(season IN INT)
return INT
IS
netwin INT;
CNT INT;
firstnames VARCHAR2s_Table;
lastnames VARCHAR2s_Table;
BEGIN
--Calculated netwin
select AVG((SEASON_WIN-SEASON_LOSS) + (PLAYOFF_WIN-PLAYOFF_LOSS))
into netwin
from COACHESSEASON
where YEAR = season;
--Prints out A
dbms_output.put_line('Average Netwin is: ' || netwin);
--This Line messes up the function, I don't know why
select T.FIRSTNAME, T.LASTNAME
BULK COLLECT INTO firstnames, lastnames
from COACHESSEASON T
where ((T.SEASON_WIN-T.SEASON_LOSS) + (T.PLAYOFF_WIN-T.PLAYOFF_LOSS))>netwin
and YEAR = season;
FOR i IN 1 .. firstnames.COUNT LOOP
DBMS_OUTPUT.put_line( firstnames(i) || ' ' || lastnames(i) );
END LOOP;
return firstnames.COUNT;
END;
/